Release 4.29
[org-mode.git] / org.el
blob19a2c475ac5edc24b8d02d4b2aadfa7453c317d8
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.29
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around 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.
44 ;; Installation
45 ;; ------------
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
72 ;; name is.
74 ;; Documentation
75 ;; -------------
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.10:
83 ;; ---------------------------
84 ;; Version 4.29
85 ;; - Inlining images in HTML export now depends on wheather the link
86 ;; contains a description or not.
87 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
88 ;; - TODO items already scheduled can be made to disappear from the global
89 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
90 ;; - In Tables, formulas may also be Lisp forms.
91 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
92 ;; for all available exporters.
93 ;; - Bug fixes, lots of them :-(
95 ;; Version 4.28
96 ;; - Bug fixes.
98 ;; Version 4.27
99 ;; - HTML exporter generalized to receive external options.
100 ;; As part of the process, author, email and date have been moved to the
101 ;; end of the HTML file.
102 ;; - Support for customizable file search in file links.
103 ;; - BibTeX database links as first application of the above.
104 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
105 ;; entries that are sublevels of another TODO entry.
107 ;; Version 4.26
108 ;; - Bug fixes.
110 ;; Version 4.25
111 ;; - Revision of the font-lock faces section, with better tty support.
112 ;; - TODO keywords in Agenda buffer are fontified.
113 ;; - Export converts links between .org files to links between .html files.
114 ;; - Better support for bold/italic/underline emphasis.
116 ;; Version 4.24
117 ;; - Bug fixes.
119 ;; Version 4.23
120 ;; - Bug fixes.
122 ;; Version 4.22
123 ;; - Bug fixes.
124 ;; - In agenda buffer, mouse-1 no longer follows link.
125 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
127 ;; Version 4.20
128 ;; - Links use now the [[link][description]] format by default.
129 ;; When inserting links, the user is prompted for a description.
130 ;; - If a link has a description, only the description is displayed
131 ;; the link part is hidden. Use C-c C-l to edit the link part.
132 ;; - TAGS are now bold, but in the same color as the headline.
133 ;; - The width of a table column can be limited by using a field "<N>".
134 ;; - New structure for the customization tree.
135 ;; - Bug fixes.
137 ;; Version 4.13
138 ;; - The list of agenda files can be maintainted in an external file.
139 ;; - Bug fixes.
141 ;; Version 4.12
142 ;; - Templates for remember buffer. Note that the remember setup changes.
143 ;; To set up templates, see `org-remember-templates'.
144 ;; - The time in new time stamps can be rounded, see new option
145 ;; `org-time-stamp-rounding-minutes'.
146 ;; - Bug fixes (there are *always* more bugs).
148 ;;; Code:
150 (eval-when-compile
151 (require 'cl)
152 (require 'calendar))
153 (require 'outline)
154 (require 'time-date)
155 (require 'easymenu)
157 (defvar calc-embedded-close-formula) ; defined by the calc package
158 (defvar calc-embedded-open-formula) ; defined by the calc package
159 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
161 ;;; Customization variables
163 (defvar org-version "4.29"
164 "The version number of the file org.el.")
165 (defun org-version ()
166 (interactive)
167 (message "Org-mode version %s" org-version))
169 ;; The following constant is for compatibility with different versions
170 ;; of outline.el.
171 (defconst org-noutline-p (featurep 'noutline)
172 "Are we using the new outline mode?")
173 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
174 (defconst org-format-transports-properties-p
175 (let ((x "a"))
176 (add-text-properties 0 1 '(test t) x)
177 (get-text-property 0 'test (format "%s" x)))
178 "Does format transport text properties?")
180 (defgroup org nil
181 "Outline-based notes management and organizer."
182 :tag "Org"
183 :group 'outlines
184 :group 'hypermedia
185 :group 'calendar)
187 (defgroup org-startup nil
188 "Options concerning startup of Org-mode."
189 :tag "Org Startup"
190 :group 'org)
192 (defcustom org-startup-folded t
193 "Non-nil means, entering Org-mode will switch to OVERVIEW.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
197 #+STARTUP: fold
198 #+STARTUP: nofold
199 #+STARTUP: content"
200 :group 'org-startup
201 :type '(choice
202 (const :tag "nofold: show all" nil)
203 (const :tag "fold: overview" t)
204 (const :tag "content: all headlines" content)))
206 (defcustom org-startup-truncated t
207 "Non-nil means, entering Org-mode will set `truncate-lines'.
208 This is useful since some lines containing links can be very long and
209 uninteresting. Also tables look terrible when wrapped."
210 :group 'org-startup
211 :type 'boolean)
213 (defcustom org-startup-align-all-tables nil
214 "Non-nil means, align all tables when visiting a file.
215 This is useful when the column width in tables is forced with <N> cookies
216 in table fields. Such tables will look correct only after the first re-align.
217 This can also be configured on a per-file basis by adding one of
218 the following lines anywhere in the buffer:
219 #+STARTUP: align
220 #+STARTUP: noalign"
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-with-deadline-check nil
225 "Non-nil means, entering Org-mode will run the deadline check.
226 This means, if you start editing an org file, you will get an
227 immediate reminder of any due deadlines.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: dlcheck
231 #+STARTUP: nodlcheck"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-CUA-compatible nil
246 "Non-nil means use alternative key bindings for S-<cursor movement>.
247 Org-mode used S-<cursor movement> for changing timestamps and priorities.
248 S-<cursor movement> is also used for example by `CUA-mode' to select text.
249 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
250 alternative bindings. Setting this variable to t will replace the following
251 keys both in Org-mode and in the Org-agenda buffer.
253 S-RET -> C-S-RET
254 S-up -> M-p
255 S-down -> M-n
256 S-left -> M--
257 S-right -> M-+
259 If you do not like the alternative keys, take a look at the variable
260 `org-disputed-keys'.
262 This option is only relevant at load-time of Org-mode. Changing it requires
263 a restart of Emacs to become effective."
264 :group 'org-startup
265 :type 'boolean)
267 (defvar org-disputed-keys
268 '((S-up [(shift up)] [(meta ?p)])
269 (S-down [(shift down)] [(meta ?n)])
270 (S-left [(shift left)] [(meta ?-)])
271 (S-right [(shift right)] [(meta ?+)])
272 (S-return [(shift return)] [(control shift return)]))
273 "Keys for which Org-mode and other modes compete.
274 This is an alist, cars are symbols for lookup, 1st element is the default key,
275 second element will be used when `org-CUA-compatible' is t.")
277 (defun org-key (key)
278 "Select a key according to `org-CUA-compatible'."
279 (nth (if org-CUA-compatible 2 1)
280 (or (assq key org-disputed-keys)
281 (error "Invalid Key %s in `org-key'" key))))
283 (defcustom org-ellipsis nil
284 "The ellipsis to use in the Org-mode outline.
285 When nil, just use the standard three dots. When a string, use that instead,
286 and just in Org-mode (which will then use its own display table).
287 Changing this requires executing `M-x org-mode' in a buffer to become
288 effective."
289 :group 'org-startup
290 :type '(choice (const :tag "Default" nil)
291 (string :tag "String" :value "...#")))
293 (defvar org-display-table nil
294 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
296 (defgroup org-keywords nil
297 "Keywords in Org-mode."
298 :tag "Org Keywords"
299 :group 'org)
301 (defcustom org-deadline-string "DEADLINE:"
302 "String to mark deadline entries.
303 A deadline is this string, followed by a time stamp. Should be a word,
304 terminated by a colon. You can insert a schedule keyword and
305 a timestamp with \\[org-deadline].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
310 (defcustom org-scheduled-string "SCHEDULED:"
311 "String to mark scheduled TODO entries.
312 A schedule is this string, followed by a time stamp. Should be a word,
313 terminated by a colon. You can insert a schedule keyword and
314 a timestamp with \\[org-schedule].
315 Changes become only effective after restarting Emacs."
316 :group 'org-keywords
317 :type 'string)
319 (defcustom org-closed-string "CLOSED:"
320 "String used as the prefix for timestamps logging closing a TODO entry."
321 :group 'org-keywords
322 :type 'string)
324 (defcustom org-comment-string "COMMENT"
325 "Entries starting with this keyword will never be exported.
326 An entry can be toggled between COMMENT and normal with
327 \\[org-toggle-comment].
328 Changes become only effective after restarting Emacs."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-quote-string "QUOTE"
333 "Entries starting with this keyword will be exported in fixed-width font.
334 Quoting applies only to the text in the entry following the headline, and does
335 not extend beyond the next headline, even if that is lower level.
336 An entry can be toggled between QUOTE and normal with
337 \\[org-toggle-fixed-width-section]."
338 :group 'org-keywords
339 :type 'string)
341 (defgroup org-structure nil
342 "Options concerning the general structure of Org-mode files."
343 :tag "Org Structure"
344 :group 'org)
346 (defgroup org-cycle nil
347 "Options concerning visibility cycling in Org-mode."
348 :tag "Org Cycle"
349 :group 'org-structure)
351 (defcustom org-cycle-emulate-tab t
352 "Where should `org-cycle' emulate TAB.
353 nil Never
354 white Only in completely white lines
355 t Everywhere except in headlines"
356 :group 'org-cycle
357 :type '(choice (const :tag "Never" nil)
358 (const :tag "Only in completely white lines" white)
359 (const :tag "Everywhere except in headlines" t)
362 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
363 "Hook that is run after `org-cycle' has changed the buffer visibility.
364 The function(s) in this hook must accept a single argument which indicates
365 the new state that was set by the most recent `org-cycle' command. The
366 argument is a symbol. After a global state change, it can have the values
367 `overview', `content', or `all'. After a local state change, it can have
368 the values `folded', `children', or `subtree'."
369 :group 'org-cycle
370 :type 'hook)
372 (defgroup org-edit-structure nil
373 "Options concerning structure editing in Org-mode."
374 :tag "Org Edit Structure"
375 :group 'org-structure)
377 (defcustom org-odd-levels-only nil
378 "Non-nil means, skip even levels and only use odd levels for the outline.
379 This has the effect that two stars are being added/taken away in
380 promotion/demotion commands. It also influences how levels are
381 handled by the exporters.
382 Changing it requires restart of `font-lock-mode' to become effective
383 for fontification also in regions already fontified.
384 You may also set this on a per-file basis by adding one of the following
385 lines to the buffer:
387 #+STARTUP: odd
388 #+STARTUP: oddeven"
389 :group 'org-edit-structure
390 :group 'org-font-lock
391 :type 'boolean)
393 (defcustom org-adapt-indentation t
394 "Non-nil means, adapt indentation when promoting and demoting.
395 When this is set and the *entire* text in an entry is indented, the
396 indentation is increased by one space in a demotion command, and
397 decreased by one in a promotion command. If any line in the entry
398 body starts at column 0, indentation is not changed at all."
399 :group 'org-edit-structure
400 :type 'boolean)
402 (defcustom org-insert-heading-hook nil
403 "Hook being run after inserting a new heading."
404 :group 'org-edit-structure
405 :type 'boolean)
407 (defcustom org-enable-fixed-width-editor t
408 "Non-nil means, lines starting with \":\" are treated as fixed-width.
409 This currently only means, they are never auto-wrapped.
410 When nil, such lines will be treated like ordinary lines.
411 See also the QUOTE keyword."
412 :group 'org-edit-structure
413 :type 'boolean)
415 (defgroup org-sparse-trees nil
416 "Options concerning sparse trees in Org-mode."
417 :tag "Org Sparse Trees"
418 :group 'org-structure)
420 (defcustom org-highlight-sparse-tree-matches t
421 "Non-nil means, highlight all matches that define a sparse tree.
422 The highlights will automatically disappear the next time the buffer is
423 changed by an edit command."
424 :group 'org-sparse-trees
425 :type 'boolean)
427 (defcustom org-show-hierarchy-above t
428 "Non-nil means, show full hierarchy when showing a spot in the tree.
429 Turning this off makes sparse trees more compact, but also less clear."
430 :group 'org-sparse-trees
431 :type 'boolean)
433 (defcustom org-show-following-heading t
434 "Non-nil means, show heading following match in `org-occur'.
435 When doing an `org-occur' it is useful to show the headline which
436 follows the match, even if they do not match the regexp. This makes it
437 easier to edit directly inside the sparse tree. However, if you use
438 `org-occur' mainly as an overview, the following headlines are
439 unnecessary clutter."
440 :group 'org-sparse-trees
441 :type 'boolean)
443 (defcustom org-occur-hook '(org-first-headline-recenter)
444 "Hook that is run after `org-occur' has constructed a sparse tree.
445 This can be used to recenter the window to show as much of the structure
446 as possible."
447 :group 'org-sparse-trees
448 :type 'hook)
450 (defgroup org-plain-lists nil
451 "Options concerning plain lists in Org-mode."
452 :tag "Org Plain lists"
453 :group 'org-structure)
455 (defcustom org-cycle-include-plain-lists nil
456 "Non-nil means, include plain lists into visibility cycling.
457 This means that during cycling, plain list items will *temporarily* be
458 interpreted as outline headlines with a level given by 1000+i where i is the
459 indentation of the bullet. In all other operations, plain list items are
460 not seen as headlines. For example, you cannot assign a TODO keyword to
461 such an item."
462 :group 'org-plain-lists
463 :type 'boolean)
466 (defcustom org-plain-list-ordered-item-terminator t
467 "The character that makes a line with leading number an ordered list item.
468 Valid values are ?. and ?\). To get both terminators, use t. While
469 ?. may look nicer, it creates the danger that a line with leading
470 number may be incorrectly interpreted as an item. ?\) therefore is
471 the safe choice."
472 :group 'org-plain-lists
473 :type '(choice (const :tag "dot like in \"2.\"" ?.)
474 (const :tag "paren like in \"2)\"" ?\))
475 (const :tab "both" t)))
477 (defcustom org-auto-renumber-ordered-lists t
478 "Non-nil means, automatically renumber ordered plain lists.
479 Renumbering happens when the sequence have been changed with
480 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
481 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
482 :group 'org-plain-lists
483 :type 'boolean)
485 (defgroup org-archive nil
486 "Options concerning archiving in Org-mode."
487 :tag "Org Archive"
488 :group 'org-structure)
490 (defcustom org-archive-location "%s_archive::"
491 "The location where subtrees should be archived.
492 This string consists of two parts, separated by a double-colon.
494 The first part is a file name - when omitted, archiving happens in the same
495 file. %s will be replaced by the current file name (without directory part).
496 Archiving to a different file is useful to keep archived entries from
497 contributing to the Org-mode Agenda.
499 The part after the double colon is a headline. The archived entries will be
500 filed under that headline. When omitted, the subtrees are simply filed away
501 at the end of the file, as top-level entries.
503 Here are a few examples:
504 \"%s_archive::\"
505 If the current file is Projects.org, archive in file
506 Projects.org_archive, as top-level trees. This is the default.
508 \"::* Archived Tasks\"
509 Archive in the current file, under the top-level headline
510 \"* Archived Tasks\".
512 \"~/org/archive.org::\"
513 Archive in file ~/org/archive.org (absolute path), as top-level trees.
515 \"basement::** Finished Tasks\"
516 Archive in file ./basement (relative path), as level 3 trees
517 below the level 2 heading \"** Finished Tasks\".
519 You may set this option on a per-file basis by adding to the buffer a
520 line like
522 #+ARCHIVE: basement::** Finished Tasks"
523 :group 'org-archive
524 :type 'string)
526 (defcustom org-archive-mark-done t
527 "Non-nil means, mark archived entries as DONE."
528 :group 'org-archive
529 :type 'boolean)
531 (defcustom org-archive-stamp-time t
532 "Non-nil means, add a time stamp to archived entries.
533 The time stamp will be added directly after the TODO state keyword in the
534 first line, so it is probably best to use this in combinations with
535 `org-archive-mark-done'."
536 :group 'org-archive
537 :type 'boolean)
539 (defgroup org-table nil
540 "Options concerning tables in Org-mode."
541 :tag "Org Table"
542 :group 'org)
544 (defcustom org-enable-table-editor 'optimized
545 "Non-nil means, lines starting with \"|\" are handled by the table editor.
546 When nil, such lines will be treated like ordinary lines.
548 When equal to the symbol `optimized', the table editor will be optimized to
549 do the following:
550 - Use automatic overwrite mode in front of whitespace in table fields.
551 This make the structure of the table stay in tact as long as the edited
552 field does not exceed the column width.
553 - Minimize the number of realigns. Normally, the table is aligned each time
554 TAB or RET are pressed to move to another field. With optimization this
555 happens only if changes to a field might have changed the column width.
556 Optimization requires replacing the functions `self-insert-command',
557 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
558 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
559 very good at guessing when a re-align will be necessary, but you can always
560 force one with \\[org-ctrl-c-ctrl-c].
562 If you would like to use the optimized version in Org-mode, but the
563 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
565 This variable can be used to turn on and off the table editor during a session,
566 but in order to toggle optimization, a restart is required.
568 See also the variable `org-table-auto-blank-field'."
569 :group 'org-table
570 :type '(choice
571 (const :tag "off" nil)
572 (const :tag "on" t)
573 (const :tag "on, optimized" optimized)))
575 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
576 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
577 In the optimized version, the table editor takes over all simple keys that
578 normally just insert a character. In tables, the characters are inserted
579 in a way to minimize disturbing the table structure (i.e. in overwrite mode
580 for empty fields). Outside tables, the correct binding of the keys is
581 restored.
583 The default for this option is t if the optimized version is also used in
584 Org-mode. See the variable `org-enable-table-editor' for details. Changing
585 this variable requires a restart of Emacs to become effective."
586 :group 'org-table
587 :type 'boolean)
589 (defgroup org-table-settings nil
590 "Settings for tables in Org-mode."
591 :tag "Org Table Settings"
592 :group 'org-table)
594 (defcustom org-table-default-size "5x2"
595 "The default size for newly created tables, Columns x Rows."
596 :group 'org-table-settings
597 :type 'string)
599 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
600 "Regular expression for recognizing numbers in table columns.
601 If a table column contains mostly numbers, it will be aligned to the
602 right. If not, it will be aligned to the left.
604 The default value of this option is a regular expression which allows
605 anything which looks remotely like a number as used in scientific
606 context. For example, all of the following will be considered a
607 number:
608 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
610 Other options offered by the customize interface are more restrictive."
611 :group 'org-table-settings
612 :type '(choice
613 (const :tag "Positive Integers"
614 "^[0-9]+$")
615 (const :tag "Integers"
616 "^[-+]?[0-9]+$")
617 (const :tag "Floating Point Numbers"
618 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
619 (const :tag "Floating Point Number or Integer"
620 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
621 (const :tag "Exponential, Floating point, Integer"
622 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
623 (const :tag "Very General Number-Like"
624 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
625 (string :tag "Regexp:")))
627 (defcustom org-table-number-fraction 0.5
628 "Fraction of numbers in a column required to make the column align right.
629 In a column all non-white fields are considered. If at least this
630 fraction of fields is matched by `org-table-number-fraction',
631 alignment to the right border applies."
632 :group 'org-table-settings
633 :type 'number)
635 (defgroup org-table-editing nil
636 "Bahavior of tables during editing in Org-mode."
637 :tag "Org Table Editing"
638 :group 'org-table)
640 (defcustom org-table-automatic-realign t
641 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
642 When nil, aligning is only done with \\[org-table-align], or after column
643 removal/insertion."
644 :group 'org-table-editing
645 :type 'boolean)
647 (defcustom org-table-limit-column-width t ;kw
648 "Non-nil means, allow to limit the width of table columns with <N> fields."
649 :group 'org-table-editing
650 :type 'boolean)
652 (defcustom org-table-auto-blank-field t
653 "Non-nil means, automatically blank table field when starting to type into it.
654 This only happens when typing immediately after a field motion
655 command (TAB, S-TAB or RET).
656 Only relevant when `org-enable-table-editor' is equal to `optimized'."
657 :group 'org-table-editing
658 :type 'boolean)
660 (defcustom org-table-tab-jumps-over-hlines t
661 "Non-nil means, tab in the last column of a table with jump over a hline.
662 If a horizontal separator line is following the current line,
663 `org-table-next-field' can either create a new row before that line, or jump
664 over the line. When this option is nil, a new line will be created before
665 this line."
666 :group 'org-table-editing
667 :type 'boolean)
669 (defcustom org-table-tab-recognizes-table.el t
670 "Non-nil means, TAB will automatically notice a table.el table.
671 When it sees such a table, it moves point into it and - if necessary -
672 calls `table-recognize-table'."
673 :group 'org-table-editing
674 :type 'boolean)
676 (defgroup org-table-calculation nil
677 "Options concerning tables in Org-mode."
678 :tag "Org Table Calculation"
679 :group 'org-table)
681 (defcustom org-table-copy-increment t
682 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
683 :group 'org-table-calculation
684 :type 'boolean)
686 (defcustom org-calc-default-modes
687 '(calc-internal-prec 12
688 calc-float-format (float 5)
689 calc-angle-mode deg
690 calc-prefer-frac nil
691 calc-symbolic-mode nil
692 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
693 calc-display-working-message t
695 "List with Calc mode settings for use in calc-eval for table formulas.
696 The list must contain alternating symbols (Calc modes variables and values).
697 Don't remove any of the default settings, just change the values. Org-mode
698 relies on the variables to be present in the list."
699 :group 'org-table-calculation
700 :type 'plist)
702 (defcustom org-table-formula-evaluate-inline t
703 "Non-nil means, TAB and RET evaluate a formula in current table field.
704 If the current field starts with an equal sign, it is assumed to be a formula
705 which should be evaluated as described in the manual and in the documentation
706 string of the command `org-table-eval-formula'. This feature requires the
707 Emacs calc package.
708 When this variable is nil, formula calculation is only available through
709 the command \\[org-table-eval-formula]."
710 :group 'org-table-calculation
711 :type 'boolean)
714 (defcustom org-table-formula-use-constants t
715 "Non-nil means, interpret constants in formulas in tables.
716 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
717 by the value given in `org-table-formula-constants', or by a value obtained
718 from the `constants.el' package."
719 :group 'org-table-calculation
720 :type 'boolean)
722 (defcustom org-table-formula-constants nil
723 "Alist with constant names and values, for use in table formulas.
724 The car of each element is a name of a constant, without the `$' before it.
725 The cdr is the value as a string. For example, if you'd like to use the
726 speed of light in a formula, you would configure
728 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
730 and then use it in an equation like `$1*$c'."
731 :group 'org-table-calculation
732 :type '(repeat
733 (cons (string :tag "name")
734 (string :tag "value"))))
736 (defcustom org-table-formula-numbers-only nil
737 "Non-nil means, calculate only with numbers in table formulas.
738 Then all input fields will be converted to a number, and the result
739 must also be a number. When nil, calc's full potential is available
740 in table calculations, including symbolics etc."
741 :group 'org-table-calculation
742 :type 'boolean)
744 (defcustom org-table-allow-automatic-line-recalculation t
745 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
746 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
747 :group 'org-table-calculation
748 :type 'boolean)
750 (defgroup org-link nil
751 "Options concerning links in Org-mode."
752 :tag "Org Link"
753 :group 'org)
755 (defcustom org-descriptive-links t
756 "Non-nil means, hide link part and only show description of bracket links.
757 Bracket links are like [[link][descritpion]]. This variable sets the initial
758 state in new org-mode buffers. The setting can then be toggled on a
759 per-buffer basis from the Org->Hyperlinks menu."
760 :group 'org-link
761 :type 'boolean)
763 (defcustom org-link-style 'bracket
764 "The style of links to be inserted with \\[org-insert-link].
765 Possible values are:
766 bracket [[link][description]]. This is recommended
767 plain Description \\n link. The old way, no longer recommended."
768 :group 'org-link
769 :type '(choice
770 (const :tag "Bracket (recommended)" bracket)
771 (const :tag "Plain (no longer recommended)" plain)))
773 (defcustom org-link-format "%s"
774 "Default format for external, URL-like linkes in the buffer.
775 This is a format string for printf, %s will be replaced by the link text.
776 The recommended value is just \"%s\", since links will be protected by
777 enclosing them in double brackets. If you prefer plain links (see variable
778 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
779 additional URL: prefix, so the format would be \"<URL:%s>\"."
780 :group 'org-link
781 :type '(choice
782 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
783 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
784 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
785 (string :tag "Other" :value "<%s>")))
787 (defcustom org-activate-links '(bracket angle plain radio tag date)
788 "Types of links that should be activated in Org-mode files.
789 This is a list of symbols, each leading to the activation of a certain link
790 type. In principle, it does not hurt to turn on most link types - there may
791 be a small gain when turning off unused link types. The types are:
793 bracket The recommended [[link][description]] or [[link]] links with hiding.
794 angular Links in angular brackes that may contain whitespace like
795 <bbdb:Carsten Dominik>.
796 plain Plain links in normal text, no whitespace, like http://google.com.
797 radio Text that is matched by a radio target, see manual for details.
798 tag Tag settings in a headline (link to tag search).
799 date Time stamps (link to calendar).
800 camel CamelCase words defining text searches.
802 Changing this variable requires a restart of Emacs to become effective."
803 :group 'org-link
804 :type '(set (const :tag "Double bracket links (new style)" bracket)
805 (const :tag "Angular bracket links (old style)" angular)
806 (const :tag "plain text links" plain)
807 (const :tag "Radio target matches" radio)
808 (const :tag "Tags" tag)
809 (const :tag "Timestamps" date)
810 (const :tag "CamelCase words" camel)))
812 (defgroup org-link-store nil
813 "Options concerning storing links in Org-mode"
814 :tag "Org Store Link"
815 :group 'org-link)
817 (defcustom org-context-in-file-links t
818 "Non-nil means, file links from `org-store-link' contain context.
819 A search string will be added to the file name with :: as separator and
820 used to find the context when the link is activated by the command
821 `org-open-at-point'.
822 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
823 negates this setting for the duration of the command."
824 :group 'org-link-store
825 :type 'boolean)
827 (defcustom org-file-link-context-use-camel-case nil
828 "Non-nil means, use CamelCase to store a search context in a file link.
829 When nil, the search string simply consists of the words of the string.
830 CamelCase is deprecated, and support for it may be dropped in the future."
831 :group 'org-link-store
832 :type 'boolean)
834 (defcustom org-keep-stored-link-after-insertion nil
835 "Non-nil means, keep link in list for entire session.
837 The command `org-store-link' adds a link pointing to the current
838 location to an internal list. These links accumulate during a session.
839 The command `org-insert-link' can be used to insert links into any
840 Org-mode file (offering completion for all stored links). When this
841 option is nil, every link which has been inserted once using \\[org-insert-link]
842 will be removed from the list, to make completing the unused links
843 more efficient."
844 :group 'org-link-store
845 :type 'boolean)
847 (defcustom org-usenet-links-prefer-google nil
848 "Non-nil means, `org-store-link' will create web links to Google groups.
849 When nil, Gnus will be used for such links.
850 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
851 negates this setting for the duration of the command."
852 :group 'org-link-store
853 :type 'boolean)
855 (defgroup org-link-follow nil
856 "Options concerning following links in Org-mode"
857 :tag "Org Follow Link"
858 :group 'org-link)
860 (defcustom org-tab-follows-link nil
861 "Non-nil means, on links TAB will follow the link.
862 Needs to be set before org.el is loaded."
863 :group 'org-link-follow
864 :type 'boolean)
866 (defcustom org-return-follows-link nil
867 "Non-nil means, on links RET will follow the link.
868 Needs to be set before org.el is loaded."
869 :group 'org-link-follow
870 :type 'boolean)
872 (defcustom org-mouse-1-follows-link t
873 "Non-nil means, mouse-1 on a link will follow the link.
874 A longer mouse click will still set point. Does not wortk on XEmacs.
875 Needs to be set before org.el is loaded."
876 :group 'org-link-follow
877 :type 'boolean)
879 (defcustom org-mark-ring-length 4
880 "Number of different positions to be recorded in the ring
881 Changing this requires a restart of Emacs to work correctly."
882 :group 'org-link-follow
883 :type 'interger)
885 (defcustom org-link-frame-setup
886 '((vm . vm-visit-folder-other-frame)
887 (gnus . gnus-other-frame)
888 (file . find-file-other-window))
889 "Setup the frame configuration for following links.
890 When following a link with Emacs, it may often be useful to display
891 this link in another window or frame. This variable can be used to
892 set this up for the different types of links.
893 For VM, use any of
894 `vm-visit-folder'
895 `vm-visit-folder-other-frame'
896 For Gnus, use any of
897 `gnus'
898 `gnus-other-frame'
899 For FILE, use any of
900 `find-file'
901 `find-file-other-window'
902 `find-file-other-frame'
903 For the calendar, use the variable `calendar-setup'.
904 For BBDB, it is currently only possible to display the matches in
905 another window."
906 :group 'org-link-follow
907 :type '(list
908 (cons (const vm)
909 (choice
910 (const vm-visit-folder)
911 (const vm-visit-folder-other-window)
912 (const vm-visit-folder-other-frame)))
913 (cons (const gnus)
914 (choice
915 (const gnus)
916 (const gnus-other-frame)))
917 (cons (const file)
918 (choice
919 (const find-file)
920 (const find-file-other-window)
921 (const find-file-other-frame)))))
923 (defcustom org-open-non-existing-files nil
924 "Non-nil means, `org-open-file' will open non-existing file.
925 When nil, an error will be generated."
926 :group 'org-link-follow
927 :type 'boolean)
929 (defcustom org-confirm-shell-links 'yes-or-no-p
930 "Non-nil means, ask for confirmation before executing shell links.
931 Shell links can be dangerous, just thing about a link
933 [[shell:rm -rf ~/*][Google Search]]
935 This link would show up in your Org-mode document as \"Google Search\"
936 but really it would remove your entire home directory. Dangerous indeed.
937 Therefore I *definitely* advise agains setting this varaiable to nil.
938 Just change it to `y-or-n-p' of you want to confirm with a single key press
939 rather than having to type \"yes\"."
940 :group 'org-link-follow
941 :type '(choice
942 (const :tag "with yes-or-no (safer)" yes-or-no-p)
943 (const :tag "with y-or-n (faster)" y-or-n-p)
944 (const :tag "no confirmation (dangerous)" nil)))
946 (defconst org-file-apps-defaults-gnu
947 '((t . mailcap))
948 "Default file applications on a UNIX or GNU/Linux system.
949 See `org-file-apps'.")
951 (defconst org-file-apps-defaults-macosx
952 '((t . "open %s")
953 ("ps" . "gv %s")
954 ("ps.gz" . "gv %s")
955 ("eps" . "gv %s")
956 ("eps.gz" . "gv %s")
957 ("dvi" . "xdvi %s")
958 ("fig" . "xfig %s"))
959 "Default file applications on a MacOS X system.
960 The system \"open\" is known as a default, but we use X11 applications
961 for some files for which the OS does not have a good default.
962 See `org-file-apps'.")
964 (defconst org-file-apps-defaults-windowsnt
965 '((t . (w32-shell-execute "open" file)))
966 "Default file applications on a Windows NT system.
967 The system \"open\" is used for most files.
968 See `org-file-apps'.")
970 (defcustom org-file-apps
972 ("txt" . emacs)
973 ("tex" . emacs)
974 ("ltx" . emacs)
975 ("org" . emacs)
976 ("el" . emacs)
977 ("bib" . emacs)
979 "External applications for opening `file:path' items in a document.
980 Org-mode uses system defaults for different file types, but
981 you can use this variable to set the application for a given file
982 extension. The entries in this list are cons cells with a file extension
983 and the corresponding command. Possible values for the command are:
984 `emacs' The file will be visited by the current Emacs process.
985 `default' Use the default application for this file type.
986 string A command to be executed by a shell; %s will be replaced
987 by the path to the file.
988 sexp A Lisp form which will be evaluated. The file path will
989 be available in the Lisp variable `file'.
990 For more examples, see the system specific constants
991 `org-file-apps-defaults-macosx'
992 `org-file-apps-defaults-windowsnt'
993 `org-file-apps-defaults-gnu'."
994 :group 'org-link-follow
995 :type '(repeat
996 (cons (choice :value ""
997 (string :tag "Extension")
998 (const :tag "Default for unrecognized files" t)
999 (const :tag "Links to a directory" directory))
1000 (choice :value ""
1001 (const :tag "Visit with Emacs" emacs)
1002 (const :tag "Use system default" default)
1003 (string :tag "Command")
1004 (sexp :tag "Lisp form")))))
1006 (defcustom org-mhe-search-all-folders nil
1007 "Non-nil means, that the search for the mh-message will be extended to
1008 all folders if the message cannot be found in the folder given in the link.
1009 Searching all folders is very effective with one of the search engines
1010 supported by MH-E, but will be slow with pick."
1011 :group 'org-link-follow
1012 :type 'boolean)
1014 (defgroup org-remember nil
1015 "Options concerning interaction with remember.el."
1016 :tag "Org Remember"
1017 :group 'org)
1019 (defcustom org-directory "~/org"
1020 "Directory with org files.
1021 This directory will be used as default to prompt for org files.
1022 Used by the hooks for remember.el."
1023 :group 'org-remember
1024 :type 'directory)
1026 (defcustom org-default-notes-file "~/.notes"
1027 "Default target for storing notes.
1028 Used by the hooks for remember.el. This can be a string, or nil to mean
1029 the value of `remember-data-file'."
1030 :group 'org-remember
1031 :type '(choice
1032 (const :tag "Default from remember-data-file" nil)
1033 file))
1035 (defcustom org-remember-templates nil
1036 "Templates for the creation of remember buffers.
1037 When nil, just let remember make the buffer.
1038 When not nil, this is a list of 3-element lists. In each entry, the first
1039 element is a character, a unique key to select this template.
1040 The second element is the template. The third element is optional and can
1041 specify a destination file for remember items created with this template.
1042 The default file is given by `org-default-notes-file'.
1044 The template specifies the structure of the remember buffer. It should have
1045 a first line starting with a star, to act as the org-mode headline.
1046 Furthermore, the following %-escapes will be replaced with content:
1047 %t time stamp, date only
1048 %T time stamp with date and time
1049 %u inactive time stamp, date only
1050 %U inactive time stamp with date and time
1051 %n user name
1052 %a annotation, normally the link created with org-store-link
1053 %i initial content, the region when remember is called with C-u.
1054 If %i is indented, the entire inserted text will be indented as well.
1055 %? This will be removed, and the cursor placed at this position."
1056 :group 'org-remember
1057 :type '(repeat :tag "enabled"
1058 (list :value (?a "\n" nil)
1059 (character :tag "Selection Key")
1060 (string :tag "Template")
1061 (file :tag "Destination file (optional)"))))
1063 (defcustom org-reverse-note-order nil
1064 "Non-nil means, store new notes at the beginning of a file or entry.
1065 When nil, new notes will be filed to the end of a file or entry."
1066 :group 'org-remember
1067 :type '(choice
1068 (const :tag "Reverse always" t)
1069 (const :tag "Reverse never" nil)
1070 (repeat :tag "By file name regexp"
1071 (cons regexp boolean))))
1073 (defgroup org-todo nil
1074 "Options concerning TODO items in Org-mode."
1075 :tag "Org TODO"
1076 :group 'org)
1078 (defcustom org-todo-keywords '("TODO" "DONE")
1079 "List of TODO entry keywords.
1080 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1081 considered to mean that the entry is \"done\". All the other mean that
1082 action is required, and will make the entry show up in todo lists, diaries
1083 etc.
1084 The command \\[org-todo] cycles an entry through these states, and an
1085 additional state where no keyword is present. For details about this
1086 cycling, see also the variable `org-todo-interpretation'
1087 Changes become only effective after restarting Emacs."
1088 :group 'org-todo
1089 :group 'org-keywords
1090 :type '(repeat (string :tag "Keyword")))
1092 (defcustom org-todo-interpretation 'sequence
1093 "Controls how TODO keywords are interpreted.
1094 This variable is only relevant if `org-todo-keywords' contains more than two
1095 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1097 When `sequence', \\[org-todo] will always switch to the next state in the
1098 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1099 to state when executed several times in direct succession. Otherwise, it
1100 switches directly to DONE from any state.
1101 See the manual for more information."
1102 :group 'org-todo
1103 :group 'org-keywords
1104 :type '(choice (const sequence)
1105 (const type)))
1107 (defcustom org-after-todo-state-change-hook nil
1108 "Hook which is run after the state of a TODO item was changed.
1109 The new state (a string with a TODO keyword, or nil) is available in the
1110 Lisp variable `state'."
1111 :group 'org-todo
1112 :type 'hook)
1114 (defcustom org-log-done nil
1115 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1116 When the state of an entry is changed from nothing to TODO, remove a previous
1117 closing date."
1118 :group 'org-todo
1119 :type 'boolean)
1121 (defgroup org-priorities nil
1122 "Priorities in Org-mode."
1123 :tag "Org Priorities"
1124 :group 'org-todo)
1126 (defcustom org-default-priority ?B
1127 "The default priority of TODO items.
1128 This is the priority an item get if no explicit priority is given."
1129 :group 'org-priorities
1130 :type 'character)
1132 (defcustom org-lowest-priority ?C
1133 "The lowest priority of TODO items. A character like ?A, ?B etc."
1134 :group 'org-priorities
1135 :type 'character)
1137 (defgroup org-time nil
1138 "Options concerning time stamps and deadlines in Org-mode."
1139 :tag "Org Time"
1140 :group 'org)
1142 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1143 "Formats for `format-time-string' which are used for time stamps.
1144 It is not recommended to change this constant.")
1146 (defcustom org-time-stamp-rounding-minutes 0
1147 "Number of minutes to round time stamps to upon insertion.
1148 When zero, insert the time unmodified. Useful rounding numbers
1149 should be factors of 60, so for example 5, 10, 15.
1150 When this is not zero, you can still force an exact time-stamp by using
1151 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1152 :group 'org-time
1153 :type 'integer)
1155 (defcustom org-deadline-warning-days 30
1156 "No. of days before expiration during which a deadline becomes active.
1157 This variable governs the display in the org file."
1158 :group 'org-time
1159 :type 'number)
1161 (defcustom org-popup-calendar-for-date-prompt t
1162 "Non-nil means, pop up a calendar when prompting for a date.
1163 In the calendar, the date can be selected with mouse-1. However, the
1164 minibuffer will also be active, and you can simply enter the date as well.
1165 When nil, only the minibuffer will be available."
1166 :group 'org-time
1167 :type 'boolean)
1169 (defcustom org-calendar-follow-timestamp-change t
1170 "Non-nil means, make the calendar window follow timestamp changes.
1171 When a timestamp is modified and the calendar window is visible, it will be
1172 moved to the new date."
1173 :group 'org-time
1174 :type 'boolean)
1176 (defgroup org-tags nil
1177 "Options concerning tags in Org-mode."
1178 :tag "Org Tags"
1179 :group 'org)
1181 (defcustom org-tags-column 48
1182 "The column to which tags should be indented in a headline.
1183 If this number is positive, it specifies the column. If it is negative,
1184 it means that the tags should be flushright to that column. For example,
1185 -79 works well for a normal 80 character screen."
1186 :group 'org-tags
1187 :type 'integer)
1189 (defcustom org-auto-align-tags t
1190 "Non-nil means, realign tags after pro/demotion of TODO state change.
1191 These operations change the length of a headline and therefore shift
1192 the tags around. With this options turned on, after each such operation
1193 the tags are again aligned to `org-tags-column'."
1194 :group 'org-tags
1195 :type 'boolean)
1197 (defcustom org-use-tag-inheritance t
1198 "Non-nil means, tags in levels apply also for sublevels.
1199 When nil, only the tags directly given in a specific line apply there.
1200 If you turn off this option, you very likely want to turn on the
1201 companion option `org-tags-match-list-sublevels'."
1202 :group 'org-tags
1203 :type 'boolean)
1205 (defcustom org-tags-match-list-sublevels nil
1206 "Non-nil means list also sublevels of headlines matching tag search.
1207 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1208 the sublevels of a headline matching a tag search often also match
1209 the same search. Listing all of them can create very long lists.
1210 Setting this variable to nil causes subtrees of a match to be skipped.
1211 This option is off by default, because inheritance in on. If you turn
1212 inheritance off, you very likely want to turn this option on.
1214 As a special case, if the tag search is restricted to TODO items, the
1215 value of this variable is ignored and sublevels are always checked, to
1216 make sure all corresponding TODO items find their way into the list."
1217 :group 'org-tags
1218 :type 'boolean)
1220 (defvar org-tags-history nil
1221 "History of minibuffer reads for tags.")
1222 (defvar org-last-tags-completion-table nil
1223 "The last used completion table for tags.")
1225 (defgroup org-agenda nil
1226 "Options concerning agenda display Org-mode."
1227 :tag "Org Agenda"
1228 :group 'org)
1230 (defvar org-category nil
1231 "Variable used by org files to set a category for agenda display.
1232 Such files should use a file variable to set it, for example
1234 -*- mode: org; org-category: \"ELisp\"
1236 or contain a special line
1238 #+CATEGORY: ELisp
1240 If the file does not specify a category, then file's base name
1241 is used instead.")
1242 (make-variable-buffer-local 'org-category)
1244 (defcustom org-agenda-files nil
1245 "The files to be used for agenda display.
1246 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1247 \\[org-remove-file]. You can also use customize to edit the list.
1249 If the value of the variable is not a list but a single file name, then
1250 the list of agenda files is actually stored and maintained in that file, one
1251 agenda file per line."
1252 :group 'org-agenda
1253 :type '(choice
1254 (repeat :tag "List of files" file)
1255 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1257 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1258 "Custom commands for the agenda.
1259 These commands will be offered on the splash screen displayed by the
1260 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1262 key The key (a single char as a string) to be associated with the command.
1263 type The command type, any of the following symbols:
1264 todo Entries with a specific TODO keyword, in all agenda files.
1265 tags Tags match in all agenda files.
1266 tags-todo Tags match in all agenda files, TODO entries only.
1267 todo-tree Sparse tree of specific TODO keyword in *current* file.
1268 tags-tree Sparse tree with all tags matches in *current* file.
1269 occur-tree Occur sparse tree for current file.
1270 match What to search for:
1271 - a single keyword for TODO keyword searches
1272 - a tags match expression for tags searches
1273 - a regular expression for occur searches"
1274 :group 'org-agenda
1275 :type '(repeat
1276 (list (string :tag "Key")
1277 (choice :tag "Type"
1278 (const :tag "Tags search in all agenda files" tags)
1279 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1280 (const :tag "TODO keyword search in all agenda files" todo)
1281 (const :tag "Tags sparse tree in current buffer" tags-tree)
1282 (const :tag "TODO keyword tree in current buffer" todo-tree)
1283 (const :tag "Occur tree in current buffer" occur-tree))
1284 (string :tag "Match"))))
1286 ;; Fixme: Need a way to toggle this variable, maybe a mode in the
1287 ;; agenda buffer?
1288 (defcustom org-agenda-todo-list-sublevels t
1289 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1290 When nil, the sublevels of a TODO entry are not checked, resulting in
1291 potentially much shorter TODO lists."
1292 :group 'org-agenda
1293 :group 'org-todo
1294 :type 'boolean)
1296 (defcustom org-agenda-todo-ignore-scheduled nil
1297 "Non-nil means, don't show scheduled entries in the global todo list.
1298 The idea behind this is that by scheduling it, you have already taken care
1299 of this item."
1300 :group 'org-agenda
1301 :group 'org-todo
1302 :type 'boolean)
1304 (defcustom org-agenda-include-all-todo nil
1305 "Non-nil means, the agenda will always contain all TODO entries.
1306 When nil, date-less entries will only be shown if `org-agenda' is called
1307 with a prefix argument.
1308 When non-nil, the TODO entries will be listed at the top of the agenda, before
1309 the entries for specific days."
1310 :group 'org-agenda
1311 :type 'boolean)
1313 (defcustom org-agenda-include-diary nil
1314 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1315 :group 'org-agenda
1316 :type 'boolean)
1318 (defcustom org-calendar-to-agenda-key [?c]
1319 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1320 The command `org-calendar-goto-agenda' will be bound to this key. The
1321 default is the character `c' because then `c' can be used to switch back and
1322 forth between agenda and calendar."
1323 :group 'org-agenda
1324 :type 'sexp)
1326 (defgroup org-agenda-setup nil
1327 "Options concerning setting up the Agenda window in Org Mode."
1328 :tag "Org Agenda Window Setup"
1329 :group 'org-agenda)
1331 (defcustom org-agenda-mouse-1-follows-link nil
1332 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1333 A longer mouse click will still set point. Does not wortk on XEmacs.
1334 Needs to be set before org.el is loaded."
1335 :group 'org-agenda-setup
1336 :type 'boolean)
1338 (defcustom org-agenda-start-with-follow-mode nil
1339 "The initial value of follwo-mode in a newly created agenda window."
1340 :group 'org-agenda-setup
1341 :type 'boolean)
1343 (defcustom org-select-timeline-window t
1344 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1345 When nil, cursor will remain in the current window."
1346 :group 'org-agenda-setup
1347 :type 'boolean)
1349 (defcustom org-select-agenda-window t
1350 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1351 When nil, cursor will remain in the current window."
1352 :group 'org-agenda-setup
1353 :type 'boolean)
1355 (defcustom org-fit-agenda-window t
1356 "Non-nil means, change window size of agenda to fit content."
1357 :group 'org-agenda-setup
1358 :type 'boolean)
1360 (defgroup org-agenda-display nil
1361 "Options concerning what to display initially in Agenda."
1362 :tag "Org Agenda Display"
1363 :group 'org-agenda)
1365 (defcustom org-agenda-show-all-dates t
1366 "Non-nil means, `org-agenda' shows every day in the selected range.
1367 When nil, only the days which actually have entries are shown."
1368 :group 'org-agenda-display
1369 :type 'boolean)
1371 (defcustom org-agenda-start-on-weekday 1
1372 "Non-nil means, start the overview always on the specified weekday.
1373 0 denotes Sunday, 1 denotes Monday etc.
1374 When nil, always start on the current day."
1375 :group 'org-agenda-display
1376 :type '(choice (const :tag "Today" nil)
1377 (number :tag "Weekday No.")))
1379 (defcustom org-agenda-ndays 7
1380 "Number of days to include in overview display.
1381 Should be 1 or 7."
1382 :group 'org-agenda-display
1383 :type 'number)
1385 (defcustom org-agenda-use-time-grid t
1386 "Non-nil means, show a time grid in the agenda schedule.
1387 A time grid is a set of lines for specific times (like every two hours between
1388 8:00 and 20:00). The items scheduled for a day at specific times are
1389 sorted in between these lines.
1390 For details about when the grid will be shown, and what it will look like, see
1391 the variable `org-agenda-time-grid'."
1392 :group 'org-agenda-display
1393 :type 'boolean)
1395 (defcustom org-agenda-time-grid
1396 '((daily today require-timed)
1397 "----------------"
1398 (800 1000 1200 1400 1600 1800 2000))
1400 "The settings for time grid for agenda display.
1401 This is a list of three items. The first item is again a list. It contains
1402 symbols specifying conditions when the grid should be displayed:
1404 daily if the agenda shows a single day
1405 weekly if the agenda shows an entire week
1406 today show grid on current date, independent of daily/weekly display
1407 require-timed show grid only if at least on item has a time specification
1409 The second item is a string which will be places behing the grid time.
1411 The third item is a list of integers, indicating the times that should have
1412 a grid line."
1413 :group 'org-agenda-display
1414 :type
1415 '(list
1416 (set :greedy t :tag "Grid Display Options"
1417 (const :tag "Show grid in single day agenda display" daily)
1418 (const :tag "Show grid in weekly agenda display" weekly)
1419 (const :tag "Always show grid for today" today)
1420 (const :tag "Show grid only if any timed entries are present"
1421 require-timed)
1422 (const :tag "Skip grid times already present in an entry"
1423 remove-match))
1424 (string :tag "Grid String")
1425 (repeat :tag "Grid Times" (integer :tag "Time"))))
1427 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1428 "Sorting structure for the agenda items of a single day.
1429 This is a list of symbols which will be used in sequence to determine
1430 if an entry should be listed before another entry. The following
1431 symbols are recognized:
1433 time-up Put entries with time-of-day indications first, early first
1434 time-down Put entries with time-of-day indications first, late first
1435 category-keep Keep the default order of categories, corresponding to the
1436 sequence in `org-agenda-files'.
1437 category-up Sort alphabetically by category, A-Z.
1438 category-down Sort alphabetically by category, Z-A.
1439 priority-up Sort numerically by priority, high priority last.
1440 priority-down Sort numerically by priority, high priority first.
1442 The different possibilities will be tried in sequence, and testing stops
1443 if one comparison returns a \"not-equal\". For example, the default
1444 '(time-up category-keep priority-down)
1445 means: Pull out all entries having a specified time of day and sort them,
1446 in order to make a time schedule for the current day the first thing in the
1447 agenda listing for the day. Of the entries without a time indication, keep
1448 the grouped in categories, don't sort the categories, but keep them in
1449 the sequence given in `org-agenda-files'. Within each category sort by
1450 priority.
1452 Leaving out `category-keep' would mean that items will be sorted across
1453 categories by priority."
1454 :group 'org-agenda-display
1455 :type '(repeat
1456 (choice
1457 (const time-up)
1458 (const time-down)
1459 (const category-keep)
1460 (const category-up)
1461 (const category-down)
1462 (const priority-up)
1463 (const priority-down))))
1465 (defcustom org-sort-agenda-notime-is-late t
1466 "Non-nil means, items without time are considered late.
1467 This is only relevant for sorting. When t, items which have no explicit
1468 time like 15:30 will be considered as 24:01, i.e. later than any items which
1469 do have a time. When nil, the default time is before 0:00. You can use this
1470 option to decide if the schedule for today should come before or after timeless
1471 agenda entries."
1472 :group 'org-agenda-display
1473 :type 'boolean)
1476 (defgroup org-agenda-prefix nil
1477 "Options concerning the entry prefix in the Org-mode agenda display."
1478 :tag "Org Agenda Prefix"
1479 :group 'org-agenda)
1481 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1482 "Format specification for the prefix of items in the agenda buffer.
1483 This format works similar to a printf format, with the following meaning:
1485 %c the category of the item, \"Diary\" for entries from the diary, or
1486 as given by the CATEGORY keyword or derived from the file name.
1487 %T the first tag of the item.
1488 %t the time-of-day specification if one applies to the entry, in the
1489 format HH:MM
1490 %s Scheduling/Deadline information, a short string
1492 All specifiers work basically like the standard `%s' of printf, but may
1493 contain two additional characters: A question mark just after the `%' and
1494 a whitespace/punctuation character just before the final letter.
1496 If the first character after `%' is a question mark, the entire field
1497 will only be included if the corresponding value applies to the
1498 current entry. This is useful for fields which should have fixed
1499 width when present, but zero width when absent. For example,
1500 \"%?-12t\" will result in a 12 character time field if a time of the
1501 day is specified, but will completely disappear in entries which do
1502 not contain a time.
1504 If there is punctuation or whitespace character just before the final
1505 format letter, this character will be appended to the field value if
1506 the value is not empty. For example, the format \"%-12:c\" leads to
1507 \"Diary: \" if the category is \"Diary\". If the category were be
1508 empty, no additional colon would be interted.
1510 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1511 - Indent the line with two space characters
1512 - Give the category in a 12 chars wide field, padded with whitespace on
1513 the right (because of `-'). Append a colon if there is a category
1514 (because of `:').
1515 - If there is a time-of-day, put it into a 12 chars wide field. If no
1516 time, don't put in an empty field, just skip it (because of '?').
1517 - Finally, put the scheduling information and append a whitespace.
1519 As another example, if you don't want the time-of-day of entries in
1520 the prefix, you could use:
1522 (setq org-agenda-prefix-format \" %-11:c% s\")
1524 See also the variables `org-agenda-remove-times-when-in-prefix' and
1525 `org-agenda-remove-tags-when-in-prefix'."
1526 :type 'string
1527 :group 'org-agenda-prefix)
1529 (defcustom org-timeline-prefix-format " % s"
1530 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1531 :type 'string
1532 :group 'org-agenda-prefix)
1534 (defvar org-prefix-format-compiled nil
1535 "The compiled version of the most recently used prefix format.
1536 Depending on which command was used last, this may be the compiled version
1537 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1539 ;; FIXME: There seem to be situations where this does no work.
1540 (defcustom org-agenda-remove-times-when-in-prefix t
1541 "Non-nil means, remove duplicate time specifications in agenda items.
1542 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1543 time-of-day specification in a headline or diary entry is extracted and
1544 placed into the prefix. If this option is non-nil, the original specification
1545 \(a timestamp or -range, or just a plain time(range) specification like
1546 11:30-4pm) will be removed for agenda display. This makes the agenda less
1547 cluttered.
1548 The option can be t or nil. It may also be the symbol `beg', indicating
1549 that the time should only be removed what it is located at the beginning of
1550 the headline/diary entry."
1551 :group 'org-agenda-prefix
1552 :type '(choice
1553 (const :tag "Always" t)
1554 (const :tag "Never" nil)
1555 (const :tag "When at beginning of entry" beg)))
1557 (defcustom org-agenda-remove-tags-when-in-prefix nil
1558 "Non-nil means, remove the tags from the headline copy in the agenda.
1559 When this is the symbol `prefix', only remove tags when
1560 `org-agenda-prefix-format' contains a `%T' specifier."
1561 :group 'org-agenda-prefix
1562 :type '(choice
1563 (const :tag "Always" t)
1564 (const :tag "Never" nil)
1565 (const :tag "When prefix format contains %T" prefix)))
1567 (defgroup org-export nil
1568 "Options for exporting org-listings."
1569 :tag "Org Export"
1570 :group 'org)
1572 (defgroup org-export-general nil
1573 "General options for exporting Org-mode files."
1574 :tag "Org Export General"
1575 :group 'org-export)
1577 (defcustom org-export-publishing-directory "."
1578 "Path to the location where exported files should be located.
1579 This path may be relative to the directory where the Org-mode file lives.
1580 The default is to put them into the same directory as the Org-mode file."
1581 :group 'org-export-general
1582 :type 'directory)
1584 (defcustom org-export-language-setup
1585 '(("en" "Author" "Date" "Table of Contents")
1586 ("da" "Ophavsmand" "Dato" "Indhold")
1587 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1588 ("es" "Autor" "Fecha" "\xccndice")
1589 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1590 ("it" "Autore" "Data" "Indice")
1591 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1592 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1593 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1594 "Terms used in export text, translated to different languages.
1595 Use the variable `org-export-default-language' to set the language,
1596 or use the +OPTION lines for a per-file setting."
1597 :group 'org-export-general
1598 :type '(repeat
1599 (list
1600 (string :tag "HTML language tag")
1601 (string :tag "Author")
1602 (string :tag "Date")
1603 (string :tag "Table of Contents"))))
1605 (defcustom org-export-default-language "en"
1606 "The default language of HTML export, as a string.
1607 This should have an association in `org-export-language-setup'."
1608 :group 'org-export-general
1609 :type 'string)
1611 (defcustom org-export-headline-levels 3
1612 "The last level which is still exported as a headline.
1613 Inferior levels will produce itemize lists when exported.
1614 Note that a numeric prefix argument to an exporter function overrides
1615 this setting.
1617 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1618 :group 'org-export-general
1619 :type 'number)
1621 (defcustom org-export-with-section-numbers t
1622 "Non-nil means, add section numbers to headlines when exporting.
1624 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1625 :group 'org-export-general
1626 :type 'boolean)
1628 (defcustom org-export-with-toc t
1629 "Non-nil means, create a table of contents in exported files.
1630 The TOC contains headlines with levels up to`org-export-headline-levels'.
1632 Headlines which contain any TODO items will be marked with \"(*)\" in
1633 ASCII export, and with red color in HTML output.
1635 In HTML output, the TOC will be clickable.
1637 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1638 :group 'org-export-general
1639 :type 'boolean)
1641 (defcustom org-export-mark-todo-in-toc nil
1642 "Non-nil means, mark TOC lines that contain any open TODO items."
1643 :group 'org-export-general
1644 :type 'boolean)
1646 (defcustom org-export-preserve-breaks nil
1647 "Non-nil means, preserve all line breaks when exporting.
1648 Normally, in HTML output paragraphs will be reformatted. In ASCII
1649 export, line breaks will always be preserved, regardless of this variable.
1651 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1652 :group 'org-export-general
1653 :type 'boolean)
1655 (defcustom org-export-with-tags t
1656 "Nil means, do not export tags, just remove them from headlines."
1657 :group 'org-export-general
1658 :type 'boolean)
1660 (defcustom org-export-with-timestamps t
1661 "Nil means, do not export timestamps and associated keywords."
1662 :group 'org-export-general
1663 :type 'boolean)
1665 (defgroup org-export-translation nil
1666 "Options for translating special ascii sequences for the export backends."
1667 :tag "Org Export Translation"
1668 :group 'org-export)
1670 (defcustom org-export-with-emphasize t
1671 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1672 If the export target supports emphasizing text, the word will be
1673 typeset in bold, italic, or underlined, respectively. Works only for
1674 single words, but you can say: I *really* *mean* *this*.
1675 Not all export backends support this.
1677 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1678 :group 'org-export-translation
1679 :type 'boolean)
1681 (defcustom org-export-with-sub-superscripts t
1682 "Non-nil means, interpret \"_\" and \"^\" for export.
1683 When this option is turned on, you can use TeX-like syntax for sub- and
1684 superscripts. Several characters after \"_\" or \"^\" will be
1685 considered as a single item - so grouping with {} is normally not
1686 needed. For example, the following things will be parsed as single
1687 sub- or superscripts.
1689 10^24 or 10^tau several digits will be considered 1 item.
1690 10^-12 or 10^-tau a leading sign with digits or a word
1691 x^2-y^3 will be read as x^2 - y^3, because items are
1692 terminated by almost any nonword/nondigit char.
1693 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1695 Still, ambiguity is possible - so when in doubt use {} to enclose the
1696 sub/superscript.
1697 Not all export backends support this, but HTML does.
1699 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1700 :group 'org-export-translation
1701 :type 'boolean)
1703 (defcustom org-export-with-TeX-macros t
1704 "Non-nil means, interpret simple TeX-like macros when exporting.
1705 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1706 No only real TeX macros will work here, but the standard HTML entities
1707 for math can be used as macro names as well. For a list of supported
1708 names in HTML export, see the constant `org-html-entities'.
1709 Not all export backends support this.
1711 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1712 :group 'org-export-translation
1713 :type 'boolean)
1715 (defcustom org-export-with-fixed-width t
1716 "Non-nil means, lines starting with \":\" will be in fixed width font.
1717 This can be used to have pre-formatted text, fragments of code etc. For
1718 example:
1719 : ;; Some Lisp examples
1720 : (while (defc cnt)
1721 : (ding))
1722 will be looking just like this in also HTML. See also the QUOTE keyword.
1723 Not all export backends support this.
1725 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1726 :group 'org-export-translation
1727 :type 'boolean)
1729 (defcustom org-match-sexp-depth 3
1730 "Number of stacked braces for sub/superscript matching.
1731 This has to be set before loading org.el to be effective."
1732 :group 'org-export-translation
1733 :type 'integer)
1735 (defgroup org-export-tables nil
1736 "Options for exporting tables in Org-mode."
1737 :tag "Org Export Tables"
1738 :group 'org-export)
1740 (defcustom org-export-with-tables t
1741 "If non-nil, lines starting with \"|\" define a table.
1742 For example:
1744 | Name | Address | Birthday |
1745 |-------------+----------+-----------|
1746 | Arthur Dent | England | 29.2.2100 |
1748 Not all export backends support this.
1750 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1751 :group 'org-export-tables
1752 :type 'boolean)
1754 (defcustom org-export-highlight-first-table-line t
1755 "Non-nil means, highlight the first table line.
1756 In HTML export, this means use <th> instead of <td>.
1757 In tables created with table.el, this applies to the first table line.
1758 In Org-mode tables, all lines before the first horizontal separator
1759 line will be formatted with <th> tags."
1760 :group 'org-export-tables
1761 :type 'boolean)
1763 (defcustom org-export-table-remove-special-lines t
1764 "Remove special lines and marking characters in calculating tables.
1765 This removes the special marking character column from tables that are set
1766 up for spreadsheet calculations. It also removes the entire lines
1767 marked with `!', `_', or `^'. The lines with `$' are kept, because
1768 the values of constants may be useful to have."
1769 :group 'org-export-tables
1770 :type 'boolean)
1772 (defcustom org-export-prefer-native-exporter-for-tables nil
1773 "Non-nil means, always export tables created with table.el natively.
1774 Natively means, use the HTML code generator in table.el.
1775 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1776 the table does not use row- or column-spanning). This has the
1777 advantage, that the automatic HTML conversions for math symbols and
1778 sub/superscripts can be applied. Org-mode's HTML generator is also
1779 much faster."
1780 :group 'org-export-tables
1781 :type 'boolean)
1783 (defgroup org-export-ascii nil
1784 "Options specific for ASCII export of Org-mode files."
1785 :tag "Org Export ASCII"
1786 :group 'org-export)
1788 (defcustom org-export-ascii-show-new-buffer t
1789 "Non-nil means, popup buffer containing the exported ASCII text.
1790 Otherwise the buffer will just be saved to a file and stay hidden."
1791 :group 'org-export-ascii
1792 :type 'boolean)
1794 (defgroup org-export-xml nil
1795 "Options specific for XML export of Org-mode files."
1796 :tag "Org Export XML"
1797 :group 'org-export)
1799 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1800 "The kind of XML to be produced by the XML exporter.
1801 Allowed values are:
1802 xoxo The XOXO exporter."
1803 :group 'org-export-xml
1804 :type '(choice
1805 (const :tag "XOXO" xoxo)))
1807 (defgroup org-export-html nil
1808 "Options specific for HTML export of Org-mode files."
1809 :tag "Org Export HTML"
1810 :group 'org-export)
1812 (defcustom org-export-html-style
1813 "<style type=\"text/css\">
1814 html {
1815 font-family: Times, serif;
1816 font-size: 12pt;
1818 .title { text-align: center; }
1819 .todo, .deadline { color: red; }
1820 .done { color: green; }
1821 .target { background-color: lavender; }
1822 pre {
1823 border: 1pt solid #AEBDCC;
1824 background-color: #F3F5F7;
1825 padding: 5pt;
1826 font-family: courier, monospace;
1828 table { border-collapse: collapse; }
1829 td, th {
1830 vertical-align: top;
1831 border: 1pt solid #ADB9CC;
1833 </style>"
1834 "The default style specification for exported HTML files.
1835 Since there are different ways of setting style information, this variable
1836 needs to contain the full HTML structure to provide a style, including the
1837 surrounding HTML tags. The style specifications should include definitions
1838 for new classes todo, done, title, and deadline. For example, legal values
1839 would be:
1841 <style type=\"text/css\">
1842 p { font-weight: normal; color: gray; }
1843 h1 { color: black; }
1844 .title { text-align: center; }
1845 .todo, .deadline { color: red; }
1846 .done { color: green; }
1847 </style>
1849 or, if you want to keep the style in a file,
1851 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1853 As the value of this option simply gets inserted into the HTML <head> header,
1854 you can \"misuse\" it to add arbitrary text to the header."
1855 :group 'org-export-html
1856 :type 'string)
1858 (defcustom org-export-html-link-org-files-as-html t
1859 "Non-nil means, make file links to `file.org' point to `file.html'.
1860 When org-mode is exporting an org-mode file to HTML, links to
1861 non-html files are directly put into a href tag in HTML.
1862 However, links to other Org-mode files (recognized by the
1863 extension `.org.) should become links to the corresponding html
1864 file, assuming that the linked org-mode file will also be
1865 converted to HTML.
1866 When nil, the links still point to the plain `.org' file."
1867 :group 'org-export-html
1868 :type 'boolean)
1870 (defcustom org-export-html-inline-images 'maybe
1871 "Non-nil means, inline images into exported HTML pages.
1872 This is done using an <img> tag. When nil, an anchor with href is used to
1873 link to the image. If this option is `maybe', then images in links with
1874 an empty description will be inlined, while images with a description will
1875 be linked only."
1876 :group 'org-export-html
1877 :type '(choice (const :tag "Never" nil)
1878 (const :tag "Always" t)
1879 (const :tag "When there is no description" maybe)))
1881 (defcustom org-export-html-expand t
1882 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1883 When nil, these tags will be exported as plain text and therefore
1884 not be interpreted by a browser.
1886 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1887 :group 'org-export-html
1888 :type 'boolean)
1890 (defcustom org-export-html-table-tag
1891 "<table border=1 cellspacing=0 cellpadding=6>"
1892 "The HTML tag used to start a table.
1893 This must be a <table> tag, but you may change the options like
1894 borders and spacing."
1895 :group 'org-export-html
1896 :type 'string)
1898 (defcustom org-export-html-with-timestamp nil
1899 "If non-nil, write `org-export-html-html-helper-timestamp'
1900 into the exported HTML text. Otherwise, the buffer will just be saved
1901 to a file."
1902 :group 'org-export-html
1903 :type 'boolean)
1905 (defcustom org-export-html-html-helper-timestamp
1906 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1907 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1908 :group 'org-export-html
1909 :type 'string)
1911 (defcustom org-export-html-show-new-buffer nil
1912 "Non-nil means, popup buffer containing the exported html text.
1913 Otherwise, the buffer will just be saved to a file and stay hidden."
1914 :group 'org-export-html
1915 :type 'boolean)
1917 (defgroup org-export-icalendar nil
1918 "Options specific for iCalendar export of Org-mode files."
1919 :tag "Org Export iCalendar"
1920 :group 'org-export)
1922 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1923 "The file name for the iCalendar file covering all agenda files.
1924 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1925 :group 'org-export-icalendar
1926 :type 'file)
1928 (defcustom org-icalendar-include-todo nil
1929 "Non-nil means, export to iCalendar files should also cover TODO items."
1930 :group 'org-export-icalendar
1931 :type 'boolean)
1933 (defcustom org-icalendar-combined-name "OrgMode"
1934 "Calendar name for the combined iCalendar representing all agenda files."
1935 :group 'org-export-icalendar
1936 :type 'string)
1938 (defgroup org-font-lock nil
1939 "Font-lock settings for highlighting in Org-mode."
1940 :tag "Org Font Lock"
1941 :group 'org)
1943 (defcustom org-level-color-stars-only nil
1944 "Non-nil means fontify only the stars in each headline.
1945 When nil, the entire headline is fontified.
1946 Changing it requires restart of `font-lock-mode' to become effective
1947 also in regions already fontified."
1948 :group 'org-font-lock
1949 :type 'boolean)
1951 (defcustom org-hide-leading-stars nil
1952 "Non-nil means, hide the first N-1 stars in a headline.
1953 This works by using the face `org-hide' for these stars. This
1954 face is white for a light background, and black for a dark
1955 background. You may have to customize the face `org-hide' to
1956 make this work.
1957 Changing it requires restart of `font-lock-mode' to become effective
1958 also in regions already fontified.
1959 You may also set this on a per-file basis by adding one of the following
1960 lines to the buffer:
1962 #+STARTUP: hidestars
1963 #+STARTUP: showstars"
1964 :group 'org-font-lock
1965 :type 'boolean)
1967 (defcustom org-fontify-done-headline nil
1968 "Non-nil means, change the face of a headline if it is marked DONE.
1969 Normally, only the TODO/DONE keyword indicates the state of a headline.
1970 When this is non-nil, the headline after the keyword is set to the
1971 `org-headline-done' as an additional indication."
1972 :group 'org-font-lock
1973 :type 'boolean)
1975 (defcustom org-fontify-emphasized-text t
1976 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1977 Changing this variable requires a restart of Emacs to take effect."
1978 :group 'org-font-lock
1979 :type 'boolean)
1981 (defgroup org-faces nil
1982 "Faces in Org-mode."
1983 :tag "Org Faces"
1984 :group 'org-font-lock)
1986 (defun org-compatible-face (specs)
1987 "Make a compatible face specification.
1988 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
1989 For them we convert a (min-colors 8) entry to a `tty' entry and move it
1990 to the top of the list. The `min-colors' attribute will be removed from
1991 any other entries, and any resulting duplicates will be removed entirely."
1992 (if (or (featurep 'xemacs) (< emacs-major-version 22))
1993 (let (r e a)
1994 (while (setq e (pop specs))
1995 (cond
1996 ((memq (car e) '(t default)) (push e r))
1997 ((setq a (member '(min-colors 8) (car e)))
1998 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
1999 (cdr e)))))
2000 ((setq a (assq 'min-colors (car e)))
2001 (setq e (cons (delq a (car e)) (cdr e)))
2002 (or (assoc (car e) r) (push e r)))
2003 (t (or (assoc (car e) r) (push e r)))))
2004 (nreverse r))
2005 specs))
2007 (defface org-hide
2008 '((((background light)) (:foreground "white"))
2009 (((background dark)) (:foreground "black")))
2010 "Face used to hide leading stars in headlines.
2011 The forground color of this face should be equal to the background
2012 color of the frame."
2013 :group 'org-faces)
2015 (defface org-level-1 ;; font-lock-function-name-face
2016 (org-compatible-face
2017 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2018 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2019 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2020 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2021 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2022 (t (:bold t))))
2023 "Face used for level 1 headlines."
2024 :group 'org-faces)
2026 (defface org-level-2 ;; font-lock-variable-name-face
2027 (org-compatible-face
2028 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2029 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2030 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2031 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2032 (t (:bold t))))
2033 "Face used for level 2 headlines."
2034 :group 'org-faces)
2036 (defface org-level-3 ;; font-lock-keyword-face
2037 (org-compatible-face
2038 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2039 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2040 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2041 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2042 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2043 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2044 (t (:bold t))))
2045 "Face used for level 3 headlines."
2046 :group 'org-faces)
2048 (defface org-level-4 ;; font-lock-comment-face
2049 (org-compatible-face
2050 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2051 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2052 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2053 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2054 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2055 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2056 (t (:bold t))))
2057 "Face used for level 4 headlines."
2058 :group 'org-faces)
2060 (defface org-level-5 ;; font-lock-type-face
2061 (org-compatible-face
2062 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2063 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2064 (((class color) (min-colors 8)) (:foreground "green"))))
2065 "Face used for level 5 headlines."
2066 :group 'org-faces)
2068 (defface org-level-6 ;; font-lock-constant-face
2069 (org-compatible-face
2070 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2071 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2072 (((class color) (min-colors 8)) (:foreground "magenta"))))
2073 "Face used for level 6 headlines."
2074 :group 'org-faces)
2076 (defface org-level-7 ;; font-lock-builtin-face
2077 (org-compatible-face
2078 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2079 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2080 (((class color) (min-colors 8)) (:foreground "blue")))) ;; FIXME: for dark bg?
2081 "Face used for level 7 headlines."
2082 :group 'org-faces)
2084 (defface org-level-8 ;; font-lock-string-face
2085 (org-compatible-face
2086 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2087 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2088 (((class color) (min-colors 8)) (:foreground "green"))))
2089 "Face used for level 8 headlines."
2090 :group 'org-faces)
2092 (defface org-special-keyword ;; font-lock-string-face
2093 (org-compatible-face
2094 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2095 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2096 (t (:italic t))))
2097 "Face used for special keywords."
2098 :group 'org-faces)
2100 (defface org-warning ;; font-lock-warning-face
2101 (org-compatible-face
2102 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2103 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2104 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2105 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2106 (t (:bold t))))
2107 "Face for deadlines and TODO keywords."
2108 :group 'org-faces)
2110 (defface org-headline-done ;; font-lock-string-face
2111 (org-compatible-face
2112 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2113 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2114 (((class color) (min-colors 8) (background light)) (:bold nil))))
2115 "Face used to indicate that a headline is DONE.
2116 This face is only used if `org-fontify-done-headline' is set."
2117 :group 'org-faces)
2119 (defface org-link
2120 '((((class color) (background light)) (:foreground "Purple" :underline t))
2121 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2122 (t (:underline t)))
2123 "Face for links."
2124 :group 'org-faces)
2126 (defface org-date
2127 '((((class color) (background light)) (:foreground "Purple" :underline t))
2128 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2129 (t (:underline t)))
2130 "Face for links."
2131 :group 'org-faces)
2133 (defface org-tag
2134 '((t (:bold t)))
2135 "Face for tags."
2136 :group 'org-faces)
2138 (defface org-todo ;; font-lock-warning-face
2139 (org-compatible-face
2140 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2141 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2142 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2143 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2144 (t (:inverse-video t :bold t))))
2145 "Face for TODO keywords."
2146 :group 'org-faces)
2148 (defface org-done ;; font-lock-type-face
2149 (org-compatible-face
2150 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2151 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2152 (((class color) (min-colors 8)) (:foreground "green"))
2153 (t (:bold t))))
2154 "Face used for DONE."
2155 :group 'org-faces)
2157 (defface org-table ;; font-lock-function-name-face
2158 (org-compatible-face
2159 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2160 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2161 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2162 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2163 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2164 (((class color) (min-colors 8) (background dark)))))
2165 "Face used for tables."
2166 :group 'org-faces)
2168 (defface org-formula
2169 (org-compatible-face
2170 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2171 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2172 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2173 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2174 (t (:bold t :italic t))))
2175 "Face for formulas."
2176 :group 'org-faces)
2178 (defface org-scheduled-today
2179 (org-compatible-face
2180 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2181 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2182 (((class color) (min-colors 8)) (:foreground "green"))
2183 (t (:bold t :italic t))))
2184 "Face for items scheduled for a certain day."
2185 :group 'org-faces)
2187 (defface org-scheduled-previously
2188 (org-compatible-face
2189 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2190 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2191 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2192 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2193 (t (:bold t))))
2194 "Face for items scheduled previously, and not yet done."
2195 :group 'org-faces)
2197 (defface org-time-grid ;; font-lock-variable-name-face
2198 (org-compatible-face
2199 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2200 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2201 (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))) ; FIXME: turn off???
2202 "Face used for time grids."
2203 :group 'org-faces)
2205 (defconst org-level-faces
2206 '(org-level-1 org-level-2 org-level-3 org-level-4
2207 org-level-5 org-level-6 org-level-7 org-level-8
2209 (defconst org-n-levels (length org-level-faces))
2211 (defconst org-bold-re
2212 (if (featurep 'xemacs)
2213 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2214 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2215 "Regular expression for bold emphasis.")
2216 (defconst org-italic-re
2217 (if (featurep 'xemacs)
2218 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2219 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2220 "Regular expression for italic emphasis.")
2221 (defconst org-underline-re
2222 (if (featurep 'xemacs)
2223 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2224 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2225 "Regular expression for underline emphasis.")
2227 ;; Variables for pre-computed regular expressions, all buffer local
2228 (defvar org-done-string nil
2229 "The last string in `org-todo-keywords', indicating an item is DONE.")
2230 (make-variable-buffer-local 'org-done-string)
2231 (defvar org-todo-regexp nil
2232 "Matches any of the TODO state keywords.")
2233 (make-variable-buffer-local 'org-todo-regexp)
2234 (defvar org-not-done-regexp nil
2235 "Matches any of the TODO state keywords except the last one.")
2236 (make-variable-buffer-local 'org-not-done-regexp)
2237 (defvar org-todo-line-regexp nil
2238 "Matches a headline and puts TODO state into group 2 if present.")
2239 (make-variable-buffer-local 'org-todo-line-regexp)
2240 (defvar org-nl-done-regexp nil
2241 "Matches newline followed by a headline with the DONE keyword.")
2242 (make-variable-buffer-local 'org-nl-done-regexp)
2243 (defvar org-looking-at-done-regexp nil
2244 "Matches the DONE keyword a point.")
2245 (make-variable-buffer-local 'org-looking-at-done-regexp)
2246 (defvar org-todo-kwd-priority-p nil
2247 "Do TODO items have priorities?")
2248 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2249 (defvar org-todo-kwd-max-priority nil
2250 "Maximum priority of TODO items.")
2251 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2252 (defvar org-ds-keyword-length 12
2253 "Maximum length of the Deadline and SCHEDULED keywords.")
2254 (make-variable-buffer-local 'org-ds-keyword-length)
2255 (defvar org-deadline-regexp nil
2256 "Matches the DEADLINE keyword.")
2257 (make-variable-buffer-local 'org-deadline-regexp)
2258 (defvar org-deadline-time-regexp nil
2259 "Matches the DEADLINE keyword together with a time stamp.")
2260 (make-variable-buffer-local 'org-deadline-time-regexp)
2261 (defvar org-deadline-line-regexp nil
2262 "Matches the DEADLINE keyword and the rest of the line.")
2263 (make-variable-buffer-local 'org-deadline-line-regexp)
2264 (defvar org-scheduled-regexp nil
2265 "Matches the SCHEDULED keyword.")
2266 (make-variable-buffer-local 'org-scheduled-regexp)
2267 (defvar org-scheduled-time-regexp nil
2268 "Matches the SCHEDULED keyword together with a time stamp.")
2269 (make-variable-buffer-local 'org-scheduled-time-regexp)
2270 (defvar org-closed-time-regexp nil
2271 "Matches the CLOSED keyword together with a time stamp.")
2272 (make-variable-buffer-local 'org-closed-time-regexp)
2274 (defvar org-keyword-time-regexp nil
2275 "Matches any of the 3 keywords, together with the time stamp.")
2276 (make-variable-buffer-local 'org-keyword-time-regexp)
2278 (defun org-set-regexps-and-options ()
2279 "Precompute regular expressions for current buffer."
2280 (when (eq major-mode 'org-mode)
2281 (let ((re (org-make-options-regexp
2282 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2283 "STARTUP" "ARCHIVE")))
2284 (splitre "[ \t]+")
2285 kwds int key value cat arch)
2286 (save-excursion
2287 (save-restriction
2288 (widen)
2289 (goto-char (point-min))
2290 (while (re-search-forward re nil t)
2291 (setq key (match-string 1) value (match-string 2))
2292 (cond
2293 ((equal key "CATEGORY")
2294 (if (string-match "[ \t]+$" value)
2295 (setq value (replace-match "" t t value)))
2296 (setq cat (intern value)))
2297 ((equal key "SEQ_TODO")
2298 (setq int 'sequence
2299 kwds (append kwds (org-split-string value splitre))))
2300 ((equal key "PRI_TODO")
2301 (setq int 'priority
2302 kwds (append kwds (org-split-string value splitre))))
2303 ((equal key "TYP_TODO")
2304 (setq int 'type
2305 kwds (append kwds (org-split-string value splitre))))
2306 ((equal key "STARTUP")
2307 (let ((opts (org-split-string value splitre))
2308 (set '(("fold" org-startup-folded t)
2309 ("overview" org-startup-folded t)
2310 ("nofold" org-startup-folded nil)
2311 ("showall" org-startup-folded nil)
2312 ("content" org-startup-folded content)
2313 ("hidestars" org-hide-leading-stars t)
2314 ("showstars" org-hide-leading-stars nil)
2315 ("odd" org-odd-levels-only t)
2316 ("oddeven" org-odd-levels-only nil)
2317 ("align" org-startup-align-all-tables t)
2318 ("noalign" org-startup-align-all-tables nil)
2319 ("dlcheck" org-startup-with-deadline-check t)
2320 ("nodlcheck" org-startup-with-deadline-check nil)))
2321 l var val)
2322 (while (setq l (assoc (pop opts) set))
2323 (setq var (nth 1 l) val (nth 2 l))
2324 (set (make-local-variable var) val))))
2325 ((equal key "ARCHIVE")
2326 (string-match " *$" value)
2327 (setq arch (replace-match "" t t value))
2328 (remove-text-properties 0 (length arch)
2329 '(face t fontified t) arch)))
2331 (and cat (set (make-local-variable 'org-category) cat))
2332 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2333 (and arch (set (make-local-variable 'org-archive-location) arch))
2334 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2335 ;; Compute the regular expressions and other local variables
2336 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2337 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2338 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2339 (length org-scheduled-string)))
2340 org-done-string
2341 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2342 org-todo-regexp
2343 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2344 "\\|") "\\)\\>")
2345 org-not-done-regexp
2346 (concat "\\<\\("
2347 (mapconcat 'regexp-quote
2348 (nreverse (cdr (reverse org-todo-keywords)))
2349 "\\|")
2350 "\\)\\>")
2351 org-todo-line-regexp
2352 (concat "^\\(\\*+\\)[ \t]*\\("
2353 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2354 "\\)? *\\(.*\\)")
2355 org-nl-done-regexp
2356 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2357 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2358 org-deadline-regexp (concat "\\<" org-deadline-string)
2359 org-deadline-time-regexp
2360 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2361 org-deadline-line-regexp
2362 (concat "\\<\\(" org-deadline-string "\\).*")
2363 org-scheduled-regexp
2364 (concat "\\<" org-scheduled-string)
2365 org-scheduled-time-regexp
2366 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2367 org-closed-time-regexp
2368 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2369 org-keyword-time-regexp
2370 (concat "\\<\\(" org-scheduled-string
2371 "\\|" org-deadline-string
2372 "\\|" org-closed-string "\\)"
2373 " *[[<]\\([^]>]+\\)[]>]")) ;; FIXME: is this correct?
2375 (org-set-font-lock-defaults)))
2377 ;; Tell the compiler about dynamically scoped variables,
2378 ;; and variables from other packages
2379 (defvar zmacs-regions) ; XEmacs regions
2380 (defvar original-date) ; dynamically scoped in calendar
2381 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2382 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2383 (defvar org-html-entities) ; defined later in this file
2384 (defvar org-goto-start-pos) ; dynamically scoped parameter
2385 (defvar org-time-was-given) ; dynamically scoped parameter
2386 (defvar org-ts-what) ; dynamically scoped parameter
2387 (defvar mark-active) ; Emacs only, not available in XEmacs.
2388 (defvar timecnt) ; dynamically scoped parameter
2389 (defvar levels-open) ; dynamically scoped parameter
2390 (defvar entry) ; dynamically scoped parameter
2391 (defvar date) ; dynamically scoped parameter
2392 (defvar description) ; dynamically scoped parameter
2393 (defvar ans1) ; dynamically scoped parameter
2394 (defvar ans2) ; dynamically scoped parameter
2395 (defvar starting-day) ; local variable
2396 (defvar include-all-loc) ; local variable
2397 (defvar vm-message-pointer) ; from vm
2398 (defvar vm-folder-directory) ; from vm
2399 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2400 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2401 (defvar gnus-group-name) ; from gnus
2402 (defvar gnus-article-current) ; from gnus
2403 (defvar w3m-current-url) ; from w3m
2404 (defvar mh-progs) ; from MH-E
2405 (defvar mh-current-folder) ; from MH-E
2406 (defvar mh-show-folder-buffer) ; from MH-E
2407 (defvar mh-index-folder) ; from MH-E
2408 (defvar mh-searcher) ; from MH-E
2409 (defvar org-selected-point) ; dynamically scoped parameter
2410 (defvar calendar-mode-map) ; from calendar.el
2411 (defvar last-arg) ; local variable
2412 (defvar remember-save-after-remembering) ; from remember.el
2413 (defvar remember-data-file) ; from remember.el
2414 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2415 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2416 (defvar orgtbl-mode) ; defined later in this file
2417 ;;; Define the mode
2419 (defvar org-mode-map
2420 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2421 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22.")
2422 (copy-keymap outline-mode-map))
2423 "Keymap for Org-mode.")
2425 (defvar org-struct-menu) ; defined later in this file
2426 (defvar org-org-menu) ; defined later in this file
2427 (defvar org-tbl-menu) ; defined later in this file
2429 ;; We use a before-change function to check if a table might need
2430 ;; an update.
2431 (defvar org-table-may-need-update t
2432 "Indicates that a table might need an update.
2433 This variable is set by `org-before-change-function'.
2434 `org-table-align' sets it back to nil.")
2435 (defvar org-mode-hook nil)
2436 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2437 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2440 ;;;###autoload
2441 (define-derived-mode org-mode outline-mode "Org"
2442 "Outline-based notes management and organizer, alias
2443 \"Carsten's outline-mode for keeping track of everything.\"
2445 Org-mode develops organizational tasks around a NOTES file which
2446 contains information about projects as plain text. Org-mode is
2447 implemented on top of outline-mode, which is ideal to keep the content
2448 of large files well structured. It supports ToDo items, deadlines and
2449 time stamps, which magically appear in the diary listing of the Emacs
2450 calendar. Tables are easily created with a built-in table editor.
2451 Plain text URL-like links connect to websites, emails (VM), Usenet
2452 messages (Gnus), BBDB entries, and any files related to the project.
2453 For printing and sharing of notes, an Org-mode file (or a part of it)
2454 can be exported as a structured ASCII or HTML file.
2456 The following commands are available:
2458 \\{org-mode-map}"
2460 ;; Get rid of Outline menus, they are not needed
2461 ;; Need to do this here because define-derived-mode sets up
2462 ;; the keymap so late.
2463 (if (featurep 'xemacs)
2464 (if org-noutline-p
2465 (progn
2466 (easy-menu-remove outline-mode-menu-heading)
2467 (easy-menu-remove outline-mode-menu-show)
2468 (easy-menu-remove outline-mode-menu-hide))
2469 (delete-menu-item '("Headings"))
2470 (delete-menu-item '("Show"))
2471 (delete-menu-item '("Hide"))
2472 (set-menubar-dirty-flag))
2473 (define-key org-mode-map [menu-bar headings] 'undefined)
2474 (define-key org-mode-map [menu-bar hide] 'undefined)
2475 (define-key org-mode-map [menu-bar show] 'undefined))
2477 (easy-menu-add org-org-menu)
2478 (easy-menu-add org-tbl-menu)
2479 (org-install-agenda-files-menu)
2480 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2481 (org-add-to-invisibility-spec '(org-cwidth))
2482 (when (featurep 'xemacs)
2483 (set (make-local-variable 'line-move-ignore-invisible) t))
2484 (setq outline-regexp "\\*+")
2485 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2486 (setq outline-level 'org-outline-level)
2487 (when (and org-ellipsis (stringp org-ellipsis))
2488 (unless org-display-table
2489 (setq org-display-table (make-display-table)))
2490 (set-display-table-slot org-display-table
2491 4 (string-to-vector org-ellipsis))
2492 (setq buffer-display-table org-display-table))
2493 (org-set-regexps-and-options)
2494 (if org-startup-truncated (setq truncate-lines t))
2495 (set (make-local-variable 'font-lock-unfontify-region-function)
2496 'org-unfontify-region)
2497 ;; Activate before-change-function
2498 (set (make-local-variable 'org-table-may-need-update) t)
2499 (org-add-hook 'before-change-functions 'org-before-change-function nil
2500 'local)
2501 ;; Paragraphs and auto-filling
2502 (org-set-autofill-regexps)
2503 (org-update-radio-target-regexp)
2504 ;; Settings for Calc embedded mode
2505 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2506 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2507 (if (and org-insert-mode-line-in-empty-file
2508 (interactive-p)
2509 (= (point-min) (point-max)))
2510 (insert " -*- mode: org -*-\n\n"))
2512 (unless org-inhibit-startup
2513 (if org-startup-align-all-tables
2514 (org-table-map-tables 'org-table-align))
2515 (if org-startup-with-deadline-check
2516 (call-interactively 'org-check-deadlines)
2517 (cond
2518 ((eq org-startup-folded t)
2519 (org-cycle '(4)))
2520 ((eq org-startup-folded 'content)
2521 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2522 (org-cycle '(4)) (org-cycle '(4))))))))
2524 (defsubst org-current-line (&optional pos)
2525 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2527 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2528 mouse-map t)
2529 "Properties to remove when a string without properties is wanted.")
2531 (defsubst org-match-string-no-properties (num &optional string)
2532 (if (featurep 'xemacs)
2533 (let ((s (match-string num string)))
2534 (remove-text-properties 0 (length s) org-rm-props s)
2536 (match-string-no-properties num string)))
2538 (defsubst org-no-properties (s)
2539 (remove-text-properties 0 (length s) org-rm-props s)
2542 (defun org-current-time ()
2543 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2544 (if (> org-time-stamp-rounding-minutes 0)
2545 (let ((r org-time-stamp-rounding-minutes)
2546 (time (decode-time)))
2547 (apply 'encode-time
2548 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2549 (nthcdr 2 time))))
2550 (current-time)))
2552 (defun org-add-props (string plist &rest props)
2553 "Add text properties to entire string, from beginning to end.
2554 PLIST may be a list of properties, PROPS are individual properties and values
2555 that will be added to PLIST. Returns the string that was modified."
2556 (add-text-properties
2557 0 (length string) (if props (append plist props) plist) string)
2558 string)
2559 (put 'org-add-props 'lisp-indent-function 2)
2562 ;;; Font-Lock stuff
2564 (defvar org-mouse-map (make-sparse-keymap))
2565 (define-key org-mouse-map
2566 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2567 (define-key org-mouse-map
2568 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2569 (when org-mouse-1-follows-link
2570 (define-key org-mouse-map [follow-link] 'mouse-face))
2571 (when org-tab-follows-link
2572 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2573 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2574 (when org-return-follows-link
2575 (define-key org-mouse-map [(return)] 'org-open-at-point)
2576 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2578 (require 'font-lock)
2580 (defconst org-non-link-chars "]\t\n\r<>")
2581 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2582 "wl" "mhe" "rmail" "gnus" "shell"))
2583 (defconst org-link-re-with-space
2584 (concat
2585 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2586 "\\([^" org-non-link-chars " ]"
2587 "[^" org-non-link-chars "]*"
2588 "[^" org-non-link-chars " ]\\)>?")
2589 "Matches a link with spaces, optional angular brackets around it.")
2591 (defconst org-link-re-with-space2
2592 (concat
2593 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2594 "\\([^" org-non-link-chars " ]"
2595 "[^]\t\n\r]*"
2596 "[^" org-non-link-chars " ]\\)>?")
2597 "Matches a link with spaces, optional angular brackets around it.")
2599 (defconst org-angle-link-re
2600 (concat
2601 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2602 "\\([^" org-non-link-chars " ]"
2603 "[^" org-non-link-chars "]*"
2604 "\\)>")
2605 "Matches link with angular brackets, spaces are allowed.")
2606 (defconst org-plain-link-re
2607 (concat
2608 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2609 "\\([^]\t\n\r<>,;() ]+\\)")
2610 "Matches plain link, without spaces.")
2612 (defconst org-bracket-link-regexp
2613 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2614 "Matches a link in double brackets.")
2616 (defconst org-bracket-link-analytic-regexp
2617 (concat
2618 "\\[\\["
2619 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2620 "\\([^]]+\\)"
2621 "\\]"
2622 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2623 "\\]"))
2624 ; 1: http:
2625 ; 2: http
2626 ; 3: path
2627 ; 4: [desc]
2628 ; 5: desc
2631 (defconst org-ts-lengths
2632 (cons (length (format-time-string (car org-time-stamp-formats)))
2633 (length (format-time-string (cdr org-time-stamp-formats))))
2634 "This holds the lengths of the two different time formats.")
2635 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2636 "Regular expression for fast time stamp matching.")
2637 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2638 "Regular expression for fast time stamp matching.")
2639 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2640 "Regular expression matching time strings for analysis.")
2641 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2642 "Regular expression matching time stamps, with groups.")
2643 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2644 "Regular expression matching a time stamp range.")
2645 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2646 org-ts-regexp "\\)?")
2647 "Regular expression matching a time stamp or time stamp range.")
2649 (defun org-activate-plain-links (limit)
2650 "Run through the buffer and add overlays to links."
2651 (if (re-search-forward org-plain-link-re limit t)
2652 (progn
2653 (add-text-properties (match-beginning 0) (match-end 0)
2654 (list 'mouse-face 'highlight
2655 'keymap org-mouse-map
2657 t)))
2659 (defun org-activate-angle-links (limit)
2660 "Run through the buffer and add overlays to links."
2661 (if (re-search-forward org-angle-link-re limit t)
2662 (progn
2663 (add-text-properties (match-beginning 0) (match-end 0)
2664 (list 'mouse-face 'highlight
2665 'keymap org-mouse-map
2667 t)))
2669 (defun org-activate-bracket-links (limit)
2670 "Run through the buffer and add overlays to bracketed links."
2671 (if (re-search-forward org-bracket-link-regexp limit t)
2672 (let* ((help (concat "LINK: "
2673 (org-match-string-no-properties 1)))
2674 ;; FIXME: above we should remove the escapes.
2675 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2676 'keymap org-mouse-map 'mouse-face 'highlight
2677 'help-echo help))
2678 (vp (list 'rear-nonsticky t
2679 'keymap org-mouse-map 'mouse-face 'highlight
2680 'help-echo help)))
2681 ;; We need to remove the invisible property here. Table narrowing
2682 ;; may have made some of this invisible.
2683 (remove-text-properties (match-beginning 0) (match-end 0)
2684 '(invisible nil))
2685 (if (match-end 3)
2686 (progn
2687 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2688 (add-text-properties (match-beginning 3) (match-end 3) vp)
2689 (add-text-properties (match-end 3) (match-end 0) ip))
2690 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2691 (add-text-properties (match-beginning 1) (match-end 1) vp)
2692 (add-text-properties (match-end 1) (match-end 0) ip))
2693 t)))
2695 (defun org-activate-dates (limit)
2696 "Run through the buffer and add overlays to dates."
2697 (if (re-search-forward org-tsr-regexp limit t)
2698 (progn
2699 (add-text-properties (match-beginning 0) (match-end 0)
2700 (list 'mouse-face 'highlight
2701 'keymap org-mouse-map))
2702 t)))
2704 (defvar org-target-link-regexp nil
2705 "Regular expression matching radio targets in plain text.")
2706 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2707 "Regular expression matching a link target.")
2708 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2709 "Regular expression matching a link target.")
2711 (defun org-activate-target-links (limit)
2712 "Run through the buffer and add overlays to target matches."
2713 (when org-target-link-regexp
2714 (let ((case-fold-search t))
2715 (if (re-search-forward org-target-link-regexp limit t)
2716 (progn
2717 (add-text-properties (match-beginning 0) (match-end 0)
2718 (list 'mouse-face 'highlight
2719 'keymap org-mouse-map
2720 'help-echo "Radio target link"
2721 'org-linked-text t))
2722 t)))))
2724 (defun org-update-radio-target-regexp ()
2725 "Find all radio targets in this file and update the regular expression."
2726 (interactive)
2727 (when (memq 'radio org-activate-links)
2728 (setq org-target-link-regexp
2729 (org-make-target-link-regexp (org-all-targets 'radio)))
2730 (org-restart-font-lock)))
2732 (defun org-hide-wide-columns (limit)
2733 (let (s e)
2734 (setq s (text-property-any (point) (or limit (point-max))
2735 'org-cwidth t))
2736 (when s
2737 (setq e (next-single-property-change s 'org-cwidth))
2738 (add-text-properties s e '(invisible org-cwidth intangible t))
2739 (goto-char e)
2740 t)))
2742 (defun org-restart-font-lock ()
2743 "Restart font-lock-mode, to force refontification."
2744 (when (and (boundp 'font-lock-mode) font-lock-mode)
2745 (font-lock-mode -1)
2746 (font-lock-mode 1)))
2748 (defun org-all-targets (&optional radio)
2749 "Return a list of all targets in this file.
2750 With optional argument RADIO, only find radio targets."
2751 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2752 rtn)
2753 (save-excursion
2754 (goto-char (point-min))
2755 (while (re-search-forward re nil t)
2756 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2757 rtn)))
2759 (defun org-make-target-link-regexp (targets)
2760 "Make regular expression matching all strings in TARGETS.
2761 The regular expression finds the targets also if there is a line break
2762 between words."
2763 (and targets
2764 (concat
2765 "\\<\\("
2766 (mapconcat
2767 (lambda (x)
2768 (while (string-match " +" x)
2769 (setq x (replace-match "\\s-+" t t x)))
2771 targets
2772 "\\|")
2773 "\\)\\>")))
2775 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2776 "Matches CamelCase words, possibly with a star before it.")
2778 (defun org-activate-camels (limit)
2779 "Run through the buffer and add overlays to dates."
2780 (if (re-search-forward org-camel-regexp limit t)
2781 (progn
2782 (add-text-properties (match-beginning 0) (match-end 0)
2783 (list 'mouse-face 'highlight
2784 'keymap org-mouse-map))
2785 t)))
2787 (defun org-activate-tags (limit)
2788 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2789 (progn
2790 (add-text-properties (match-beginning 1) (match-end 1)
2791 (list 'mouse-face 'highlight
2792 'keymap org-mouse-map))
2793 t)))
2795 (defun org-font-lock-level ()
2796 (save-excursion
2797 (org-back-to-heading t)
2798 (- (match-end 0) (match-beginning 0))))
2800 (defun org-outline-level ()
2801 (save-excursion
2802 (looking-at outline-regexp)
2803 (if (match-beginning 1)
2804 (+ (org-get-string-indentation (match-string 1)) 1000)
2805 (- (match-end 0) (match-beginning 0)))))
2807 (defvar org-font-lock-keywords nil)
2809 (defun org-set-font-lock-defaults ()
2810 (let* ((em org-fontify-emphasized-text)
2811 (lk org-activate-links)
2812 (org-font-lock-extra-keywords
2813 (list
2814 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2815 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2816 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2817 (1 'org-table))
2818 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2819 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2820 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2821 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2822 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
2823 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2824 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2825 (if org-table-limit-column-width
2826 '(org-hide-wide-columns (0 nil append)))
2827 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2828 '(1 'org-todo t))
2829 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2830 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2831 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2832 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2833 ; (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2834 ; (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2835 ; (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2836 (if em (list org-bold-re 2 ''bold 'prepend))
2837 (if em (list org-italic-re 2 ''italic 'prepend))
2838 (if em (list org-underline-re 2 ''underline 'prepend))
2839 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2840 "\\|" org-quote-string "\\)\\>")
2841 '(1 'org-special-keyword t))
2842 '("^#.*" (0 'font-lock-comment-face t))
2843 (if org-fontify-done-headline
2844 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2845 '(1 'org-done t) '(2 'org-headline-done t))
2846 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2847 '(1 'org-done t)))
2848 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2849 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2850 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2851 (if org-format-transports-properties-p
2852 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
2854 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2855 ;; Now set the full font-lock-keywords
2856 (set (make-local-variable 'org-font-lock-keywords)
2857 org-font-lock-extra-keywords)
2858 (set (make-local-variable 'font-lock-defaults)
2859 '(org-font-lock-keywords t nil nil backward-paragraph))
2860 (kill-local-variable 'font-lock-keywords) nil))
2862 (defvar org-m nil)
2863 (defvar org-l nil)
2864 (defvar org-f nil)
2865 (defun org-get-level-face (n)
2866 "Get the right face for match N in font-lock matching of healdines."
2867 (setq org-l (- (match-end 2) (match-beginning 1)))
2868 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2869 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2870 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2871 (cond
2872 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2873 ((eq n 2) org-f)
2874 (t (if org-level-color-stars-only nil org-f))))
2876 (defun org-unfontify-region (beg end &optional maybe_loudly)
2877 "Remove fontification and activation overlays from links."
2878 (font-lock-default-unfontify-region beg end)
2879 (let* ((buffer-undo-list t)
2880 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2881 (inhibit-modification-hooks t)
2882 deactivate-mark buffer-file-name buffer-file-truename)
2883 (remove-text-properties beg end
2884 '(mouse-face nil keymap nil org-linked-text nil
2885 invisible nil intangible nil))))
2886 ;;; Visibility cycling
2888 (defvar org-cycle-global-status nil)
2889 (defvar org-cycle-subtree-status nil)
2890 (defun org-cycle (&optional arg)
2891 "Visibility cycling for Org-mode.
2893 - When this function is called with a prefix argument, rotate the entire
2894 buffer through 3 states (global cycling)
2895 1. OVERVIEW: Show only top-level headlines.
2896 2. CONTENTS: Show all headlines of all levels, but no body text.
2897 3. SHOW ALL: Show everything.
2899 - When point is at the beginning of a headline, rotate the subtree started
2900 by this line through 3 different states (local cycling)
2901 1. FOLDED: Only the main headline is shown.
2902 2. CHILDREN: The main headline and the direct children are shown.
2903 From this state, you can move to one of the children
2904 and zoom in further.
2905 3. SUBTREE: Show the entire subtree, including body text.
2907 - When there is a numeric prefix, go up to a heading with level ARG, do
2908 a `show-subtree' and return to the previous cursor position. If ARG
2909 is negative, go up that many levels.
2911 - When point is not at the beginning of a headline, execute
2912 `indent-relative', like TAB normally does. See the option
2913 `org-cycle-emulate-tab' for details.
2915 - Special case: if point is the the beginning of the buffer and there is
2916 no headline in line 1, this function will act as if called with prefix arg."
2917 (interactive "P")
2919 (if (or (and (bobp) (not (looking-at outline-regexp)))
2920 (equal arg '(4)))
2921 ;; special case: use global cycling
2922 (setq arg t))
2924 (let ((outline-regexp
2925 (if org-cycle-include-plain-lists
2926 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2927 outline-regexp)))
2929 (cond
2931 ((org-at-table-p 'any)
2932 ;; Enter the table or move to the next field in the table
2933 (or (org-table-recognize-table.el)
2934 (progn
2935 (if arg (org-table-edit-field t)
2936 (org-table-justify-field-maybe)
2937 (org-table-next-field)))))
2939 ((eq arg t) ;; Global cycling
2941 (cond
2942 ((and (eq last-command this-command)
2943 (eq org-cycle-global-status 'overview))
2944 ;; We just created the overview - now do table of contents
2945 ;; This can be slow in very large buffers, so indicate action
2946 (message "CONTENTS...")
2947 (save-excursion
2948 ;; Visit all headings and show their offspring
2949 (goto-char (point-max))
2950 (catch 'exit
2951 (while (and (progn (condition-case nil
2952 (outline-previous-visible-heading 1)
2953 (error (goto-char (point-min))))
2955 (looking-at outline-regexp))
2956 (show-branches)
2957 (if (bobp) (throw 'exit nil))))
2958 (message "CONTENTS...done"))
2959 (setq org-cycle-global-status 'contents)
2960 (run-hook-with-args 'org-cycle-hook 'contents))
2962 ((and (eq last-command this-command)
2963 (eq org-cycle-global-status 'contents))
2964 ;; We just showed the table of contents - now show everything
2965 (show-all)
2966 (message "SHOW ALL")
2967 (setq org-cycle-global-status 'all)
2968 (run-hook-with-args 'org-cycle-hook 'all))
2971 ;; Default action: go to overview
2972 (hide-sublevels 1)
2973 (message "OVERVIEW")
2974 (setq org-cycle-global-status 'overview)
2975 (run-hook-with-args 'org-cycle-hook 'overview))))
2977 ((integerp arg)
2978 ;; Show-subtree, ARG levels up from here.
2979 (save-excursion
2980 (org-back-to-heading)
2981 (outline-up-heading (if (< arg 0) (- arg)
2982 (- (funcall outline-level) arg)))
2983 (org-show-subtree)))
2985 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2986 ;; At a heading: rotate between three different views
2987 (org-back-to-heading)
2988 (let ((goal-column 0) eoh eol eos)
2989 ;; First, some boundaries
2990 (save-excursion
2991 (org-back-to-heading)
2992 (save-excursion
2993 (beginning-of-line 2)
2994 (while (and (not (eobp)) ;; this is like `next-line'
2995 (get-char-property (1- (point)) 'invisible))
2996 (beginning-of-line 2)) (setq eol (point)))
2997 (outline-end-of-heading) (setq eoh (point))
2998 (org-end-of-subtree t) (setq eos (point))
2999 (outline-next-heading))
3000 ;; Find out what to do next and set `this-command'
3001 (cond
3002 ((= eos eoh)
3003 ;; Nothing is hidden behind this heading
3004 (message "EMPTY ENTRY")
3005 (setq org-cycle-subtree-status nil))
3006 ((>= eol eos)
3007 ;; Entire subtree is hidden in one line: open it
3008 (org-show-entry)
3009 (show-children)
3010 (message "CHILDREN")
3011 (setq org-cycle-subtree-status 'children)
3012 (run-hook-with-args 'org-cycle-hook 'children))
3013 ((and (eq last-command this-command)
3014 (eq org-cycle-subtree-status 'children))
3015 ;; We just showed the children, now show everything.
3016 (org-show-subtree)
3017 (message "SUBTREE")
3018 (setq org-cycle-subtree-status 'subtree)
3019 (run-hook-with-args 'org-cycle-hook 'subtree))
3021 ;; Default action: hide the subtree.
3022 (hide-subtree)
3023 (message "FOLDED")
3024 (setq org-cycle-subtree-status 'folded)
3025 (run-hook-with-args 'org-cycle-hook 'folded)))))
3027 ;; TAB emulation
3028 (buffer-read-only (org-back-to-heading))
3029 ((if (and (eq org-cycle-emulate-tab 'white)
3030 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
3032 (eq org-cycle-emulate-tab t))
3033 (if (and (looking-at "[ \n\r\t]")
3034 (string-match "^[ \t]*$" (buffer-substring
3035 (point-at-bol) (point))))
3036 (progn
3037 (beginning-of-line 1)
3038 (and (looking-at "[ \t]+") (replace-match ""))))
3039 (indent-relative))
3041 (t (save-excursion
3042 (org-back-to-heading)
3043 (org-cycle))))))
3045 (defun org-optimize-window-after-visibility-change (state)
3046 "Adjust the window after a change in outline visibility.
3047 This function is the default value of the hook `org-cycle-hook'."
3048 (when (get-buffer-window (current-buffer))
3049 (cond
3050 ((eq state 'overview) (org-first-headline-recenter 1))
3051 ((eq state 'content) nil)
3052 ((eq state 'all) nil)
3053 ((eq state 'folded) nil)
3054 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3055 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3057 (defun org-subtree-end-visible-p ()
3058 "Is the end of the current subtree visible?"
3059 (pos-visible-in-window-p
3060 (save-excursion (org-end-of-subtree t) (point))))
3062 (defun org-first-headline-recenter (&optional N)
3063 "Move cursor to the first headline and recenter the headline.
3064 Optional argument N means, put the headline into the Nth line of the window."
3065 (goto-char (point-min))
3066 (when (re-search-forward (concat "^" outline-regexp) nil t)
3067 (beginning-of-line)
3068 (recenter (prefix-numeric-value N))))
3070 (defvar org-goto-window-configuration nil)
3071 (defvar org-goto-marker nil)
3072 (defvar org-goto-map (make-sparse-keymap))
3073 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3074 (while (setq cmd (pop cmds))
3075 (substitute-key-definition cmd cmd org-goto-map global-map)))
3076 (define-key org-goto-map "\C-m" 'org-goto-ret)
3077 (define-key org-goto-map [(left)] 'org-goto-left)
3078 (define-key org-goto-map [(right)] 'org-goto-right)
3079 (define-key org-goto-map [(?q)] 'org-goto-quit)
3080 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3081 (define-key org-goto-map "\C-i" 'org-cycle)
3082 (define-key org-goto-map [(tab)] 'org-cycle)
3083 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3084 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3085 (define-key org-goto-map "n" 'outline-next-visible-heading)
3086 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3087 (define-key org-goto-map "f" 'outline-forward-same-level)
3088 (define-key org-goto-map "b" 'outline-backward-same-level)
3089 (define-key org-goto-map "u" 'outline-up-heading)
3090 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3091 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3092 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3093 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3094 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3095 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3096 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3098 (defconst org-goto-help
3099 "Select a location to jump to, press RET
3100 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3102 (defun org-goto ()
3103 "Go to a different location of the document, keeping current visibility.
3105 When you want to go to a different location in a document, the fastest way
3106 is often to fold the entire buffer and then dive into the tree. This
3107 method has the disadvantage, that the previous location will be folded,
3108 which may not be what you want.
3110 This command works around this by showing a copy of the current buffer in
3111 overview mode. You can dive into the tree in that copy, to find the
3112 location you want to reach. When pressing RET, the command returns to the
3113 original buffer in which the visibility is still unchanged. It then jumps
3114 to the new location, making it and the headline hierarchy above it visible."
3115 (interactive)
3116 (let* ((org-goto-start-pos (point))
3117 (selected-point
3118 (org-get-location (current-buffer) org-goto-help)))
3119 (if selected-point
3120 (progn
3121 (org-mark-ring-push org-goto-start-pos)
3122 (goto-char selected-point)
3123 (if (or (org-invisible-p) (org-invisible-p2))
3124 (org-show-hierarchy-above)))
3125 (error "Quit"))))
3127 (defun org-get-location (buf help)
3128 "Let the user select a location in the Org-mode buffer BUF.
3129 This function uses a recursive edit. It returns the selected position
3130 or nil."
3131 (let (org-selected-point)
3132 (save-excursion
3133 (save-window-excursion
3134 (delete-other-windows)
3135 (switch-to-buffer (get-buffer-create "*org-goto*"))
3136 (with-output-to-temp-buffer "*Help*"
3137 (princ help))
3138 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3139 (setq buffer-read-only nil)
3140 (erase-buffer)
3141 (insert-buffer-substring buf)
3142 (let ((org-startup-truncated t)
3143 (org-startup-folded t)
3144 (org-startup-align-all-tables nil)
3145 (org-startup-with-deadline-check nil))
3146 (org-mode))
3147 (setq buffer-read-only t)
3148 (if (boundp 'org-goto-start-pos)
3149 (goto-char org-goto-start-pos)
3150 (goto-char (point-min)))
3151 (org-beginning-of-line)
3152 (message "Select location and press RET")
3153 ;; now we make sure that during selection, ony very few keys work
3154 ;; and that it is impossible to switch to another window.
3155 (let ((gm (current-global-map))
3156 (overriding-local-map org-goto-map))
3157 (unwind-protect
3158 (progn
3159 (use-global-map org-goto-map)
3160 (recursive-edit))
3161 (use-global-map gm)))))
3162 (kill-buffer "*org-goto*")
3163 org-selected-point))
3165 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3166 (defun org-goto-ret (&optional arg)
3167 "Finish `org-goto' by going to the new location."
3168 (interactive "P")
3169 (setq org-selected-point (point)
3170 current-prefix-arg arg)
3171 (throw 'exit nil))
3173 (defun org-goto-left ()
3174 "Finish `org-goto' by going to the new location."
3175 (interactive)
3176 (if (org-on-heading-p)
3177 (progn
3178 (beginning-of-line 1)
3179 (setq org-selected-point (point)
3180 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3181 (throw 'exit nil))
3182 (error "Not on a heading")))
3184 (defun org-goto-right ()
3185 "Finish `org-goto' by going to the new location."
3186 (interactive)
3187 (if (org-on-heading-p)
3188 (progn
3189 (outline-end-of-subtree)
3190 (or (eobp) (forward-char 1))
3191 (setq org-selected-point (point)
3192 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3193 (throw 'exit nil))
3194 (error "Not on a heading")))
3196 (defun org-goto-quit ()
3197 "Finish `org-goto' without cursor motion."
3198 (interactive)
3199 (setq org-selected-point nil)
3200 (throw 'exit nil))
3202 ;;; Promotion, Demotion, Inserting new headlines
3204 (defvar org-ignore-region nil
3205 "To temporarily disable the active region.")
3207 ;; FIXME: Fix behavior if point is on the stars but not at bol.
3208 (defun org-insert-heading (&optional force-heading)
3209 "Insert a new heading or item with same depth at point.
3210 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3211 If point is at the beginning of a headline, insert a sibling before the
3212 current headline. If point is in the middle of a headline, split the headline
3213 at that position and make the rest of the headline part of the sibling below
3214 the current headline."
3215 (interactive "P")
3216 (if (= (buffer-size) 0)
3217 (insert "\n* ")
3218 (when (or force-heading (not (org-insert-item)))
3219 (let* ((head (save-excursion
3220 (condition-case nil
3221 (org-back-to-heading)
3222 (error (outline-next-heading)))
3223 (prog1 (match-string 0)
3224 (funcall outline-level))))
3225 pos)
3226 (cond
3227 ((and (org-on-heading-p) (bolp)
3228 (save-excursion (backward-char 1) (not (org-invisible-p))))
3229 (open-line 1))
3230 ((bolp) nil)
3231 (t (newline)))
3232 (insert head) (just-one-space)
3233 (setq pos (point))
3234 (end-of-line 1)
3235 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3236 (run-hooks 'org-insert-heading-hook)))))
3238 (defun org-insert-item ()
3239 "Insert a new item at the current level.
3240 Return t when things worked, nil when we are not in an item."
3241 (when (save-excursion
3242 (condition-case nil
3243 (progn
3244 (org-beginning-of-item)
3245 (org-at-item-p)
3247 (error nil)))
3248 (let* ((bul (match-string 0))
3249 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3250 (match-end 0)))
3251 (eowcol (save-excursion (goto-char eow) (current-column)))
3252 pos)
3253 (cond
3254 ((and (org-at-item-p) (<= (point) eow))
3255 ;; before the bullet
3256 (beginning-of-line 1)
3257 (open-line 1))
3258 ((<= (point) eow)
3259 (beginning-of-line 1))
3260 (t (newline)))
3261 (insert bul)
3262 (just-one-space)
3263 (setq pos (point))
3264 (end-of-line 1)
3265 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3266 (org-maybe-renumber-ordered-list)
3269 (defun org-insert-todo-heading (arg)
3270 "Insert a new heading with the same level and TODO state as current heading.
3271 If the heading has no TODO state, or if the state is DONE, use the first
3272 state (TODO by default). Also with prefix arg, force first state."
3273 (interactive "P")
3274 (org-insert-heading)
3275 (save-excursion
3276 (org-back-to-heading)
3277 (if org-noutline-p
3278 (outline-previous-heading)
3279 (outline-previous-visible-heading t))
3280 (looking-at org-todo-line-regexp))
3281 (if (or arg
3282 (not (match-beginning 2))
3283 (equal (match-string 2) org-done-string))
3284 (insert (car org-todo-keywords) " ")
3285 (insert (match-string 2) " ")))
3287 (defun org-promote-subtree ()
3288 "Promote the entire subtree.
3289 See also `org-promote'."
3290 (interactive)
3291 (save-excursion
3292 (org-map-tree 'org-promote)))
3294 (defun org-demote-subtree ()
3295 "Demote the entire subtree. See `org-demote'.
3296 See also `org-promote'."
3297 (interactive)
3298 (save-excursion
3299 (org-map-tree 'org-demote)))
3301 (defun org-do-promote ()
3302 "Promote the current heading higher up the tree.
3303 If the region is active in `transient-mark-mode', promote all headings
3304 in the region."
3305 (interactive)
3306 (save-excursion
3307 (if (org-region-active-p)
3308 (org-map-region 'org-promote (region-beginning) (region-end))
3309 (org-promote)))
3310 (org-fix-position-after-promote))
3312 (defun org-do-demote ()
3313 "Demote the current heading lower down the tree.
3314 If the region is active in `transient-mark-mode', demote all headings
3315 in the region."
3316 (interactive)
3317 (save-excursion
3318 (if (org-region-active-p)
3319 (org-map-region 'org-demote (region-beginning) (region-end))
3320 (org-demote)))
3321 (org-fix-position-after-promote))
3323 (defun org-fix-position-after-promote ()
3324 "Make sure that after pro/demotion cursor position is right."
3325 (and (equal (char-after) ?\ )
3326 (equal (char-before) ?*)
3327 (forward-char 1)))
3329 (defun org-get-legal-level (level change)
3330 "Rectify a level change under the influence of `org-odd-levels-only'
3331 LEVEL is a current level, CHANGE is by how much the level should be
3332 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3333 even level numbers will become the next higher odd number."
3334 (if org-odd-levels-only
3335 (cond ((not change) (1+ (* 2 (/ level 2))))
3336 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3337 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3338 (max 1 (+ level change))))
3340 (defun org-promote ()
3341 "Promote the current heading higher up the tree.
3342 If the region is active in `transient-mark-mode', promote all headings
3343 in the region."
3344 (org-back-to-heading t)
3345 (let* ((level (save-match-data (funcall outline-level)))
3346 (up-head (make-string (org-get-legal-level level -1) ?*))
3347 (diff (abs (- level (length up-head)))))
3348 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3349 (replace-match up-head nil t)
3350 ;; Fixup tag positioning
3351 (and org-auto-align-tags (org-set-tags nil t))
3352 (if org-adapt-indentation
3353 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3354 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3356 (defun org-demote ()
3357 "Demote the current heading lower down the tree.
3358 If the region is active in `transient-mark-mode', demote all headings
3359 in the region."
3360 (org-back-to-heading t)
3361 (let* ((level (save-match-data (funcall outline-level)))
3362 (down-head (make-string (org-get-legal-level level 1) ?*))
3363 (diff (abs (- level (length down-head)))))
3364 (replace-match down-head nil t)
3365 ;; Fixup tag positioning
3366 (and org-auto-align-tags (org-set-tags nil t))
3367 (if org-adapt-indentation
3368 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3370 (defun org-map-tree (fun)
3371 "Call FUN for every heading underneath the current one."
3372 (org-back-to-heading)
3373 (let ((level (funcall outline-level)))
3374 (save-excursion
3375 (funcall fun)
3376 (while (and (progn
3377 (outline-next-heading)
3378 (> (funcall outline-level) level))
3379 (not (eobp)))
3380 (funcall fun)))))
3382 (defun org-map-region (fun beg end)
3383 "Call FUN for every heading between BEG and END."
3384 (let ((org-ignore-region t))
3385 (save-excursion
3386 (setq end (copy-marker end))
3387 (goto-char beg)
3388 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3389 (< (point) end))
3390 (funcall fun))
3391 (while (and (progn
3392 (outline-next-heading)
3393 (< (point) end))
3394 (not (eobp)))
3395 (funcall fun)))))
3397 (defun org-fixup-indentation (from to prohibit)
3398 "Change the indentation in the current entry by re-replacing FROM with TO.
3399 However, if the regexp PROHIBIT matches at all, don't do anything.
3400 This is being used to change indentation along with the length of the
3401 heading marker. But if there are any lines which are not indented, nothing
3402 is changed at all."
3403 (save-excursion
3404 (let ((end (save-excursion (outline-next-heading)
3405 (point-marker))))
3406 (unless (save-excursion (re-search-forward prohibit end t))
3407 (while (re-search-forward from end t)
3408 (replace-match to)
3409 (beginning-of-line 2)))
3410 (move-marker end nil))))
3412 ;;; Vertical tree motion, cutting and pasting of subtrees
3414 (defun org-move-subtree-up (&optional arg)
3415 "Move the current subtree up past ARG headlines of the same level."
3416 (interactive "p")
3417 (org-move-subtree-down (- (prefix-numeric-value arg))))
3419 (defun org-move-subtree-down (&optional arg)
3420 "Move the current subtree down past ARG headlines of the same level."
3421 (interactive "p")
3422 (setq arg (prefix-numeric-value arg))
3423 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3424 'outline-get-last-sibling))
3425 (ins-point (make-marker))
3426 (cnt (abs arg))
3427 beg end txt folded)
3428 ;; Select the tree
3429 (org-back-to-heading)
3430 (setq beg (point))
3431 (save-match-data
3432 (save-excursion (outline-end-of-heading)
3433 (setq folded (org-invisible-p)))
3434 (outline-end-of-subtree))
3435 (outline-next-heading)
3436 (setq end (point))
3437 ;; Find insertion point, with error handling
3438 (goto-char beg)
3439 (while (> cnt 0)
3440 (or (and (funcall movfunc) (looking-at outline-regexp))
3441 (progn (goto-char beg)
3442 (error "Cannot move past superior level or buffer limit")))
3443 (setq cnt (1- cnt)))
3444 (if (> arg 0)
3445 ;; Moving forward - still need to move over subtree
3446 (progn (outline-end-of-subtree)
3447 (outline-next-heading)
3448 (if (not (or (looking-at (concat "^" outline-regexp))
3449 (bolp)))
3450 (newline))))
3451 (move-marker ins-point (point))
3452 (setq txt (buffer-substring beg end))
3453 (delete-region beg end)
3454 (insert txt)
3455 (goto-char ins-point)
3456 (if folded (hide-subtree))
3457 (move-marker ins-point nil)))
3459 (defvar org-subtree-clip ""
3460 "Clipboard for cut and paste of subtrees.
3461 This is actually only a copy of the kill, because we use the normal kill
3462 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3464 (defvar org-subtree-clip-folded nil
3465 "Was the last copied subtree folded?
3466 This is used to fold the tree back after pasting.")
3468 (defun org-cut-subtree ()
3469 "Cut the current subtree into the clipboard.
3470 This is a short-hand for marking the subtree and then cutting it."
3471 (interactive)
3472 (org-copy-subtree 'cut))
3474 (defun org-copy-subtree (&optional cut)
3475 "Cut the current subtree into the clipboard.
3476 This is a short-hand for marking the subtree and then copying it.
3477 If CUT is non nil, actually cut the subtree."
3478 (interactive)
3479 (let (beg end folded)
3480 (org-back-to-heading)
3481 (setq beg (point))
3482 (save-match-data
3483 (save-excursion (outline-end-of-heading)
3484 (setq folded (org-invisible-p)))
3485 (outline-end-of-subtree))
3486 (if (equal (char-after) ?\n) (forward-char 1))
3487 (setq end (point))
3488 (goto-char beg)
3489 (when (> end beg)
3490 (setq org-subtree-clip-folded folded)
3491 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3492 (setq org-subtree-clip (current-kill 0))
3493 (message "%s: Subtree with %d characters"
3494 (if cut "Cut" "Copied")
3495 (length org-subtree-clip)))))
3497 (defun org-paste-subtree (&optional level tree)
3498 "Paste the clipboard as a subtree, with modification of headline level.
3499 The entire subtree is promoted or demoted in order to match a new headline
3500 level. By default, the new level is derived from the visible headings
3501 before and after the insertion point, and taken to be the inferior headline
3502 level of the two. So if the previous visible heading is level 3 and the
3503 next is level 4 (or vice versa), level 4 will be used for insertion.
3504 This makes sure that the subtree remains an independent subtree and does
3505 not swallow low level entries.
3507 You can also force a different level, either by using a numeric prefix
3508 argument, or by inserting the heading marker by hand. For example, if the
3509 cursor is after \"*****\", then the tree will be shifted to level 5.
3511 If you want to insert the tree as is, just use \\[yank].
3513 If optional TREE is given, use this text instead of the kill ring."
3514 (interactive "P")
3515 (unless (org-kill-is-subtree-p tree)
3516 (error
3517 (substitute-command-keys
3518 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3519 (let* ((txt (or tree (current-kill 0)))
3520 (^re (concat "^\\(" outline-regexp "\\)"))
3521 (re (concat "\\(" outline-regexp "\\)"))
3522 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3524 (old-level (if (string-match ^re txt)
3525 (- (match-end 0) (match-beginning 0))
3526 -1))
3527 (force-level (cond (level (prefix-numeric-value level))
3528 ((string-match
3529 ^re_ (buffer-substring (point-at-bol) (point)))
3530 (- (match-end 0) (match-beginning 0)))
3531 (t nil)))
3532 (previous-level (save-excursion
3533 (condition-case nil
3534 (progn
3535 (outline-previous-visible-heading 1)
3536 (if (looking-at re)
3537 (- (match-end 0) (match-beginning 0))
3539 (error 1))))
3540 (next-level (save-excursion
3541 (condition-case nil
3542 (progn
3543 (outline-next-visible-heading 1)
3544 (if (looking-at re)
3545 (- (match-end 0) (match-beginning 0))
3547 (error 1))))
3548 (new-level (or force-level (max previous-level next-level)))
3549 (shift (if (or (= old-level -1)
3550 (= new-level -1)
3551 (= old-level new-level))
3553 (- new-level old-level)))
3554 (shift1 shift)
3555 (delta (if (> shift 0) -1 1))
3556 (func (if (> shift 0) 'org-demote 'org-promote))
3557 (org-odd-levels-only nil)
3558 beg end)
3559 ;; Remove the forces level indicator
3560 (if force-level
3561 (delete-region (point-at-bol) (point)))
3562 ;; Make sure we start at the beginning of an empty line
3563 (if (not (bolp)) (insert "\n"))
3564 (if (not (looking-at "[ \t]*$"))
3565 (progn (insert "\n") (backward-char 1)))
3566 ;; Paste
3567 (setq beg (point))
3568 (insert txt)
3569 (setq end (point))
3570 (goto-char beg)
3571 ;; Shift if necessary
3572 (if (= shift 0)
3573 (message "Pasted at level %d, without shift" new-level)
3574 (save-restriction
3575 (narrow-to-region beg end)
3576 (while (not (= shift 0))
3577 (org-map-region func (point-min) (point-max))
3578 (setq shift (+ delta shift)))
3579 (goto-char (point-min))
3580 (message "Pasted at level %d, with shift by %d levels"
3581 new-level shift1)))
3582 (if (and (eq org-subtree-clip (current-kill 0))
3583 org-subtree-clip-folded)
3584 ;; The tree was folded before it was killed/copied
3585 (hide-subtree))))
3587 (defun org-kill-is-subtree-p (&optional txt)
3588 "Check if the current kill is an outline subtree, or a set of trees.
3589 Returns nil if kill does not start with a headline, or if the first
3590 headline level is not the largest headline level in the tree.
3591 So this will actually accept several entries of equal levels as well,
3592 which is OK for `org-paste-subtree'.
3593 If optional TXT is given, check this string instead of the current kill."
3594 (let* ((kill (or txt (current-kill 0) ""))
3595 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3596 (- (match-end 0) (match-beginning 0))))
3597 (re (concat "^" outline-regexp))
3598 (start 1))
3599 (if (not start-level)
3600 nil ;; does not even start with a heading
3601 (catch 'exit
3602 (while (setq start (string-match re kill (1+ start)))
3603 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3604 (throw 'exit nil)))
3605 t))))
3607 ;;; Plain list items
3609 (defun org-at-item-p ()
3610 "Is point in a line starting a hand-formatted item?"
3611 (let ((llt org-plain-list-ordered-item-terminator))
3612 (save-excursion
3613 (goto-char (point-at-bol))
3614 (looking-at
3615 (cond
3616 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3617 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3618 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3619 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3621 (defun org-get-indentation ()
3622 "Get the indentation of the current line, interpreting tabs."
3623 (save-excursion
3624 (beginning-of-line 1)
3625 (skip-chars-forward " \t")
3626 (current-column)))
3628 (defun org-beginning-of-item ()
3629 "Go to the beginning of the current hand-formatted item.
3630 If the cursor is not in an item, throw an error."
3631 (let ((pos (point))
3632 (limit (save-excursion (org-back-to-heading)
3633 (beginning-of-line 2) (point)))
3634 ind ind1)
3635 (if (org-at-item-p)
3636 (beginning-of-line 1)
3637 (beginning-of-line 1)
3638 (skip-chars-forward " \t")
3639 (setq ind (current-column))
3640 (if (catch 'exit
3641 (while t
3642 (beginning-of-line 0)
3643 (if (< (point) limit) (throw 'exit nil))
3644 (unless (looking-at " \t]*$")
3645 (skip-chars-forward " \t")
3646 (setq ind1 (current-column))
3647 (if (< ind1 ind)
3648 (throw 'exit (org-at-item-p))))))
3650 (goto-char pos)
3651 (error "Not in an item")))))
3653 (defun org-end-of-item ()
3654 "Go to the end of the current hand-formatted item.
3655 If the cursor is not in an item, throw an error."
3656 (let ((pos (point))
3657 (limit (save-excursion (outline-next-heading) (point)))
3658 (ind (save-excursion
3659 (org-beginning-of-item)
3660 (skip-chars-forward " \t")
3661 (current-column)))
3662 ind1)
3663 (if (catch 'exit
3664 (while t
3665 (beginning-of-line 2)
3666 (if (>= (point) limit) (throw 'exit t))
3667 (unless (looking-at "[ \t]*$")
3668 (skip-chars-forward " \t")
3669 (setq ind1 (current-column))
3670 (if (<= ind1 ind) (throw 'exit t)))))
3671 (beginning-of-line 1)
3672 (goto-char pos)
3673 (error "Not in an item"))))
3675 (defun org-move-item-down (arg)
3676 "Move the plain list item at point down, i.e. swap with following item.
3677 Subitems (items with larger indentation) are considered part of the item,
3678 so this really moves item trees."
3679 (interactive "p")
3680 (let (beg end ind ind1 (pos (point)) txt)
3681 (org-beginning-of-item)
3682 (setq beg (point))
3683 (setq ind (org-get-indentation))
3684 (org-end-of-item)
3685 (setq end (point))
3686 (setq ind1 (org-get-indentation))
3687 (if (and (org-at-item-p) (= ind ind1))
3688 (progn
3689 (org-end-of-item)
3690 (setq txt (buffer-substring beg end))
3691 (save-excursion
3692 (delete-region beg end))
3693 (setq pos (point))
3694 (insert txt)
3695 (goto-char pos)
3696 (org-maybe-renumber-ordered-list))
3697 (goto-char pos)
3698 (error "Cannot move this item further down"))))
3700 (defun org-move-item-up (arg)
3701 "Move the plain list item at point up, i.e. swap with previous item.
3702 Subitems (items with larger indentation) are considered part of the item,
3703 so this really moves item trees."
3704 (interactive "p")
3705 (let (beg end ind ind1 (pos (point)) txt)
3706 (org-beginning-of-item)
3707 (setq beg (point))
3708 (setq ind (org-get-indentation))
3709 (org-end-of-item)
3710 (setq end (point))
3711 (goto-char beg)
3712 (catch 'exit
3713 (while t
3714 (beginning-of-line 0)
3715 (if (looking-at "[ \t]*$")
3717 (if (<= (setq ind1 (org-get-indentation)) ind)
3718 (throw 'exit t)))))
3719 (condition-case nil
3720 (org-beginning-of-item)
3721 (error (goto-char beg)
3722 (error "Cannot move this item further up")))
3723 (setq ind1 (org-get-indentation))
3724 (if (and (org-at-item-p) (= ind ind1))
3725 (progn
3726 (setq txt (buffer-substring beg end))
3727 (save-excursion
3728 (delete-region beg end))
3729 (setq pos (point))
3730 (insert txt)
3731 (goto-char pos)
3732 (org-maybe-renumber-ordered-list))
3733 (goto-char pos)
3734 (error "Cannot move this item further up"))))
3736 (defun org-maybe-renumber-ordered-list ()
3737 "Renumber the ordered list at point if setup allows it.
3738 This tests the user option `org-auto-renumber-ordered-lists' before
3739 doing the renumbering."
3740 (and org-auto-renumber-ordered-lists
3741 (org-at-item-p)
3742 (match-beginning 3)
3743 (org-renumber-ordered-list 1)))
3745 (defun org-get-string-indentation (s)
3746 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3747 (let ((n -1) (i 0) (w tab-width) c)
3748 (catch 'exit
3749 (while (< (setq n (1+ n)) (length s))
3750 (setq c (aref s n))
3751 (cond ((= c ?\ ) (setq i (1+ i)))
3752 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3753 (t (throw 'exit t)))))
3756 (defun org-renumber-ordered-list (arg)
3757 "Renumber an ordered plain list.
3758 Cursor next to be in the first line of an item, the line that starts
3759 with something like \"1.\" or \"2)\"."
3760 (interactive "p")
3761 (unless (and (org-at-item-p)
3762 (match-beginning 3))
3763 (error "This is not an ordered list"))
3764 (let ((line (org-current-line))
3765 (col (current-column))
3766 (ind (org-get-string-indentation
3767 (buffer-substring (point-at-bol) (match-beginning 3))))
3768 ;; (term (substring (match-string 3) -1))
3769 ind1 (n (1- arg)))
3770 ;; find where this list begins
3771 (catch 'exit
3772 (while t
3773 (catch 'next
3774 (beginning-of-line 0)
3775 (if (looking-at "[ \t]*$") (throw 'next t))
3776 (skip-chars-forward " \t") (setq ind1 (current-column))
3777 (if (or (< ind1 ind)
3778 (and (= ind1 ind)
3779 (not (org-at-item-p))))
3780 (throw 'exit t)))))
3781 ;; Walk forward and replace these numbers
3782 (catch 'exit
3783 (while t
3784 (catch 'next
3785 (beginning-of-line 2)
3786 (if (eobp) (throw 'exit nil))
3787 (if (looking-at "[ \t]*$") (throw 'next nil))
3788 (skip-chars-forward " \t") (setq ind1 (current-column))
3789 (if (> ind1 ind) (throw 'next t))
3790 (if (< ind1 ind) (throw 'exit t))
3791 (if (not (org-at-item-p)) (throw 'exit nil))
3792 (if (not (match-beginning 3))
3793 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3794 (delete-region (match-beginning 3) (1- (match-end 3)))
3795 (goto-char (match-beginning 3))
3796 (insert (format "%d" (setq n (1+ n)))))))
3797 (goto-line line)
3798 (move-to-column col)))
3800 (defvar org-last-indent-begin-marker (make-marker))
3801 (defvar org-last-indent-end-marker (make-marker))
3803 (defun org-outdent-item (arg)
3804 "Outdent a local list item."
3805 (interactive "p")
3806 (org-indent-item (- arg)))
3808 (defun org-indent-item (arg)
3809 "Indent a local list item."
3810 (interactive "p")
3811 (unless (org-at-item-p)
3812 (error "Not on an item"))
3813 (let (beg end ind ind1)
3814 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3815 (setq beg org-last-indent-begin-marker
3816 end org-last-indent-end-marker)
3817 (org-beginning-of-item)
3818 (setq beg (move-marker org-last-indent-begin-marker (point)))
3819 (org-end-of-item)
3820 (setq end (move-marker org-last-indent-end-marker (point))))
3821 (goto-char beg)
3822 (skip-chars-forward " \t") (setq ind (current-column))
3823 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3824 (while (< (point) end)
3825 (beginning-of-line 1)
3826 (skip-chars-forward " \t") (setq ind1 (current-column))
3827 (delete-region (point-at-bol) (point))
3828 (indent-to-column (+ ind1 arg))
3829 (beginning-of-line 2))
3830 (goto-char beg)))
3832 ;;; Archiving
3834 (defun org-archive-subtree ()
3835 "Move the current subtree to the archive.
3836 The archive can be a certain top-level heading in the current file, or in
3837 a different file. The tree will be moved to that location, the subtree
3838 heading be marked DONE, and the current time will be added."
3839 (interactive)
3840 ;; Save all relevant TODO keyword-relatex variables
3841 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3842 (tr-org-todo-keywords org-todo-keywords)
3843 (tr-org-todo-interpretation org-todo-interpretation)
3844 (tr-org-done-string org-done-string)
3845 (tr-org-todo-regexp org-todo-regexp)
3846 (tr-org-todo-line-regexp org-todo-line-regexp)
3847 (this-buffer (current-buffer))
3848 file heading buffer level newfile-p)
3849 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3850 (progn
3851 (setq file (format (match-string 1 org-archive-location)
3852 (file-name-nondirectory buffer-file-name))
3853 heading (match-string 2 org-archive-location)))
3854 (error "Invalid `org-archive-location'"))
3855 (if (> (length file) 0)
3856 (setq newfile-p (not (file-exists-p file))
3857 buffer (find-file-noselect file))
3858 (setq buffer (current-buffer)))
3859 (unless buffer
3860 (error "Cannot access file \"%s\"" file))
3861 (if (and (> (length heading) 0)
3862 (string-match "^\\*+" heading))
3863 (setq level (match-end 0))
3864 (setq heading nil level 0))
3865 (save-excursion
3866 ;; We first only copy, in case something goes wrong
3867 ;; we need to protect this-command, to avoid kill-region sets it,
3868 ;; which would lead to duplication of subtrees
3869 (let (this-command) (org-copy-subtree))
3870 (set-buffer buffer)
3871 ;; Enforce org-mode for the archive buffer
3872 (if (not (eq major-mode 'org-mode))
3873 ;; Force the mode for future visits.
3874 (let ((org-insert-mode-line-in-empty-file t))
3875 (call-interactively 'org-mode)))
3876 (when newfile-p
3877 (goto-char (point-max))
3878 (insert (format "\nArchived entries from file %s\n\n"
3879 (buffer-file-name this-buffer))))
3880 ;; Force the TODO keywords of the original buffer
3881 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3882 (org-todo-keywords tr-org-todo-keywords)
3883 (org-todo-interpretation tr-org-todo-interpretation)
3884 (org-done-string tr-org-done-string)
3885 (org-todo-regexp tr-org-todo-regexp)
3886 (org-todo-line-regexp tr-org-todo-line-regexp))
3887 (goto-char (point-min))
3888 (if heading
3889 (progn
3890 (if (re-search-forward
3891 (concat "\\(^\\|\r\\)"
3892 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3893 nil t)
3894 (goto-char (match-end 0))
3895 ;; Heading not found, just insert it at the end
3896 (goto-char (point-max))
3897 (or (bolp) (insert "\n"))
3898 (insert "\n" heading "\n")
3899 (end-of-line 0))
3900 ;; Make the heading visible, and the following as well
3901 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3902 (if (re-search-forward
3903 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3904 nil t)
3905 (progn (goto-char (match-beginning 0)) (insert "\n")
3906 (beginning-of-line 0))
3907 (goto-char (point-max)) (insert "\n")))
3908 (goto-char (point-max)) (insert "\n"))
3909 ;; Paste
3910 (org-paste-subtree (1+ level))
3911 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3912 (if org-archive-mark-done
3913 (org-todo (length org-todo-keywords)))
3914 ;; Move cursor to right after the TODO keyword
3915 (when org-archive-stamp-time
3916 (beginning-of-line 1)
3917 (looking-at org-todo-line-regexp)
3918 (goto-char (or (match-end 2) (match-beginning 3)))
3919 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3920 (org-current-time))
3921 ")"))
3922 ;; Save the buffer, if it is not the same buffer.
3923 (if (not (eq this-buffer buffer)) (save-buffer))))
3924 ;; Here we are back in the original buffer. Everything seems to have
3925 ;; worked. So now cut the tree and finish up.
3926 (let (this-command) (org-cut-subtree))
3927 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
3928 (message "Subtree archived %s"
3929 (if (eq this-buffer buffer)
3930 (concat "under heading: " heading)
3931 (concat "in file: " (abbreviate-file-name file))))))
3933 ;;; Completion
3935 (defun org-complete (&optional arg)
3936 "Perform completion on word at point.
3937 At the beginning of a headline, this completes TODO keywords as given in
3938 `org-todo-keywords'.
3939 If the current word is preceded by a backslash, completes the TeX symbols
3940 that are supported for HTML support.
3941 If the current word is preceded by \"#+\", completes special words for
3942 setting file options.
3943 At all other locations, this simply calls `ispell-complete-word'."
3944 (interactive "P")
3945 (catch 'exit
3946 (let* ((end (point))
3947 (beg1 (save-excursion
3948 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3949 (skip-chars-backward "a-zA-Z_@0-9")
3950 (point)))
3951 (beg (save-excursion
3952 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3953 (skip-chars-backward "a-zA-Z0-9_:$")
3954 (point)))
3955 (camel (equal (char-before beg) ?*))
3956 (tag (equal (char-before beg1) ?:))
3957 (texp (equal (char-before beg) ?\\))
3958 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3959 beg)
3960 "#+"))
3961 (completion-ignore-case opt)
3962 (type nil)
3963 (tbl nil)
3964 (table (cond
3965 (opt
3966 (setq type :opt)
3967 (mapcar (lambda (x)
3968 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3969 (cons (match-string 2 x) (match-string 1 x)))
3970 (org-split-string (org-get-current-options) "\n")))
3971 (texp
3972 (setq type :tex)
3973 org-html-entities)
3974 ((string-match "\\`\\*+[ \t]*\\'"
3975 (buffer-substring (point-at-bol) beg))
3976 (setq type :todo)
3977 (mapcar 'list org-todo-keywords))
3978 (camel
3979 (setq type :camel)
3980 (save-excursion
3981 (goto-char (point-min))
3982 (while (re-search-forward org-todo-line-regexp nil t)
3983 (push (list
3984 (if org-file-link-context-use-camel-case
3985 (org-make-org-heading-camel (match-string 3) t)
3986 (org-make-org-heading-search-string
3987 (match-string 3) t)))
3988 tbl)))
3989 tbl)
3990 (tag (setq type :tag beg beg1)
3991 (org-get-buffer-tags))
3992 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3993 (pattern (buffer-substring-no-properties beg end))
3994 (completion (try-completion pattern table)))
3995 (cond ((eq completion t)
3996 (if (equal type :opt)
3997 (insert (substring (cdr (assoc (upcase pattern) table))
3998 (length pattern)))))
3999 ((null completion)
4000 (message "Can't find completion for \"%s\"" pattern)
4001 (ding))
4002 ((not (string= pattern completion))
4003 (delete-region beg end)
4004 (if (string-match " +$" completion)
4005 (setq completion (replace-match "" t t completion)))
4006 (insert completion)
4007 (if (get-buffer-window "*Completions*")
4008 (delete-window (get-buffer-window "*Completions*")))
4009 (if (assoc completion table)
4010 (if (eq type :todo) (insert " ")
4011 (if (eq type :tag) (insert ":"))))
4012 (if (and (equal type :opt) (assoc completion table))
4013 (message "%s" (substitute-command-keys
4014 "Press \\[org-complete] again to insert example settings"))))
4016 (message "Making completion list...")
4017 (let ((list (sort (all-completions pattern table) 'string<)))
4018 (with-output-to-temp-buffer "*Completions*"
4019 (condition-case nil
4020 ;; Protection needed for XEmacs and emacs 21
4021 (display-completion-list list pattern)
4022 (error (display-completion-list list)))))
4023 (message "Making completion list...%s" "done"))))))
4025 ;;; Comments, TODO and DEADLINE
4027 (defun org-toggle-comment ()
4028 "Change the COMMENT state of an entry."
4029 (interactive)
4030 (save-excursion
4031 (org-back-to-heading)
4032 (if (looking-at (concat outline-regexp
4033 "\\( +\\<" org-comment-string "\\>\\)"))
4034 (replace-match "" t t nil 1)
4035 (if (looking-at outline-regexp)
4036 (progn
4037 (goto-char (match-end 0))
4038 (insert " " org-comment-string))))))
4040 (defvar org-last-todo-state-is-todo nil
4041 "This is non-nil when the last TODO state change led to a TODO state.
4042 If the last change removed the TODO tag or switched to DONE, then
4043 this is nil.")
4045 (defun org-todo (&optional arg)
4046 "Change the TODO state of an item.
4047 The state of an item is given by a keyword at the start of the heading,
4048 like
4049 *** TODO Write paper
4050 *** DONE Call mom
4052 The different keywords are specified in the variable `org-todo-keywords'.
4053 By default the available states are \"TODO\" and \"DONE\".
4054 So for this example: when the item starts with TODO, it is changed to DONE.
4055 When it starts with DONE, the DONE is removed. And when neither TODO nor
4056 DONE are present, add TODO at the beginning of the heading.
4058 With prefix arg, use completion to determine the new state. With numeric
4059 prefix arg, switch to that state."
4060 (interactive "P")
4061 (save-excursion
4062 (org-back-to-heading)
4063 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4064 (or (looking-at (concat " +" org-todo-regexp " *"))
4065 (looking-at " *"))
4066 (let* ((this (match-string 1))
4067 (completion-ignore-case t)
4068 (member (member this org-todo-keywords))
4069 (tail (cdr member))
4070 (state (cond
4071 ((equal arg '(4))
4072 ;; Read a state with completion
4073 (completing-read "State: " (mapcar (lambda(x) (list x))
4074 org-todo-keywords)
4075 nil t))
4076 ((eq arg 'right)
4077 (if this
4078 (if tail (car tail) nil)
4079 (car org-todo-keywords)))
4080 ((eq arg 'left)
4081 (if (equal member org-todo-keywords)
4083 (if this
4084 (nth (- (length org-todo-keywords) (length tail) 2)
4085 org-todo-keywords)
4086 org-done-string)))
4087 (arg
4088 ;; user requests a specific state
4089 (nth (1- (prefix-numeric-value arg))
4090 org-todo-keywords))
4091 ((null member) (car org-todo-keywords))
4092 ((null tail) nil) ;; -> first entry
4093 ((eq org-todo-interpretation 'sequence)
4094 (car tail))
4095 ((memq org-todo-interpretation '(type priority))
4096 (if (eq this-command last-command)
4097 (car tail)
4098 (if (> (length tail) 0) org-done-string nil)))
4099 (t nil)))
4100 (next (if state (concat " " state " ") " ")))
4101 (replace-match next t t)
4102 (setq org-last-todo-state-is-todo
4103 (not (equal state org-done-string)))
4104 (when org-log-done
4105 (if (equal state org-done-string)
4106 (org-add-planning-info 'closed (current-time) 'scheduled)
4107 (if (not this)
4108 (org-add-planning-info nil nil 'closed))))
4109 ;; Fixup tag positioning
4110 (and org-auto-align-tags (org-set-tags nil t))
4111 (run-hooks 'org-after-todo-state-change-hook)))
4112 ;; Fixup cursor location if close to the keyword
4113 (if (and (outline-on-heading-p)
4114 (not (bolp))
4115 (save-excursion (beginning-of-line 1)
4116 (looking-at org-todo-line-regexp))
4117 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4118 (progn
4119 (goto-char (or (match-end 2) (match-end 1)))
4120 (just-one-space))))
4122 (defun org-log-done (&optional undone)
4123 "Add a time stamp logging that a TODO entry has been closed.
4124 When UNDONE is non-nil, remove such a time stamp again."
4125 (interactive)
4126 (let (beg end col)
4127 (save-excursion
4128 (org-back-to-heading t)
4129 (setq beg (point))
4130 (looking-at (concat outline-regexp " *"))
4131 (goto-char (match-end 0))
4132 (setq col (current-column))
4133 (outline-next-heading)
4134 (setq end (point))
4135 (goto-char beg)
4136 (when (re-search-forward (concat
4137 "[\r\n]\\([ \t]*"
4138 (regexp-quote org-closed-string)
4139 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4140 (delete-region (match-beginning 1) (match-end 1)))
4141 (unless undone
4142 (org-back-to-heading t)
4143 (skip-chars-forward "^\n\r")
4144 (goto-char (min (1+ (point)) (point-max)))
4145 (when (not (member (char-before) '(?\r ?\n)))
4146 (insert "\n"))
4147 (indent-to col)
4148 (insert org-closed-string " "
4149 (format-time-string
4150 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4151 (org-current-time))
4152 "\n")))))
4154 (defun org-show-todo-tree (arg)
4155 "Make a compact tree which shows all headlines marked with TODO.
4156 The tree will show the lines where the regexp matches, and all higher
4157 headlines above the match.
4158 With \\[universal-argument] prefix, also show the DONE entries.
4159 With a numeric prefix N, construct a sparse tree for the Nth element
4160 of `org-todo-keywords'."
4161 (interactive "P")
4162 (let ((case-fold-search nil)
4163 (kwd-re
4164 (cond ((null arg) org-not-done-regexp)
4165 ((equal arg '(4)) org-todo-regexp)
4166 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4167 (regexp-quote (nth (1- (prefix-numeric-value arg))
4168 org-todo-keywords)))
4169 (t (error "Invalid prefix argument: %s" arg)))))
4170 (message "%d TODO entries found"
4171 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4173 (defun org-deadline ()
4174 "Insert the DEADLINE: string to make a deadline.
4175 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4176 to modify it to the correct date."
4177 (interactive)
4178 (org-add-planning-info 'deadline nil nil)) ;; FIXME: remove closed?
4180 (defun org-schedule ()
4181 "Insert the SCHEDULED: string to schedule a TODO item.
4182 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4183 to modify it to the correct date."
4184 (interactive)
4185 (org-add-planning-info 'scheduled nil 'closed))
4187 (defun org-add-planning-info (what &optional time &rest remove)
4188 "Insert new timestamp with keyword in the line directly after the headline.
4189 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
4190 If non is given, the user is prompted for a date.
4191 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
4192 be removed."
4193 (interactive)
4194 (save-excursion
4195 (let (beg end col list elt (buffer-invisibility-spec nil) ts)
4196 (org-back-to-heading t)
4197 (setq beg (point))
4198 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
4199 (goto-char (match-end 1))
4200 (setq col (current-column))
4201 (goto-char (1+ (match-end 0)))
4202 (if (and (not (looking-at outline-regexp))
4203 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
4204 "[^\r\n]*")))
4205 (narrow-to-region (match-beginning 0) (match-end 0))
4206 (insert "\n")
4207 (backward-char 1)
4208 (narrow-to-region (point) (point))
4209 (indent-to-column col))
4210 ;; Check if we have to remove something.
4211 (setq list (cons what remove))
4212 (while list
4213 (setq elt (pop list))
4214 (goto-char (point-min))
4215 (when (or (and (eq elt 'scheduled)
4216 (re-search-forward org-scheduled-time-regexp nil t))
4217 (and (eq elt 'deadline)
4218 (re-search-forward org-deadline-time-regexp nil t))
4219 (and (eq elt 'closed)
4220 (re-search-forward org-closed-time-regexp nil t)))
4221 (replace-match "")
4222 (if (looking-at " +") (replace-match ""))))
4223 (goto-char (point-max))
4224 (when what
4225 (insert
4226 (if (not (equal (char-before) ?\ )) " " "")
4227 (cond ((eq what 'scheduled) org-scheduled-string)
4228 ((eq what 'deadline) org-deadline-string)
4229 ((eq what 'closed) org-closed-string))
4230 " ")
4231 (insert
4232 (setq ts
4233 (format-time-string
4234 (if (eq what 'closed)
4235 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4236 (car org-time-stamp-formats))
4237 (or time (org-read-date nil 'to-time))))))
4238 (goto-char (point-min))
4239 (widen)
4240 (if (looking-at "[ \t]+\r?\n")
4241 (replace-match ""))
4242 ts)))
4244 (defun org-occur (regexp &optional callback)
4245 "Make a compact tree which shows all matches of REGEXP.
4246 The tree will show the lines where the regexp matches, and all higher
4247 headlines above the match. It will also show the heading after the match,
4248 to make sure editing the matching entry is easy.
4249 If CALLBACK is non-nil, it is a function which is called to confirm
4250 that the match should indeed be shown."
4251 (interactive "sRegexp: ")
4252 (org-remove-occur-highlights nil nil t)
4253 (setq regexp (org-check-occur-regexp regexp))
4254 (let ((cnt 0))
4255 (save-excursion
4256 (goto-char (point-min))
4257 (hide-sublevels 1)
4258 (while (re-search-forward regexp nil t)
4259 (when (or (not callback)
4260 (save-match-data (funcall callback)))
4261 (setq cnt (1+ cnt))
4262 (org-highlight-new-match (match-beginning 0) (match-end 0))
4263 (org-show-hierarchy-above))))
4264 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4265 nil 'local)
4266 (run-hooks 'org-occur-hook)
4267 (if (interactive-p)
4268 (message "%d match(es) for regexp %s" cnt regexp))
4269 cnt))
4271 (defun org-show-hierarchy-above ()
4272 "Make sure point and the headings hierarchy above is visible."
4273 (catch 'exit
4274 (if (org-on-heading-p t)
4275 (org-flag-heading nil) ; only show the heading
4276 (and (or (org-invisible-p) (org-invisible-p2))
4277 (org-show-hidden-entry))) ; show entire entry
4278 (save-excursion
4279 (and org-show-following-heading
4280 (outline-next-heading)
4281 (org-flag-heading nil))) ; show the next heading
4282 (when org-show-hierarchy-above
4283 (save-excursion ; show all higher headings
4284 (while (and (condition-case nil
4285 (progn (org-up-heading-all 1) t)
4286 (error nil))
4287 (not (bobp)))
4288 (org-flag-heading nil))))))
4290 ;; Overlay compatibility functions
4291 (defun org-make-overlay (beg end &optional buffer)
4292 (if (featurep 'xemacs)
4293 (make-extent beg end buffer)
4294 (make-overlay beg end buffer)))
4295 (defun org-delete-overlay (ovl)
4296 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4297 (defun org-detatch-overlay (ovl)
4298 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4299 (defun org-move-overlay (ovl beg end &optional buffer)
4300 (if (featurep 'xemacs)
4301 (set-extent-endpoints ovl beg end buffer)
4302 (move-overlay ovl beg end buffer)))
4303 (defun org-overlay-put (ovl prop value)
4304 (if (featurep 'xemacs)
4305 (set-extent-property ovl prop value)
4306 (overlay-put ovl prop value)))
4308 (defvar org-occur-highlights nil)
4309 (defun org-highlight-new-match (beg end)
4310 "Highlight from BEG to END and mark the highlight is an occur headline."
4311 (let ((ov (org-make-overlay beg end)))
4312 (org-overlay-put ov 'face 'secondary-selection)
4313 (push ov org-occur-highlights)))
4315 (defun org-remove-occur-highlights (&optional beg end noremove)
4316 "Remove the occur highlights from the buffer.
4317 BEG and END are ignored. If NOREMOVE is nil, remove this function
4318 from the `before-change-functions' in the current buffer."
4319 (interactive)
4320 (mapc 'org-delete-overlay org-occur-highlights)
4321 (setq org-occur-highlights nil)
4322 (unless noremove
4323 (remove-hook 'before-change-functions
4324 'org-remove-occur-highlights 'local)))
4326 ;;; Priorities
4328 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4329 "Regular expression matching the priority indicator.")
4331 (defvar org-remove-priority-next-time nil)
4333 (defun org-priority-up ()
4334 "Increase the priority of the current item."
4335 (interactive)
4336 (org-priority 'up))
4338 (defun org-priority-down ()
4339 "Decrease the priority of the current item."
4340 (interactive)
4341 (org-priority 'down))
4343 (defun org-priority (&optional action)
4344 "Change the priority of an item by ARG.
4345 ACTION can be set, up, or down."
4346 (interactive)
4347 (setq action (or action 'set))
4348 (let (current new news have remove)
4349 (save-excursion
4350 (org-back-to-heading)
4351 (if (looking-at org-priority-regexp)
4352 (setq current (string-to-char (match-string 2))
4353 have t)
4354 (setq current org-default-priority))
4355 (cond
4356 ((eq action 'set)
4357 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4358 (setq new (read-char-exclusive))
4359 (cond ((equal new ?\ ) (setq remove t))
4360 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4361 (error "Priority must be between `%c' and `%c'"
4362 ?A org-lowest-priority))))
4363 ((eq action 'up)
4364 (setq new (1- current)))
4365 ((eq action 'down)
4366 (setq new (1+ current)))
4367 (t (error "Invalid action")))
4368 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4369 (setq news (format "%c" new))
4370 (if have
4371 (if remove
4372 (replace-match "" t t nil 1)
4373 (replace-match news t t nil 2))
4374 (if remove
4375 (error "No priority cookie found in line")
4376 (looking-at org-todo-line-regexp)
4377 (if (match-end 2)
4378 (progn
4379 (goto-char (match-end 2))
4380 (insert " [#" news "]"))
4381 (goto-char (match-beginning 3))
4382 (insert "[#" news "] ")))))
4383 (if remove
4384 (message "Priority removed")
4385 (message "Priority of current item set to %s" news))))
4388 (defun org-get-priority (s)
4389 "Find priority cookie and return priority."
4390 (save-match-data
4391 (if (not (string-match org-priority-regexp s))
4392 (* 1000 (- org-lowest-priority org-default-priority))
4393 (* 1000 (- org-lowest-priority
4394 (string-to-char (match-string 2 s)))))))
4396 ;;; Timestamps
4398 (defvar org-last-changed-timestamp nil)
4400 (defun org-time-stamp (arg)
4401 "Prompt for a date/time and insert a time stamp.
4402 If the user specifies a time like HH:MM, or if this command is called
4403 with a prefix argument, the time stamp will contain date and time.
4404 Otherwise, only the date will be included. All parts of a date not
4405 specified by the user will be filled in from the current date/time.
4406 So if you press just return without typing anything, the time stamp
4407 will represent the current date/time. If there is already a timestamp
4408 at the cursor, it will be modified."
4409 (interactive "P")
4410 (let ((fmt (if arg (cdr org-time-stamp-formats)
4411 (car org-time-stamp-formats)))
4412 (org-time-was-given nil)
4413 time)
4414 (cond
4415 ((and (org-at-timestamp-p)
4416 (eq last-command 'org-time-stamp)
4417 (eq this-command 'org-time-stamp))
4418 (insert "--")
4419 (setq time (let ((this-command this-command))
4420 (org-read-date arg 'totime)))
4421 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4422 (insert (format-time-string fmt time)))
4423 ((org-at-timestamp-p)
4424 (setq time (let ((this-command this-command))
4425 (org-read-date arg 'totime)))
4426 (and (org-at-timestamp-p) (replace-match
4427 (setq org-last-changed-timestamp
4428 (format-time-string fmt time))
4429 t t))
4430 (message "Timestamp updated"))
4432 (setq time (let ((this-command this-command))
4433 (org-read-date arg 'totime)))
4434 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4435 (insert (format-time-string fmt time))))))
4437 (defun org-time-stamp-inactive (&optional arg)
4438 "Insert an inactive time stamp.
4439 An inactive time stamp is enclosed in square brackets instead of angle
4440 brackets. It is inactive in the sense that it does not trigger agenda entries,
4441 does not link to the calendar and cannot be changed with the S-cursor keys.
4442 So these are more for recording a certain time/date."
4443 (interactive "P")
4444 (let ((fmt (if arg (cdr org-time-stamp-formats)
4445 (car org-time-stamp-formats)))
4446 (org-time-was-given nil)
4447 time)
4448 (setq time (org-read-date arg 'totime))
4449 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4450 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4451 (insert (format-time-string fmt time))))
4453 (defvar org-date-ovl (org-make-overlay 1 1))
4454 (org-overlay-put org-date-ovl 'face 'org-warning)
4455 (org-detatch-overlay org-date-ovl)
4457 (defun org-read-date (&optional with-time to-time)
4458 "Read a date and make things smooth for the user.
4459 The prompt will suggest to enter an ISO date, but you can also enter anything
4460 which will at least partially be understood by `parse-time-string'.
4461 Unrecognized parts of the date will default to the current day, month, year,
4462 hour and minute. For example,
4463 3-2-5 --> 2003-02-05
4464 feb 15 --> currentyear-02-15
4465 sep 12 9 --> 2009-09-12
4466 12:45 --> today 12:45
4467 22 sept 0:34 --> currentyear-09-22 0:34
4468 12 --> currentyear-currentmonth-12
4469 Fri --> nearest Friday (today or later)
4470 etc.
4471 The function understands only English month and weekday abbreviations,
4472 but this can be configured with the variables `parse-time-months' and
4473 `parse-time-weekdays'.
4475 While prompting, a calendar is popped up - you can also select the
4476 date with the mouse (button 1). The calendar shows a period of three
4477 months. To scroll it to other months, use the keys `>' and `<'.
4478 If you don't like the calendar, turn it off with
4479 \(setq org-popup-calendar-for-date-prompt nil)
4481 With optional argument TO-TIME, the date will immediately be converted
4482 to an internal time.
4483 With an optional argument WITH-TIME, the prompt will suggest to also
4484 insert a time. Note that when WITH-TIME is not set, you can still
4485 enter a time, and this function will inform the calling routine about
4486 this change. The calling routine may then choose to change the format
4487 used to insert the time stamp into the buffer to include the time."
4488 (require 'parse-time)
4489 (let* ((org-time-stamp-rounding-minutes
4490 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4491 (ct (org-current-time))
4492 (default-time
4493 ;; Default time is either today, or, when entering a range,
4494 ;; the range start.
4495 (if (save-excursion
4496 (re-search-backward
4497 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4498 (- (point) 20) t))
4499 (apply
4500 'encode-time
4501 (mapcar (lambda(x) (or x 0))
4502 (parse-time-string (match-string 1))))
4503 ct))
4504 (calendar-move-hook nil)
4505 (view-diary-entries-initially nil)
4506 (view-calendar-holidays-initially nil)
4507 (timestr (format-time-string
4508 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4509 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4510 ans ans1 ans2
4511 second minute hour day month year tl wday wday1)
4513 (if org-popup-calendar-for-date-prompt
4514 (save-excursion
4515 (save-window-excursion
4516 (calendar)
4517 (calendar-forward-day (- (time-to-days default-time)
4518 (calendar-absolute-from-gregorian
4519 (calendar-current-date))))
4520 (org-eval-in-calendar nil)
4521 (let* ((old-map (current-local-map))
4522 (map (copy-keymap calendar-mode-map))
4523 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4524 (define-key map (kbd "RET") 'org-calendar-select)
4525 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4526 'org-calendar-select-mouse)
4527 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4528 'org-calendar-select-mouse)
4529 (define-key minibuffer-local-map [(meta shift left)]
4530 (lambda () (interactive)
4531 (org-eval-in-calendar '(calendar-backward-month 1))))
4532 (define-key minibuffer-local-map [(meta shift right)]
4533 (lambda () (interactive)
4534 (org-eval-in-calendar '(calendar-forward-month 1))))
4535 (define-key minibuffer-local-map [(shift up)]
4536 (lambda () (interactive)
4537 (org-eval-in-calendar '(calendar-backward-week 1))))
4538 (define-key minibuffer-local-map [(shift down)]
4539 (lambda () (interactive)
4540 (org-eval-in-calendar '(calendar-forward-week 1))))
4541 (define-key minibuffer-local-map [(shift left)]
4542 (lambda () (interactive)
4543 (org-eval-in-calendar '(calendar-backward-day 1))))
4544 (define-key minibuffer-local-map [(shift right)]
4545 (lambda () (interactive)
4546 (org-eval-in-calendar '(calendar-forward-day 1))))
4547 (define-key minibuffer-local-map ">"
4548 (lambda () (interactive)
4549 (org-eval-in-calendar '(scroll-calendar-left 1))))
4550 (define-key minibuffer-local-map "<"
4551 (lambda () (interactive)
4552 (org-eval-in-calendar '(scroll-calendar-right 1))))
4553 (unwind-protect
4554 (progn
4555 (use-local-map map)
4556 (setq ans (read-string prompt "" nil nil))
4557 (if (not (string-match "\\S-" ans)) (setq ans nil))
4558 (setq ans (or ans1 ans ans2)))
4559 (use-local-map old-map)))))
4560 ;; Naked prompt only
4561 (setq ans (read-string prompt "" nil timestr)))
4562 (org-detatch-overlay org-date-ovl)
4564 (if (string-match
4565 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4566 (progn
4567 (setq year (if (match-end 2)
4568 (string-to-number (match-string 2 ans))
4569 (string-to-number (format-time-string "%Y")))
4570 month (string-to-number (match-string 3 ans))
4571 day (string-to-number (match-string 4 ans)))
4572 (if (< year 100) (setq year (+ 2000 year)))
4573 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4574 t nil ans))))
4575 (setq tl (parse-time-string ans)
4576 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4577 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4578 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4579 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4580 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4581 second (or (nth 0 tl) 0)
4582 wday (nth 6 tl))
4583 (when (and wday (not (nth 3 tl)))
4584 ;; Weekday was given, but no day, so pick that day in the week
4585 ;; on or after the derived date.
4586 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4587 (unless (equal wday wday1)
4588 (setq day (+ day (% (- wday wday1 -7) 7)))))
4589 (if (and (boundp 'org-time-was-given)
4590 (nth 2 tl))
4591 (setq org-time-was-given t))
4592 (if (< year 100) (setq year (+ 2000 year)))
4593 (if to-time
4594 (encode-time second minute hour day month year)
4595 (if (or (nth 1 tl) (nth 2 tl))
4596 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4597 (format "%04d-%02d-%02d" year month day)))))
4599 (defun org-eval-in-calendar (form)
4600 "Eval FORM in the calendar window and return to current window.
4601 Also, store the cursor date in variable ans2."
4602 (let ((sw (selected-window)))
4603 (select-window (get-buffer-window "*Calendar*"))
4604 (eval form)
4605 (when (calendar-cursor-to-date)
4606 (let* ((date (calendar-cursor-to-date))
4607 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4608 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4609 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4610 (select-window sw)))
4612 (defun org-calendar-select ()
4613 "Return to `org-read-date' with the date currently selected.
4614 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4615 (interactive)
4616 (when (calendar-cursor-to-date)
4617 (let* ((date (calendar-cursor-to-date))
4618 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4619 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4620 (if (active-minibuffer-window) (exit-minibuffer))))
4622 (defun org-calendar-select-mouse (ev)
4623 "Return to `org-read-date' with the date currently selected.
4624 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4625 (interactive "e")
4626 (mouse-set-point ev)
4627 (when (calendar-cursor-to-date)
4628 (let* ((date (calendar-cursor-to-date))
4629 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4630 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4631 (if (active-minibuffer-window) (exit-minibuffer))))
4633 (defun org-check-deadlines (ndays)
4634 "Check if there are any deadlines due or past due.
4635 A deadline is considered due if it happens within `org-deadline-warning-days'
4636 days from today's date. If the deadline appears in an entry marked DONE,
4637 it is not shown. The prefix arg NDAYS can be used to test that many
4638 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4639 (interactive "P")
4640 (let* ((org-warn-days
4641 (cond
4642 ((equal ndays '(4)) 100000)
4643 (ndays (prefix-numeric-value ndays))
4644 (t org-deadline-warning-days)))
4645 (case-fold-search nil)
4646 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4647 (callback
4648 (lambda ()
4649 (and (let ((d1 (time-to-days (current-time)))
4650 (d2 (time-to-days
4651 (org-time-string-to-time (match-string 1)))))
4652 (< (- d2 d1) org-warn-days))
4653 (not (org-entry-is-done-p))))))
4654 (message "%d deadlines past-due or due within %d days"
4655 (org-occur regexp callback)
4656 org-warn-days)))
4658 (defun org-evaluate-time-range (&optional to-buffer)
4659 "Evaluate a time range by computing the difference between start and end.
4660 Normally the result is just printed in the echo area, but with prefix arg
4661 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4662 If the time range is actually in a table, the result is inserted into the
4663 next column.
4664 For time difference computation, a year is assumed to be exactly 365
4665 days in order to avoid rounding problems."
4666 (interactive "P")
4667 (save-excursion
4668 (unless (org-at-date-range-p)
4669 (goto-char (point-at-bol))
4670 (re-search-forward org-tr-regexp (point-at-eol) t))
4671 (if (not (org-at-date-range-p))
4672 (error "Not at a time-stamp range, and none found in current line")))
4673 (let* ((ts1 (match-string 1))
4674 (ts2 (match-string 2))
4675 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4676 (match-end (match-end 0))
4677 (time1 (org-time-string-to-time ts1))
4678 (time2 (org-time-string-to-time ts2))
4679 (t1 (time-to-seconds time1))
4680 (t2 (time-to-seconds time2))
4681 (diff (abs (- t2 t1)))
4682 (negative (< (- t2 t1) 0))
4683 ;; (ys (floor (* 365 24 60 60)))
4684 (ds (* 24 60 60))
4685 (hs (* 60 60))
4686 (fy "%dy %dd %02d:%02d")
4687 (fy1 "%dy %dd")
4688 (fd "%dd %02d:%02d")
4689 (fd1 "%dd")
4690 (fh "%02d:%02d")
4691 y d h m align)
4692 (if havetime
4693 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4695 d (floor (/ diff ds)) diff (mod diff ds)
4696 h (floor (/ diff hs)) diff (mod diff hs)
4697 m (floor (/ diff 60)))
4698 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4700 d (floor (+ (/ diff ds) 0.5))
4701 h 0 m 0))
4702 (if (not to-buffer)
4703 (message (org-make-tdiff-string y d h m))
4704 (when (org-at-table-p)
4705 (goto-char match-end)
4706 (setq align t)
4707 (and (looking-at " *|") (goto-char (match-end 0))))
4708 (if (looking-at
4709 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4710 (replace-match ""))
4711 (if negative (insert " -"))
4712 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4713 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4714 (insert " " (format fh h m))))
4715 (if align (org-table-align))
4716 (message "Time difference inserted"))))
4718 (defun org-make-tdiff-string (y d h m)
4719 (let ((fmt "")
4720 (l nil))
4721 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4722 l (push y l)))
4723 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4724 l (push d l)))
4725 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4726 l (push h l)))
4727 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4728 l (push m l)))
4729 (apply 'format fmt (nreverse l))))
4731 (defun org-time-string-to-time (s)
4732 (apply 'encode-time (org-parse-time-string s)))
4734 (defun org-parse-time-string (s &optional nodefault)
4735 "Parse the standard Org-mode time string.
4736 This should be a lot faster than the normal `parse-time-string'.
4737 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4738 hour and minute fields will be nil if not given."
4739 (if (string-match org-ts-regexp1 s)
4740 (list 0
4741 (if (or (match-beginning 8) (not nodefault))
4742 (string-to-number (or (match-string 8 s) "0")))
4743 (if (or (match-beginning 7) (not nodefault))
4744 (string-to-number (or (match-string 7 s) "0")))
4745 (string-to-number (match-string 4 s))
4746 (string-to-number (match-string 3 s))
4747 (string-to-number (match-string 2 s))
4748 nil nil nil)
4749 (make-list 9 0)))
4751 (defun org-timestamp-up (&optional arg)
4752 "Increase the date item at the cursor by one.
4753 If the cursor is on the year, change the year. If it is on the month or
4754 the day, change that.
4755 With prefix ARG, change by that many units."
4756 (interactive "p")
4757 (org-timestamp-change (prefix-numeric-value arg)))
4759 (defun org-timestamp-down (&optional arg)
4760 "Decrease the date item at the cursor by one.
4761 If the cursor is on the year, change the year. If it is on the month or
4762 the day, change that.
4763 With prefix ARG, change by that many units."
4764 (interactive "p")
4765 (org-timestamp-change (- (prefix-numeric-value arg))))
4767 (defun org-timestamp-up-day (&optional arg)
4768 "Increase the date in the time stamp by one day.
4769 With prefix ARG, change that many days."
4770 (interactive "p")
4771 (if (and (not (org-at-timestamp-p))
4772 (org-on-heading-p))
4773 (org-todo 'up)
4774 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4776 (defun org-timestamp-down-day (&optional arg)
4777 "Decrease the date in the time stamp by one day.
4778 With prefix ARG, change that many days."
4779 (interactive "p")
4780 (if (and (not (org-at-timestamp-p))
4781 (org-on-heading-p))
4782 (org-todo 'down)
4783 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4785 (defsubst org-pos-in-match-range (pos n)
4786 (and (match-beginning n)
4787 (<= (match-beginning n) pos)
4788 (>= (match-end n) pos)))
4790 (defun org-at-timestamp-p ()
4791 "Determine if the cursor is in or at a timestamp."
4792 (interactive)
4793 (let* ((tsr org-ts-regexp2)
4794 (pos (point))
4795 (ans (or (looking-at tsr)
4796 (save-excursion
4797 (skip-chars-backward "^<\n\r\t")
4798 (if (> (point) 1) (backward-char 1))
4799 (and (looking-at tsr)
4800 (> (- (match-end 0) pos) -1))))))
4801 (and (boundp 'org-ts-what)
4802 (setq org-ts-what
4803 (cond
4804 ((org-pos-in-match-range pos 2) 'year)
4805 ((org-pos-in-match-range pos 3) 'month)
4806 ((org-pos-in-match-range pos 7) 'hour)
4807 ((org-pos-in-match-range pos 8) 'minute)
4808 ((or (org-pos-in-match-range pos 4)
4809 (org-pos-in-match-range pos 5)) 'day)
4810 (t 'day))))
4811 ans))
4813 (defun org-timestamp-change (n &optional what)
4814 "Change the date in the time stamp at point.
4815 The date will be changed by N times WHAT. WHAT can be `day', `month',
4816 `year', `minute', `second'. If WHAT is not given, the cursor position
4817 in the timestamp determines what will be changed."
4818 (let ((fmt (car org-time-stamp-formats))
4819 org-ts-what
4820 (pos (point))
4821 ts time time0)
4822 (if (not (org-at-timestamp-p))
4823 (error "Not at a timestamp"))
4824 (setq org-ts-what (or what org-ts-what))
4825 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4826 (- (match-end 0) (match-beginning 0))))
4828 (cdr org-time-stamp-formats)
4829 (car org-time-stamp-formats)))
4830 (setq ts (match-string 0))
4831 (replace-match "")
4832 (setq time0 (org-parse-time-string ts))
4833 (setq time
4834 (apply 'encode-time
4835 (append
4836 (list (or (car time0) 0))
4837 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4838 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4839 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4840 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4841 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4842 (nthcdr 6 time0))))
4843 (if (eq what 'calendar)
4844 (let ((cal-date
4845 (save-excursion
4846 (save-match-data
4847 (set-buffer "*Calendar*")
4848 (calendar-cursor-to-date)))))
4849 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4850 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4851 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4852 (setcar time0 (or (car time0) 0))
4853 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4854 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4855 (setq time (apply 'encode-time time0))))
4856 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4857 (goto-char pos)
4858 ;; Try to recenter the calendar window, if any
4859 (if (and org-calendar-follow-timestamp-change
4860 (get-buffer-window "*Calendar*" t)
4861 (memq org-ts-what '(day month year)))
4862 (org-recenter-calendar (time-to-days time)))))
4864 (defun org-recenter-calendar (date)
4865 "If the calendar is visible, recenter it to DATE."
4866 (let* ((win (selected-window))
4867 (cwin (get-buffer-window "*Calendar*" t))
4868 (calendar-move-hook nil))
4869 (when cwin
4870 (select-window cwin)
4871 (calendar-goto-date (if (listp date) date
4872 (calendar-gregorian-from-absolute date)))
4873 (select-window win))))
4875 (defun org-goto-calendar (&optional arg)
4876 "Go to the Emacs calendar at the current date.
4877 If there is a time stamp in the current line, go to that date.
4878 A prefix ARG can be used to force the current date."
4879 (interactive "P")
4880 (let ((tsr org-ts-regexp) diff
4881 (calendar-move-hook nil)
4882 (view-calendar-holidays-initially nil)
4883 (view-diary-entries-initially nil))
4884 (if (or (org-at-timestamp-p)
4885 (save-excursion
4886 (beginning-of-line 1)
4887 (looking-at (concat ".*" tsr))))
4888 (let ((d1 (time-to-days (current-time)))
4889 (d2 (time-to-days
4890 (org-time-string-to-time (match-string 1)))))
4891 (setq diff (- d2 d1))))
4892 (calendar)
4893 (calendar-goto-today)
4894 (if (and diff (not arg)) (calendar-forward-day diff))))
4896 (defun org-date-from-calendar ()
4897 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4898 If there is already a time stamp at the cursor position, update it."
4899 (interactive)
4900 (org-timestamp-change 0 'calendar))
4902 ;;; Agenda, and Diary Integration
4904 ;;; Define the mode
4906 (defvar org-agenda-mode-map (make-sparse-keymap)
4907 "Keymap for `org-agenda-mode'.")
4909 (defvar org-agenda-menu) ; defined later in this file.
4910 (defvar org-agenda-follow-mode nil)
4911 (defvar org-agenda-show-log nil)
4912 (defvar org-agenda-buffer-name "*Org Agenda*")
4913 (defvar org-agenda-redo-command nil)
4914 (defvar org-agenda-mode-hook nil)
4915 (defvar org-agenda-type nil)
4916 (defvar org-agenda-force-single-file nil)
4918 ;;;###autoload
4919 (defun org-agenda-mode ()
4920 "Mode for time-sorted view on action items in Org-mode files.
4922 The following commands are available:
4924 \\{org-agenda-mode-map}"
4925 (interactive)
4926 (kill-all-local-variables)
4927 (setq major-mode 'org-agenda-mode)
4928 (setq mode-name "Org-Agenda")
4929 (use-local-map org-agenda-mode-map)
4930 (easy-menu-add org-agenda-menu)
4931 (if org-startup-truncated (setq truncate-lines t))
4932 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4933 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4934 (unless org-agenda-keep-modes
4935 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
4936 org-agenda-show-log nil))
4937 (easy-menu-change
4938 '("Agenda") "Agenda Files"
4939 (append
4940 (list
4941 (vector
4942 (if (get 'org-agenda-files 'org-restrict)
4943 "Restricted to single file"
4944 "Edit File List")
4945 '(org-edit-agenda-file-list)
4946 (not (get 'org-agenda-files 'org-restrict)))
4947 "--")
4948 (mapcar 'org-file-menu-entry (org-agenda-files))))
4949 (org-agenda-set-mode-name)
4950 (apply
4951 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4952 (list 'org-agenda-mode-hook)))
4954 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4955 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4956 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4957 (define-key org-agenda-mode-map " " 'org-agenda-show)
4958 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4959 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4960 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4961 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4962 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4963 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4964 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4965 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4966 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4967 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4968 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4969 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4971 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4972 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
4973 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
4974 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4975 (while l (define-key org-agenda-mode-map
4976 (int-to-string (pop l)) 'digit-argument)))
4978 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4979 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4980 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4981 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4982 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4983 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4984 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4985 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4986 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4987 (define-key org-agenda-mode-map "n" 'next-line)
4988 (define-key org-agenda-mode-map "p" 'previous-line)
4989 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4990 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4991 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4992 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4993 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4994 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4995 (eval-after-load "calendar"
4996 '(define-key calendar-mode-map org-calendar-to-agenda-key
4997 'org-calendar-goto-agenda))
4998 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4999 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
5000 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
5001 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
5002 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
5003 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
5004 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
5005 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
5006 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
5007 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
5008 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
5009 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
5010 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
5011 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
5012 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
5013 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
5014 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
5015 "Local keymap for agenda entries from Org-mode.")
5017 (define-key org-agenda-keymap
5018 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
5019 (define-key org-agenda-keymap
5020 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
5021 (when org-agenda-mouse-1-follows-link
5022 (define-key org-agenda-keymap [follow-link] 'mouse-face))
5023 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
5024 '("Agenda"
5025 ("Agenda Files")
5026 "--"
5027 ["Show" org-agenda-show t]
5028 ["Go To (other window)" org-agenda-goto t]
5029 ["Go To (one window)" org-agenda-switch-to t]
5030 ["Follow Mode" org-agenda-follow-mode
5031 :style toggle :selected org-agenda-follow-mode :active t]
5032 "--"
5033 ["Cycle TODO" org-agenda-todo t]
5034 ("Tags"
5035 ["Show all Tags" org-agenda-show-tags t]
5036 ["Set Tags" org-agenda-set-tags t])
5037 ("Schedule"
5038 ["Schedule" org-agenda-schedule t]
5039 ["Set Deadline" org-agenda-deadline t]
5040 "--"
5041 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
5042 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
5043 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
5044 ("Priority"
5045 ["Set Priority" org-agenda-priority t]
5046 ["Increase Priority" org-agenda-priority-up t]
5047 ["Decrease Priority" org-agenda-priority-down t]
5048 ["Show Priority" org-agenda-show-priority t])
5049 "--"
5050 ;; ["New agenda command" org-agenda t]
5051 ["Rebuild buffer" org-agenda-redo t]
5052 "--"
5053 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
5054 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
5055 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
5056 "--"
5057 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
5058 :style radio :selected (equal org-agenda-ndays 1)]
5059 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
5060 :style radio :selected (equal org-agenda-ndays 7)]
5061 "--"
5062 ["Show Logbook entries" org-agenda-log-mode
5063 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
5064 ["Include Diary" org-agenda-toggle-diary
5065 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
5066 ["Use Time Grid" org-agenda-toggle-time-grid
5067 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
5068 "--"
5069 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
5070 ("Calendar Commands"
5071 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
5072 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
5073 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
5074 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
5075 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
5076 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
5077 "--"
5078 ["Quit" org-agenda-quit t]
5079 ["Exit and Release Buffers" org-agenda-exit t]
5082 ;;;###autoload
5083 (defun org-agenda (arg)
5084 "Dispatch agenda commands to collect entries to the agenda buffer.
5085 Prompts for a character to select a command. Any prefix arg will be passed
5086 on to the selected command. The default selections are:
5088 a Call `org-agenda' to display the agenda for the current day or week.
5089 t Call `org-todo-list' to display the global todo list.
5090 T Call `org-todo-list' to display the global todo list, select only
5091 entries with a specific TODO keyword (the user gets a prompt).
5092 m Call `org-tags-view' to display headlines with tags matching
5093 a condition (the user is prompted for the condition).
5094 M Like `m', but select only TODO entries, no ordinary headlines.
5096 More commands can be added by configuring the variable
5097 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
5098 searches can be pre-defined in this way.
5100 If the current buffer is in Org-mode and visiting a file, you can also
5101 first press `1' to indicate that the agenda should be temporarily (until the
5102 next use of \\[org-agenda]) restricted to the current file."
5103 (interactive "P")
5104 (catch 'exit
5105 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
5106 (custom org-agenda-custom-commands)
5107 c entry key type string)
5108 (put 'org-agenda-files 'org-restrict nil)
5109 (save-window-excursion
5110 (delete-other-windows)
5111 (switch-to-buffer-other-window " *Agenda Commands*")
5112 (erase-buffer)
5113 (insert
5114 "Press key for an agenda command:
5115 --------------------------------
5116 a Agenda for current week or day
5117 t List of all TODO entries T Entries with special TODO kwd
5118 m Match a TAGS query M Like m, but only TODO entries
5119 C Configure your own agenda commands")
5120 (while (setq entry (pop custom))
5121 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
5122 (insert (format "\n%-4s%-14s: %s"
5124 (cond
5125 ((eq type 'tags) "Tags query")
5126 ((eq type 'todo) "TODO keyword")
5127 ((eq type 'tags-tree) "Tags tree")
5128 ((eq type 'todo-tree) "TODO kwd tree")
5129 ((eq type 'occur-tree) "Occur tree")
5130 (t "???"))
5131 (org-add-props string nil 'face 'org-warning))))
5132 (goto-char (point-min))
5133 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
5134 (message "Press key for agenda command%s"
5135 (if restrict-ok ", or [1] to restrict to current file" ""))
5136 (setq c (read-char-exclusive))
5137 (message "")
5138 (when (equal c ?1)
5139 (if restrict-ok
5140 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
5141 (error "Cannot restrict agenda to current buffer"))
5142 (message "Press key for agenda command%s"
5143 (if restrict-ok " (restricted to current file)" ""))
5144 (setq c (read-char-exclusive))
5145 (message "")))
5146 (require 'calendar) ; FIXME: can we avoid this for some commands?
5147 ;; For example the todo list should not need it (but does...)
5148 (cond
5149 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
5150 ((equal c ?a) (call-interactively 'org-agenda-list))
5151 ((equal c ?t) (call-interactively 'org-todo-list))
5152 ((equal c ?T)
5153 (setq current-prefix-arg (or arg '(4)))
5154 (call-interactively 'org-todo-list))
5155 ((equal c ?m) (call-interactively 'org-tags-view))
5156 ((equal c ?M)
5157 (setq current-prefix-arg (or arg '(4)))
5158 (call-interactively 'org-tags-view))
5159 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5160 (setq type (nth 1 entry) string (nth 2 entry))
5161 (cond
5162 ((eq type 'tags)
5163 (org-tags-view current-prefix-arg string))
5164 ((eq type 'tags-todo)
5165 (org-tags-view '(4) string))
5166 ((eq type 'todo)
5167 (org-todo-list string))
5168 ((eq type 'tags-tree)
5169 (org-check-for-org-mode)
5170 (org-tags-sparse-tree current-prefix-arg string))
5171 ((eq type 'todo-tree)
5172 (org-check-for-org-mode)
5173 (org-occur (concat "^" outline-regexp "[ \t]*"
5174 (regexp-quote string) "\\>")))
5175 ((eq type 'occur-tree)
5176 (org-check-for-org-mode)
5177 (org-occur string))
5178 (t (error "Invalid custom agenda command type %s" type))))
5179 (t (error "Invalid key"))))))
5181 (defun org-check-for-org-mode ()
5182 "Make sure current buffer is in org-mode. Error if not."
5183 (or (eq major-mode 'org-mode)
5184 (error "Cannot execute org-mode agenda command on buffer in %s."
5185 major-mode)))
5187 (defun org-fit-agenda-window ()
5188 "Fit the window to the buffer size."
5189 (and org-fit-agenda-window
5190 (fboundp 'fit-window-to-buffer)
5191 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5192 (/ (frame-height) 2))))
5194 (defun org-agenda-files (&optional unrestricted)
5195 "Get the list of agenda files.
5196 Optional UNRESTRICTED means return the full list even if a restriction
5197 is currently in place."
5198 (cond
5199 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5200 ((stringp org-agenda-files) (org-read-agenda-file-list))
5201 ((listp org-agenda-files) org-agenda-files)
5202 (t (error "Invalid value of `org-agenda-files'"))))
5204 (defvar org-window-configuration)
5206 (defun org-edit-agenda-file-list ()
5207 "Edit the list of agenda files.
5208 Depending on setup, this either uses customize to edit the variable
5209 `org-agenda-files', or it visits the file that is holding the list. In the
5210 latter case, the buffer is set up in a way that saving it automatically kills
5211 the buffer and restores the previous window configuration."
5212 (interactive)
5213 (if (stringp org-agenda-files)
5214 (let ((cw (current-window-configuration)))
5215 (find-file org-agenda-files)
5216 (set (make-local-variable 'org-window-configuration) cw)
5217 (org-add-hook 'after-save-hook
5218 (lambda ()
5219 (set-window-configuration
5220 (prog1 org-window-configuration
5221 (kill-buffer (current-buffer))))
5222 (org-install-agenda-files-menu)
5223 (message "New agenda file list installed"))
5224 nil 'local)
5225 (message (substitute-command-keys
5226 "Edit list and finish with \\[save-buffer]")))
5227 (customize-variable 'org-agenda-files)))
5229 (defun org-store-new-agenda-file-list (list)
5230 "Set new value for the agenda file list and save it correcly."
5231 (if (stringp org-agenda-files)
5232 (let ((f org-agenda-files) b)
5233 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5234 (with-temp-file f
5235 (insert (mapconcat 'identity list "\n") "\n")))
5236 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5237 (setq org-agenda-files list)
5238 (customize-save-variable 'org-agenda-files org-agenda-files))))
5240 (defun org-read-agenda-file-list ()
5241 "Read the list of agenda files from a file."
5242 (when (stringp org-agenda-files)
5243 (with-temp-buffer
5244 (insert-file-contents org-agenda-files)
5245 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5247 (defvar org-agenda-markers nil
5248 "List of all currently active markers created by `org-agenda'.")
5249 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5250 "Creation time of the last agenda marker.")
5252 (defun org-agenda-new-marker (&optional pos)
5253 "Return a new agenda marker.
5254 Org-mode keeps a list of these markers and resets them when they are
5255 no longer in use."
5256 (let ((m (copy-marker (or pos (point)))))
5257 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5258 (push m org-agenda-markers)
5261 (defun org-agenda-maybe-reset-markers (&optional force)
5262 "Reset markers created by `org-agenda'. But only if they are old enough."
5263 (if (or force
5264 (> (- (time-to-seconds (current-time))
5265 org-agenda-last-marker-time)
5267 (while org-agenda-markers
5268 (move-marker (pop org-agenda-markers) nil))))
5270 (defvar org-agenda-new-buffers nil
5271 "Buffers created to visit agenda files.")
5273 (defun org-get-agenda-file-buffer (file)
5274 "Get a buffer visiting FILE. If the buffer needs to be created, add
5275 it to the list of buffers which might be released later."
5276 (let ((buf (find-buffer-visiting file)))
5277 (if buf
5278 buf ; just return it
5279 ;; Make a new buffer and remember it
5280 (setq buf (find-file-noselect file))
5281 (if buf (push buf org-agenda-new-buffers))
5282 buf)))
5284 (defun org-release-buffers (blist)
5285 "Release all buffers in list, asking the user for confirmation when needed.
5286 When a buffer is unmodified, it is just killed. When modified, it is saved
5287 \(if the user agrees) and then killed."
5288 (let (buf file)
5289 (while (setq buf (pop blist))
5290 (setq file (buffer-file-name buf))
5291 (when (and (buffer-modified-p buf)
5292 file
5293 (y-or-n-p (format "Save file %s? " file)))
5294 (with-current-buffer buf (save-buffer)))
5295 (kill-buffer buf))))
5297 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5299 (defun org-timeline (&optional include-all keep-modes)
5300 "Show a time-sorted view of the entries in the current org file.
5301 Only entries with a time stamp of today or later will be listed. With
5302 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5303 under the current date.
5304 If the buffer contains an active region, only check the region for
5305 dates."
5306 (interactive "P")
5307 (require 'calendar)
5308 (org-agenda-maybe-reset-markers 'force)
5309 (org-compile-prefix-format org-timeline-prefix-format)
5310 (let* ((dopast t)
5311 (dotodo include-all)
5312 (doclosed org-agenda-show-log)
5313 (org-agenda-keep-modes keep-modes)
5314 (entry buffer-file-name)
5315 (org-agenda-files (list buffer-file-name))
5316 (date (calendar-current-date))
5317 (win (selected-window))
5318 (pos1 (point))
5319 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5320 (end (if (org-region-active-p) (region-end) (point-max)))
5321 (day-numbers (org-get-all-dates beg end 'no-ranges
5322 t doclosed)) ; always include today
5323 (today (time-to-days (current-time)))
5324 (org-respect-restriction t)
5325 (past t)
5326 args
5327 s e rtn d)
5328 (setq org-agenda-redo-command
5329 (list 'progn
5330 (list 'switch-to-buffer-other-window (current-buffer))
5331 (list 'org-timeline (list 'quote include-all) t)))
5332 (if (not dopast)
5333 ;; Remove past dates from the list of dates.
5334 (setq day-numbers (delq nil (mapcar (lambda(x)
5335 (if (>= x today) x nil))
5336 day-numbers))))
5337 (switch-to-buffer-other-window
5338 (get-buffer-create org-agenda-buffer-name))
5339 (setq buffer-read-only nil)
5340 (erase-buffer)
5341 (org-agenda-mode) (setq buffer-read-only nil)
5342 (set (make-local-variable 'org-agenda-type) 'timeline)
5343 (if doclosed (push :closed args))
5344 (push :timestamp args)
5345 (if dotodo (push :todo args))
5346 (while (setq d (pop day-numbers))
5347 (if (and (>= d today)
5348 dopast
5349 past)
5350 (progn
5351 (setq past nil)
5352 (insert (make-string 79 ?-) "\n")))
5353 (setq date (calendar-gregorian-from-absolute d))
5354 (setq s (point))
5355 (setq rtn (apply 'org-agenda-get-day-entries
5356 entry date args))
5357 (if (or rtn (equal d today))
5358 (progn
5359 (insert (calendar-day-name date) " "
5360 (number-to-string (extract-calendar-day date)) " "
5361 (calendar-month-name (extract-calendar-month date)) " "
5362 (number-to-string (extract-calendar-year date)) "\n")
5363 (put-text-property s (1- (point)) 'face
5364 'org-level-3)
5365 (if (equal d today)
5366 (put-text-property s (1- (point)) 'org-today t))
5367 (insert (org-finalize-agenda-entries rtn) "\n")
5368 (put-text-property s (1- (point)) 'day d))))
5369 (goto-char (point-min))
5370 (setq buffer-read-only t)
5371 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5372 (point-min)))
5373 (when (not org-select-timeline-window)
5374 (select-window win)
5375 (goto-char pos1))))
5377 ;;;###autoload
5378 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5379 "Produce a weekly view from all files in variable `org-agenda-files'.
5380 The view will be for the current week, but from the overview buffer you
5381 will be able to go to other weeks.
5382 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5383 also be shown, under the current date.
5384 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5385 on the days are also shown. See the variable `org-log-done' for how
5386 to turn on logging.
5387 START-DAY defaults to TODAY, or to the most recent match for the weekday
5388 given in `org-agenda-start-on-weekday'.
5389 NDAYS defaults to `org-agenda-ndays'."
5390 (interactive "P")
5391 (org-agenda-maybe-reset-markers 'force)
5392 (org-compile-prefix-format org-agenda-prefix-format)
5393 (require 'calendar)
5394 (let* ((org-agenda-start-on-weekday
5395 (if (or (equal ndays 1)
5396 (and (null ndays) (equal 1 org-agenda-ndays)))
5397 nil org-agenda-start-on-weekday))
5398 (org-agenda-keep-modes keep-modes)
5399 (thefiles (org-agenda-files))
5400 (files thefiles)
5401 (win (selected-window))
5402 (today (time-to-days (current-time)))
5403 (sd (or start-day today))
5404 (start (if (or (null org-agenda-start-on-weekday)
5405 (< org-agenda-ndays 7))
5407 (let* ((nt (calendar-day-of-week
5408 (calendar-gregorian-from-absolute sd)))
5409 (n1 org-agenda-start-on-weekday)
5410 (d (- nt n1)))
5411 (- sd (+ (if (< d 0) 7 0) d)))))
5412 (day-numbers (list start))
5413 (inhibit-redisplay t)
5414 s e rtn rtnall file date d start-pos end-pos todayp nd)
5415 (setq org-agenda-redo-command
5416 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5417 ;; Make the list of days
5418 (setq ndays (or ndays org-agenda-ndays)
5419 nd ndays)
5420 (while (> ndays 1)
5421 (push (1+ (car day-numbers)) day-numbers)
5422 (setq ndays (1- ndays)))
5423 (setq day-numbers (nreverse day-numbers))
5424 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5425 (progn
5426 (delete-other-windows)
5427 (switch-to-buffer-other-window
5428 (get-buffer-create org-agenda-buffer-name))))
5429 (setq buffer-read-only nil)
5430 (erase-buffer)
5431 (org-agenda-mode) (setq buffer-read-only nil)
5432 (set (make-local-variable 'org-agenda-type) 'agenda)
5433 (set (make-local-variable 'starting-day) (car day-numbers))
5434 (set (make-local-variable 'include-all-loc) include-all)
5435 (when (and (or include-all org-agenda-include-all-todo)
5436 (member today day-numbers))
5437 (setq files thefiles
5438 rtnall nil)
5439 (while (setq file (pop files))
5440 (catch 'nextfile
5441 (org-check-agenda-file file)
5442 (setq date (calendar-gregorian-from-absolute today)
5443 rtn (org-agenda-get-day-entries
5444 file date :todo))
5445 (setq rtnall (append rtnall rtn))))
5446 (when rtnall
5447 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5448 (add-text-properties (point-min) (1- (point))
5449 (list 'face 'org-level-3))
5450 (insert (org-finalize-agenda-entries rtnall) "\n")))
5451 (while (setq d (pop day-numbers))
5452 (setq date (calendar-gregorian-from-absolute d)
5453 s (point))
5454 (if (or (setq todayp (= d today))
5455 (and (not start-pos) (= d sd)))
5456 (setq start-pos (point))
5457 (if (and start-pos (not end-pos))
5458 (setq end-pos (point))))
5459 (setq files thefiles
5460 rtnall nil)
5461 (while (setq file (pop files))
5462 (catch 'nextfile
5463 (org-check-agenda-file file)
5464 (if org-agenda-show-log
5465 (setq rtn (org-agenda-get-day-entries
5466 file date
5467 :deadline :scheduled :timestamp :closed))
5468 (setq rtn (org-agenda-get-day-entries
5469 file date
5470 :deadline :scheduled :timestamp)))
5471 (setq rtnall (append rtnall rtn))))
5472 (if org-agenda-include-diary
5473 (progn
5474 (require 'diary-lib)
5475 (setq rtn (org-get-entries-from-diary date))
5476 (setq rtnall (append rtnall rtn))))
5477 (if (or rtnall org-agenda-show-all-dates)
5478 (progn
5479 (insert (format "%-9s %2d %s %4d\n"
5480 (calendar-day-name date)
5481 (extract-calendar-day date)
5482 (calendar-month-name (extract-calendar-month date))
5483 (extract-calendar-year date)))
5484 (put-text-property s (1- (point)) 'face
5485 'org-level-3)
5486 (if rtnall (insert
5487 (org-finalize-agenda-entries
5488 (org-agenda-add-time-grid-maybe
5489 rtnall nd todayp))
5490 "\n"))
5491 (put-text-property s (1- (point)) 'day d))))
5492 (goto-char (point-min))
5493 (setq buffer-read-only t)
5494 (org-fit-agenda-window)
5495 (unless (and (pos-visible-in-window-p (point-min))
5496 (pos-visible-in-window-p (point-max)))
5497 (goto-char (1- (point-max)))
5498 (recenter -1)
5499 (if (not (pos-visible-in-window-p (or start-pos 1)))
5500 (progn
5501 (goto-char (or start-pos 1))
5502 (recenter 1))))
5503 (goto-char (or start-pos 1))
5504 (if (not org-select-agenda-window) (select-window win))
5505 (message "")))
5507 (defvar org-select-this-todo-keyword nil)
5509 ;;;###autoload
5510 (defun org-todo-list (arg &optional keep-modes)
5511 "Show all TODO entries from all agenda file in a single list.
5512 The prefix arg can be used to select a specific TODO keyword and limit
5513 the list to these. When using \\[universal-argument], you will be prompted
5514 for a keyword. A numeric prefix directly selects the Nth keyword in
5515 `org-todo-keywords'."
5516 (interactive "P")
5517 (org-agenda-maybe-reset-markers 'force)
5518 (org-compile-prefix-format org-agenda-prefix-format)
5519 (let* ((org-agenda-keep-modes keep-modes)
5520 (today (time-to-days (current-time)))
5521 (date (calendar-gregorian-from-absolute today))
5522 (win (selected-window))
5523 (kwds org-todo-keywords)
5524 (completion-ignore-case t)
5525 (org-select-this-todo-keyword
5526 (if (stringp arg) arg
5527 (and arg (integerp arg) (> arg 0)
5528 (nth (1- arg) org-todo-keywords))))
5529 rtn rtnall files file pos)
5530 (when (equal arg '(4))
5531 (setq org-select-this-todo-keyword
5532 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5533 nil t)))
5534 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5535 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5536 (progn
5537 (delete-other-windows)
5538 (switch-to-buffer-other-window
5539 (get-buffer-create org-agenda-buffer-name))))
5540 (setq buffer-read-only nil)
5541 (erase-buffer)
5542 (org-agenda-mode) (setq buffer-read-only nil)
5543 (set (make-local-variable 'org-agenda-type) 'todo)
5544 (set (make-local-variable 'last-arg) arg)
5545 (set (make-local-variable 'org-todo-keywords) kwds)
5546 (set (make-local-variable 'org-agenda-redo-command)
5547 '(org-todo-list (or current-prefix-arg last-arg) t))
5548 (setq files (org-agenda-files)
5549 rtnall nil)
5550 (while (setq file (pop files))
5551 (catch 'nextfile
5552 (org-check-agenda-file file)
5553 (setq rtn (org-agenda-get-day-entries file date :todo))
5554 (setq rtnall (append rtnall rtn))))
5555 (insert "Global list of TODO items of type: ")
5556 (add-text-properties (point-min) (1- (point))
5557 (list 'face 'org-level-3))
5558 (setq pos (point))
5559 (insert (or org-select-this-todo-keyword "ALL") "\n")
5560 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5561 (setq pos (point))
5562 (insert
5563 "Available with `N r': (0)ALL "
5564 (let ((n 0))
5565 (mapconcat (lambda (x)
5566 (format "(%d)%s" (setq n (1+ n)) x))
5567 org-todo-keywords " "))
5568 "\n")
5569 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5570 (when rtnall
5571 (insert (org-finalize-agenda-entries rtnall) "\n"))
5572 (goto-char (point-min))
5573 (setq buffer-read-only t)
5574 (org-fit-agenda-window)
5575 (if (not org-select-agenda-window) (select-window win))))
5577 (defun org-check-agenda-file (file)
5578 "Make sure FILE exists. If not, ask user what to do."
5579 (when (not (file-exists-p file))
5580 (message "non-existent file %s. [R]emove from list or [A]bort?"
5581 (abbreviate-file-name file))
5582 (let ((r (downcase (read-char-exclusive))))
5583 (cond
5584 ((equal r ?r)
5585 (org-remove-file file)
5586 (throw 'nextfile t))
5587 (t (error "Abort"))))))
5589 (defun org-agenda-check-type (error &rest types)
5590 "Check if agenda buffer is of allowed type.
5591 If ERROR is non-nil, throw an error, otherwise just return nil."
5592 (if (memq org-agenda-type types)
5594 (if error
5595 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5596 nil)))
5598 (defun org-agenda-quit ()
5599 "Exit agenda by removing the window or the buffer."
5600 (interactive)
5601 (let ((buf (current-buffer)))
5602 (if (not (one-window-p)) (delete-window))
5603 (kill-buffer buf)
5604 (org-agenda-maybe-reset-markers 'force)))
5606 (defun org-agenda-exit ()
5607 "Exit agenda by removing the window or the buffer.
5608 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5609 Org-mode buffers visited directly by the user will not be touched."
5610 (interactive)
5611 (org-release-buffers org-agenda-new-buffers)
5612 (setq org-agenda-new-buffers nil)
5613 (org-agenda-quit))
5615 (defun org-agenda-redo ()
5616 "Rebuild Agenda.
5617 When this is the global TODO list, a prefix argument will be interpreted."
5618 (interactive)
5619 (message "Rebuilding agenda buffer...")
5620 (eval org-agenda-redo-command)
5621 (message "Rebuilding agenda buffer...done"))
5623 (defun org-agenda-goto-today ()
5624 "Go to today."
5625 (interactive)
5626 (org-agenda-check-type t 'timeline 'agenda)
5627 (if (boundp 'starting-day)
5628 (let ((cmd (car org-agenda-redo-command))
5629 (iall (nth 1 org-agenda-redo-command))
5630 (nday (nth 3 org-agenda-redo-command))
5631 (keep (nth 4 org-agenda-redo-command)))
5632 (eval (list cmd iall nil nday keep)))
5633 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5634 (point-min)))))
5636 (defun org-agenda-later (arg)
5637 "Go forward in time by `org-agenda-ndays' days.
5638 With prefix ARG, go forward that many times `org-agenda-ndays'."
5639 (interactive "p")
5640 (org-agenda-check-type t 'agenda)
5641 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5642 (+ starting-day (* arg org-agenda-ndays)) nil t))
5644 (defun org-agenda-earlier (arg)
5645 "Go back in time by `org-agenda-ndays' days.
5646 With prefix ARG, go back that many times `org-agenda-ndays'."
5647 (interactive "p")
5648 (org-agenda-check-type t 'agenda)
5649 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5650 (- starting-day (* arg org-agenda-ndays)) nil t))
5652 (defun org-agenda-week-view ()
5653 "Switch to weekly view for agenda."
5654 (interactive)
5655 (org-agenda-check-type t 'agenda)
5656 (setq org-agenda-ndays 7)
5657 (org-agenda-list include-all-loc
5658 (or (get-text-property (point) 'day)
5659 starting-day)
5660 nil t)
5661 (org-agenda-set-mode-name)
5662 (message "Switched to week view"))
5664 (defun org-agenda-day-view ()
5665 "Switch to daily view for agenda."
5666 (interactive)
5667 (org-agenda-check-type t 'agenda)
5668 (setq org-agenda-ndays 1)
5669 (org-agenda-list include-all-loc
5670 (or (get-text-property (point) 'day)
5671 starting-day)
5672 nil t)
5673 (org-agenda-set-mode-name)
5674 (message "Switched to day view"))
5676 (defun org-agenda-next-date-line (&optional arg)
5677 "Jump to the next line indicating a date in agenda buffer."
5678 (interactive "p")
5679 (org-agenda-check-type t 'agenda 'timeline)
5680 (beginning-of-line 1)
5681 (if (looking-at "^\\S-") (forward-char 1))
5682 (if (not (re-search-forward "^\\S-" nil t arg))
5683 (progn
5684 (backward-char 1)
5685 (error "No next date after this line in this buffer")))
5686 (goto-char (match-beginning 0)))
5688 (defun org-agenda-previous-date-line (&optional arg)
5689 "Jump to the previous line indicating a date in agenda buffer."
5690 (interactive "p")
5691 (org-agenda-check-type t 'agenda 'timeline)
5692 (beginning-of-line 1)
5693 (if (not (re-search-backward "^\\S-" nil t arg))
5694 (error "No previous date before this line in this buffer")))
5696 ;; Initialize the highlight
5697 (defvar org-hl (org-make-overlay 1 1))
5698 (org-overlay-put org-hl 'face 'highlight)
5700 (defun org-highlight (begin end &optional buffer)
5701 "Highlight a region with overlay."
5702 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5703 org-hl begin end (or buffer (current-buffer))))
5705 (defun org-unhighlight ()
5706 "Detach overlay INDEX."
5707 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5710 (defun org-agenda-follow-mode ()
5711 "Toggle follow mode in an agenda buffer."
5712 (interactive)
5713 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5714 (org-agenda-set-mode-name)
5715 (message "Follow mode is %s"
5716 (if org-agenda-follow-mode "on" "off")))
5718 (defun org-agenda-log-mode ()
5719 "Toggle log mode in an agenda buffer."
5720 (interactive)
5721 (org-agenda-check-type t 'agenda 'timeline)
5722 (setq org-agenda-show-log (not org-agenda-show-log))
5723 (org-agenda-set-mode-name)
5724 (org-agenda-redo)
5725 (message "Log mode is %s"
5726 (if org-agenda-show-log "on" "off")))
5728 (defun org-agenda-toggle-diary ()
5729 "Toggle diary inclusion in an agenda buffer."
5730 (interactive)
5731 (org-agenda-check-type t 'agenda)
5732 (setq org-agenda-include-diary (not org-agenda-include-diary))
5733 (org-agenda-redo)
5734 (org-agenda-set-mode-name)
5735 (message "Diary inclusion turned %s"
5736 (if org-agenda-include-diary "on" "off")))
5738 (defun org-agenda-toggle-time-grid ()
5739 "Toggle time grid in an agenda buffer."
5740 (interactive)
5741 (org-agenda-check-type t 'agenda)
5742 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5743 (org-agenda-redo)
5744 (org-agenda-set-mode-name)
5745 (message "Time-grid turned %s"
5746 (if org-agenda-use-time-grid "on" "off")))
5748 (defun org-agenda-set-mode-name ()
5749 "Set the mode name to indicate all the small mode settings."
5750 (setq mode-name
5751 (concat "Org-Agenda"
5752 (if (equal org-agenda-ndays 1) " Day" "")
5753 (if (equal org-agenda-ndays 7) " Week" "")
5754 (if org-agenda-follow-mode " Follow" "")
5755 (if org-agenda-include-diary " Diary" "")
5756 (if org-agenda-use-time-grid " Grid" "")
5757 (if org-agenda-show-log " Log" "")))
5758 (force-mode-line-update))
5760 (defun org-agenda-post-command-hook ()
5761 (and (eolp) (not (bolp)) (backward-char 1))
5762 (if (and org-agenda-follow-mode
5763 (get-text-property (point) 'org-marker))
5764 (org-agenda-show)))
5766 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5768 (defun org-get-entries-from-diary (date)
5769 "Get the (Emacs Calendar) diary entries for DATE."
5770 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5771 (diary-display-hook '(fancy-diary-display))
5772 (list-diary-entries-hook
5773 (cons 'org-diary-default-entry list-diary-entries-hook))
5774 (diary-file-name-prefix-function nil) ; turn this feature off
5775 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5776 entries
5777 (org-disable-agenda-to-diary t))
5778 (save-excursion
5779 (save-window-excursion
5780 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5781 (if (not (get-buffer fancy-diary-buffer))
5782 (setq entries nil)
5783 (with-current-buffer fancy-diary-buffer
5784 (setq buffer-read-only nil)
5785 (if (= (point-max) 1)
5786 ;; No entries
5787 (setq entries nil)
5788 ;; Omit the date and other unnecessary stuff
5789 (org-agenda-cleanup-fancy-diary)
5790 ;; Add prefix to each line and extend the text properties
5791 (if (= (point-max) 1)
5792 (setq entries nil)
5793 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5794 (set-buffer-modified-p nil)
5795 (kill-buffer fancy-diary-buffer)))
5796 (when entries
5797 (setq entries (org-split-string entries "\n"))
5798 (setq entries
5799 (mapcar
5800 (lambda (x)
5801 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5802 ;; Extend the text properties to the beginning of the line
5803 (org-add-props x (text-properties-at (1- (length x)) x)))
5804 entries)))))
5806 (defun org-agenda-cleanup-fancy-diary ()
5807 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5808 This gets rid of the date, the underline under the date, and
5809 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5810 date. It also removes lines that contain only whitespace."
5811 (goto-char (point-min))
5812 (if (looking-at ".*?:[ \t]*")
5813 (progn
5814 (replace-match "")
5815 (re-search-forward "\n=+$" nil t)
5816 (replace-match "")
5817 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5818 (re-search-forward "\n=+$" nil t)
5819 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5820 (goto-char (point-min))
5821 (while (re-search-forward "^ +\n" nil t)
5822 (replace-match ""))
5823 (goto-char (point-min))
5824 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5825 (replace-match "")))
5827 ;; Make sure entries from the diary have the right text properties.
5828 (eval-after-load "diary-lib"
5829 '(if (boundp 'diary-modify-entry-list-string-function)
5830 ;; We can rely on the hook, nothing to do
5832 ;; Hook not avaiable, must use advice to make this work
5833 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5834 "Make the position visible."
5835 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5836 (stringp string)
5837 buffer-file-name)
5838 (setq string (org-modify-diary-entry-string string))))))
5840 (defun org-modify-diary-entry-string (string)
5841 "Add text properties to string, allowing org-mode to act on it."
5842 (org-add-props string nil
5843 'mouse-face 'highlight
5844 'keymap org-agenda-keymap
5845 'help-echo (format "mouse-2 or RET jump to diary file %s"
5846 (abbreviate-file-name buffer-file-name))
5847 'org-agenda-diary-link t
5848 'org-marker (org-agenda-new-marker (point-at-bol))))
5850 (defun org-diary-default-entry ()
5851 "Add a dummy entry to the diary.
5852 Needed to avoid empty dates which mess up holiday display."
5853 ;; Catch the error if dealing with the new add-to-diary-alist
5854 (when org-disable-agenda-to-diary
5855 (condition-case nil
5856 (add-to-diary-list original-date "Org-mode dummy" "")
5857 (error
5858 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5860 (defun org-cycle-agenda-files ()
5861 "Cycle through the files in `org-agenda-files'.
5862 If the current buffer visits an agenda file, find the next one in the list.
5863 If the current buffer does not, find the first agenda file."
5864 (interactive)
5865 (let* ((fs (org-agenda-files t))
5866 (files (append fs (list (car fs))))
5867 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5868 file)
5869 (unless files (error "No agenda files"))
5870 (catch 'exit
5871 (while (setq file (pop files))
5872 (if (equal (file-truename file) tcf)
5873 (when (car files)
5874 (find-file (car files))
5875 (throw 'exit t))))
5876 (find-file (car fs)))))
5878 (defun org-agenda-file-to-end ()
5879 "Move/add the current file to the end of the agenda file list.
5880 If the file is not present in the list, it is appended to the list. If it is
5881 present, it is moved there."
5882 (interactive)
5883 (org-agenda-file-to-front 'to-end))
5885 (defun org-agenda-file-to-front (&optional to-end)
5886 "Move/add the current file to the top of the agenda file list.
5887 If the file is not present in the list, it is added to the front. If it is
5888 present, it is moved there. With optional argument TO-END, add/move to the
5889 end of the list."
5890 (interactive "P")
5891 (let ((file-alist (mapcar (lambda (x)
5892 (cons (file-truename x) x))
5893 (org-agenda-files t)))
5894 (ctf (file-truename buffer-file-name))
5895 x had)
5896 (setq x (assoc ctf file-alist) had x)
5898 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5899 (if to-end
5900 (setq file-alist (append (delq x file-alist) (list x)))
5901 (setq file-alist (cons x (delq x file-alist))))
5902 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5903 (org-install-agenda-files-menu)
5904 (message "File %s to %s of agenda file list"
5905 (if had "moved" "added") (if to-end "end" "front"))))
5907 (defun org-remove-file (&optional file)
5908 "Remove current file from the list of files in variable `org-agenda-files'.
5909 These are the files which are being checked for agenda entries.
5910 Optional argument FILE means, use this file instead of the current."
5911 (interactive)
5912 (let* ((file (or file buffer-file-name))
5913 (true-file (file-truename file))
5914 (afile (abbreviate-file-name file))
5915 (files (delq nil (mapcar
5916 (lambda (x)
5917 (if (equal true-file
5918 (file-truename x))
5919 nil x))
5920 (org-agenda-files t)))))
5921 (if (not (= (length files) (length (org-agenda-files t))))
5922 (progn
5923 (org-store-new-agenda-file-list files)
5924 (org-install-agenda-files-menu)
5925 (message "Removed file: %s" afile))
5926 (message "File was not in list: %s" afile))))
5928 (defun org-file-menu-entry (file)
5929 (vector file (list 'find-file file) t))
5931 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5932 "Return a list of all relevant day numbers from BEG to END buffer positions.
5933 If NO-RANGES is non-nil, include only the start and end dates of a range,
5934 not every single day in the range. If FORCE-TODAY is non-nil, make
5935 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5936 inactive time stamps (those in square brackets) are included."
5937 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5938 dates date day day1 day2 ts1 ts2)
5939 (if force-today
5940 (setq dates (list (time-to-days (current-time)))))
5941 (save-excursion
5942 (goto-char beg)
5943 (while (re-search-forward re end t)
5944 (setq day (time-to-days (org-time-string-to-time
5945 (substring (match-string 1) 0 10))))
5946 (or (memq day dates) (push day dates)))
5947 (unless no-ranges
5948 (goto-char beg)
5949 (while (re-search-forward org-tr-regexp end t)
5950 (setq ts1 (substring (match-string 1) 0 10)
5951 ts2 (substring (match-string 2) 0 10)
5952 day1 (time-to-days (org-time-string-to-time ts1))
5953 day2 (time-to-days (org-time-string-to-time ts2)))
5954 (while (< (setq day1 (1+ day1)) day2)
5955 (or (memq day1 dates) (push day1 dates)))))
5956 (sort dates '<))))
5958 ;;;###autoload
5959 (defun org-diary (&rest args)
5960 "Return diary information from org-files.
5961 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5962 It accesses org files and extracts information from those files to be
5963 listed in the diary. The function accepts arguments specifying what
5964 items should be listed. The following arguments are allowed:
5966 :timestamp List the headlines of items containing a date stamp or
5967 date range matching the selected date. Deadlines will
5968 also be listed, on the expiration day.
5970 :deadline List any deadlines past due, or due within
5971 `org-deadline-warning-days'. The listing occurs only
5972 in the diary for *today*, not at any other date. If
5973 an entry is marked DONE, it is no longer listed.
5975 :scheduled List all items which are scheduled for the given date.
5976 The diary for *today* also contains items which were
5977 scheduled earlier and are not yet marked DONE.
5979 :todo List all TODO items from the org-file. This may be a
5980 long list - so this is not turned on by default.
5981 Like deadlines, these entries only show up in the
5982 diary for *today*, not at any other date.
5984 The call in the diary file should look like this:
5986 &%%(org-diary) ~/path/to/some/orgfile.org
5988 Use a separate line for each org file to check. Or, if you omit the file name,
5989 all files listed in `org-agenda-files' will be checked automatically:
5991 &%%(org-diary)
5993 If you don't give any arguments (as in the example above), the default
5994 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5995 also be written as
5997 &%%(org-diary :deadline :timestamp :scheduled)
5999 The function expects the lisp variables `entry' and `date' to be provided
6000 by the caller, because this is how the calendar works. Don't use this
6001 function from a program - use `org-agenda-get-day-entries' instead."
6002 (org-agenda-maybe-reset-markers)
6003 (org-compile-prefix-format org-agenda-prefix-format)
6004 (setq args (or args '(:deadline :scheduled :timestamp)))
6005 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
6006 (list entry)
6007 (org-agenda-files t)))
6008 file rtn results)
6009 ;; If this is called during org-agenda, don't return any entries to
6010 ;; the calendar. Org Agenda will list these entries itself.
6011 (if org-disable-agenda-to-diary (setq files nil))
6012 (while (setq file (pop files))
6013 (setq rtn (apply 'org-agenda-get-day-entries file date args))
6014 (setq results (append results rtn)))
6015 (if results
6016 (concat (org-finalize-agenda-entries results) "\n"))))
6017 (defvar org-category-table nil)
6018 (defun org-get-category-table ()
6019 "Get the table of categories and positions in current buffer."
6020 (let (tbl)
6021 (save-excursion
6022 (goto-char (point-min))
6023 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
6024 (push (cons (point) (org-trim (match-string 2))) tbl)))
6025 tbl))
6026 (defun org-get-category (&optional pos)
6027 "Get the category applying to position POS."
6028 (if (not org-category-table)
6029 (cond
6030 ((null org-category)
6031 (setq org-category
6032 (if buffer-file-name
6033 (file-name-sans-extension
6034 (file-name-nondirectory buffer-file-name))
6035 "???")))
6036 ((symbolp org-category) (symbol-name org-category))
6037 (t org-category))
6038 (let ((tbl org-category-table)
6039 (pos (or pos (point))))
6040 (while (and tbl (> (caar tbl) pos))
6041 (pop tbl))
6042 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
6043 org-category-table))))))
6045 (defun org-agenda-get-day-entries (file date &rest args)
6046 "Does the work for `org-diary' and `org-agenda'.
6047 FILE is the path to a file to be checked for entries. DATE is date like
6048 the one returned by `calendar-current-date'. ARGS are symbols indicating
6049 which kind of entries should be extracted. For details about these, see
6050 the documentation of `org-diary'."
6051 (setq args (or args '(:deadline :scheduled :timestamp)))
6052 (let* ((org-startup-with-deadline-check nil)
6053 (org-startup-folded nil)
6054 (org-startup-align-all-tables nil)
6055 (buffer (if (file-exists-p file)
6056 (org-get-agenda-file-buffer file)
6057 (error "No such file %s" file)))
6058 arg results rtn)
6059 (if (not buffer)
6060 ;; If file does not exist, make sure an error message ends up in diary
6061 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6062 (with-current-buffer buffer
6063 (unless (eq major-mode 'org-mode)
6064 (error "Agenda file %s is not in `org-mode'" file))
6065 (setq org-category-table (org-get-category-table))
6066 (let ((case-fold-search nil))
6067 (save-excursion
6068 (save-restriction
6069 (if org-respect-restriction
6070 (if (org-region-active-p)
6071 ;; Respect a region to restrict search
6072 (narrow-to-region (region-beginning) (region-end)))
6073 ;; If we work for the calendar or many files,
6074 ;; get rid of any restriction
6075 (widen))
6076 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
6077 (while (setq arg (pop args))
6078 (cond
6079 ((and (eq arg :todo)
6080 (equal date (calendar-current-date)))
6081 (setq rtn (org-agenda-get-todos))
6082 (setq results (append results rtn)))
6083 ((eq arg :timestamp)
6084 (setq rtn (org-agenda-get-blocks))
6085 (setq results (append results rtn))
6086 (setq rtn (org-agenda-get-timestamps))
6087 (setq results (append results rtn)))
6088 ((eq arg :scheduled)
6089 (setq rtn (org-agenda-get-scheduled))
6090 (setq results (append results rtn)))
6091 ((eq arg :closed)
6092 (setq rtn (org-agenda-get-closed))
6093 (setq results (append results rtn)))
6094 ((and (eq arg :deadline)
6095 (equal date (calendar-current-date)))
6096 (setq rtn (org-agenda-get-deadlines))
6097 (setq results (append results rtn))))))))
6098 results))))
6100 (defun org-entry-is-done-p ()
6101 "Is the current entry marked DONE?"
6102 (save-excursion
6103 (and (re-search-backward "[\r\n]\\*" nil t)
6104 (looking-at org-nl-done-regexp))))
6106 (defun org-at-date-range-p ()
6107 "Is the cursor inside a date range?"
6108 (interactive)
6109 (save-excursion
6110 (catch 'exit
6111 (let ((pos (point)))
6112 (skip-chars-backward "^<\r\n")
6113 (skip-chars-backward "<")
6114 (and (looking-at org-tr-regexp)
6115 (>= (match-end 0) pos)
6116 (throw 'exit t))
6117 (skip-chars-backward "^<\r\n")
6118 (skip-chars-backward "<")
6119 (and (looking-at org-tr-regexp)
6120 (>= (match-end 0) pos)
6121 (throw 'exit t)))
6122 nil)))
6124 (defun org-agenda-get-todos ()
6125 "Return the TODO information for agenda display."
6126 (let* ((props (list 'face nil
6127 'done-face 'org-done
6128 'org-not-done-regexp org-not-done-regexp
6129 'mouse-face 'highlight
6130 'keymap org-agenda-keymap
6131 'help-echo
6132 (format "mouse-2 or RET jump to org file %s"
6133 (abbreviate-file-name buffer-file-name))))
6134 (regexp (concat "[\n\r]\\*+ *\\("
6135 (if org-select-this-todo-keyword
6136 (concat "\\<\\(" org-select-this-todo-keyword
6137 "\\)\\>")
6138 org-not-done-regexp)
6139 "[^\n\r]*\\)"))
6140 (sched-re (concat ".*\n.*?" org-scheduled-time-regexp))
6141 marker priority category tags
6142 ee txt)
6143 (goto-char (point-min))
6144 (while (re-search-forward regexp nil t)
6145 (when (not (and org-agenda-todo-ignore-scheduled
6146 (save-match-data (looking-at sched-re))))
6147 (goto-char (match-beginning 1))
6148 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
6149 category (org-get-category)
6150 tags (org-get-tags-at (point))
6151 txt (org-format-agenda-item "" (match-string 1) category tags)
6152 priority
6153 (+ (org-get-priority txt)
6154 (if org-todo-kwd-priority-p
6155 (- org-todo-kwd-max-priority -2
6156 (length
6157 (member (match-string 2) org-todo-keywords)))
6158 1)))
6159 (org-add-props txt props
6160 'org-marker marker 'org-hd-marker marker
6161 'priority priority 'category category)
6162 (push txt ee)
6163 (if org-agenda-todo-list-sublevels ; FIXME???? Change needed?
6164 (goto-char (match-end 1))
6165 (org-end-of-subtree 'invisible))))
6166 (nreverse ee)))
6168 (defconst org-agenda-no-heading-message
6169 "No heading for this item in buffer or region.")
6171 (defun org-agenda-get-timestamps ()
6172 "Return the date stamp information for agenda display."
6173 (let* ((props (list 'face nil
6174 'org-not-done-regexp org-not-done-regexp
6175 'mouse-face 'highlight
6176 'keymap org-agenda-keymap
6177 'help-echo
6178 (format "mouse-2 or RET jump to org file %s"
6179 (abbreviate-file-name buffer-file-name))))
6180 (regexp (regexp-quote
6181 (substring
6182 (format-time-string
6183 (car org-time-stamp-formats)
6184 (apply 'encode-time ; DATE bound by calendar
6185 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6186 0 11)))
6187 marker hdmarker deadlinep scheduledp donep tmp priority category
6188 ee txt timestr tags)
6189 (goto-char (point-min))
6190 (while (re-search-forward regexp nil t)
6191 (if (not (save-match-data (org-at-date-range-p)))
6192 (progn
6193 (setq marker (org-agenda-new-marker (match-beginning 0))
6194 category (org-get-category (match-beginning 0))
6195 tmp (buffer-substring (max (point-min)
6196 (- (match-beginning 0)
6197 org-ds-keyword-length))
6198 (match-beginning 0))
6199 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6200 deadlinep (string-match org-deadline-regexp tmp)
6201 scheduledp (string-match org-scheduled-regexp tmp)
6202 donep (org-entry-is-done-p))
6203 (if (string-match ">" timestr)
6204 ;; substring should only run to end of time stamp
6205 (setq timestr (substring timestr 0 (match-end 0))))
6206 (save-excursion
6207 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6208 (progn
6209 (goto-char (match-end 1))
6210 (setq hdmarker (org-agenda-new-marker)
6211 tags (org-get-tags-at))
6212 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6213 (setq txt (org-format-agenda-item
6214 (format "%s%s"
6215 (if deadlinep "Deadline: " "")
6216 (if scheduledp "Scheduled: " ""))
6217 (match-string 1) category tags timestr)))
6218 (setq txt org-agenda-no-heading-message))
6219 (setq priority (org-get-priority txt))
6220 (org-add-props txt props
6221 'org-marker marker 'org-hd-marker hdmarker)
6222 (if deadlinep
6223 (org-add-props txt nil
6224 'face (if donep 'org-done 'org-warning)
6225 'undone-face 'org-warning 'done-face 'org-done
6226 'category category 'priority (+ 100 priority))
6227 (if scheduledp
6228 (org-add-props txt nil
6229 'face 'org-scheduled-today
6230 'undone-face 'org-scheduled-today 'done-face 'org-done
6231 'category category 'priority (+ 99 priority))
6232 (org-add-props txt nil 'priority priority 'category category)))
6233 (push txt ee))
6234 (outline-next-heading))))
6235 (nreverse ee)))
6237 (defun org-agenda-get-closed ()
6238 "Return the logged TODO entries for agenda display."
6239 (let* ((props (list 'mouse-face 'highlight
6240 'org-not-done-regexp org-not-done-regexp
6241 'keymap org-agenda-keymap
6242 'help-echo
6243 (format "mouse-2 or RET jump to org file %s"
6244 (abbreviate-file-name buffer-file-name))))
6245 (regexp (concat
6246 "\\<" org-closed-string " *\\["
6247 (regexp-quote
6248 (substring
6249 (format-time-string
6250 (car org-time-stamp-formats)
6251 (apply 'encode-time ; DATE bound by calendar
6252 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6253 1 11))))
6254 marker hdmarker priority category tags
6255 ee txt timestr)
6256 (goto-char (point-min))
6257 (while (re-search-forward regexp nil t)
6258 (if (not (save-match-data (org-at-date-range-p)))
6259 (progn
6260 (setq marker (org-agenda-new-marker (match-beginning 0))
6261 category (org-get-category (match-beginning 0))
6262 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6263 ;; donep (org-entry-is-done-p)
6265 (if (string-match "\\]" timestr)
6266 ;; substring should only run to end of time stamp
6267 (setq timestr (substring timestr 0 (match-end 0))))
6268 (save-excursion
6269 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6270 (progn
6271 (goto-char (match-end 1))
6272 (setq hdmarker (org-agenda-new-marker)
6273 tags (org-get-tags-at))
6274 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6275 (setq txt (org-format-agenda-item
6276 "Closed: "
6277 (match-string 1) category tags timestr)))
6278 (setq txt org-agenda-no-heading-message))
6279 (setq priority 100000)
6280 (org-add-props txt props
6281 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6282 'priority priority 'category category
6283 'undone-face 'org-warning 'done-face 'org-done)
6284 (push txt ee))
6285 (outline-next-heading))))
6286 (nreverse ee)))
6288 (defun org-agenda-get-deadlines ()
6289 "Return the deadline information for agenda display."
6290 (let* ((wdays org-deadline-warning-days)
6291 (props (list 'mouse-face 'highlight
6292 'org-not-done-regexp org-not-done-regexp
6293 'keymap org-agenda-keymap
6294 'help-echo
6295 (format "mouse-2 or RET jump to org file %s"
6296 (abbreviate-file-name buffer-file-name))))
6297 (regexp org-deadline-time-regexp)
6298 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6299 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6300 d2 diff pos pos1 category tags
6301 ee txt head)
6302 (goto-char (point-min))
6303 (while (re-search-forward regexp nil t)
6304 (setq pos (1- (match-beginning 1))
6305 d2 (time-to-days
6306 (org-time-string-to-time (match-string 1)))
6307 diff (- d2 d1))
6308 ;; When to show a deadline in the calendar:
6309 ;; If the expiration is within wdays warning time.
6310 ;; Past-due deadlines are only shown on the current date
6311 (if (and (< diff wdays) todayp (not (= diff 0)))
6312 (save-excursion
6313 (setq category (org-get-category))
6314 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6315 (progn
6316 (goto-char (match-end 0))
6317 (setq pos1 (match-end 1))
6318 (setq tags (org-get-tags-at pos1))
6319 (setq head (buffer-substring-no-properties
6320 (point)
6321 (progn (skip-chars-forward "^\r\n")
6322 (point))))
6323 (if (string-match org-looking-at-done-regexp head)
6324 (setq txt nil)
6325 (setq txt (org-format-agenda-item
6326 (format "In %3d d.: " diff) head category tags))))
6327 (setq txt org-agenda-no-heading-message))
6328 (when txt
6329 (org-add-props txt props
6330 'org-marker (org-agenda-new-marker pos)
6331 'org-hd-marker (org-agenda-new-marker pos1)
6332 'priority (+ (- 10 diff) (org-get-priority txt))
6333 'category category
6334 'face (cond ((<= diff 0) 'org-warning)
6335 ((<= diff 5) 'org-scheduled-previously)
6336 (t nil))
6337 'undone-face (cond
6338 ((<= diff 0) 'org-warning)
6339 ((<= diff 5) 'org-scheduled-previously)
6340 (t nil))
6341 'done-face 'org-done)
6342 (push txt ee)))))
6343 ee))
6345 (defun org-agenda-get-scheduled ()
6346 "Return the scheduled information for agenda display."
6347 (let* ((props (list 'face 'org-scheduled-previously
6348 'org-not-done-regexp org-not-done-regexp
6349 'undone-face 'org-scheduled-previously
6350 'done-face 'org-done
6351 'mouse-face 'highlight
6352 'keymap org-agenda-keymap
6353 'help-echo
6354 (format "mouse-2 or RET jump to org file %s"
6355 (abbreviate-file-name buffer-file-name))))
6356 (regexp org-scheduled-time-regexp)
6357 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6358 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6359 d2 diff pos pos1 category tags
6360 ee txt head)
6361 (goto-char (point-min))
6362 (while (re-search-forward regexp nil t)
6363 (setq pos (1- (match-beginning 1))
6364 d2 (time-to-days
6365 (org-time-string-to-time (match-string 1)))
6366 diff (- d2 d1))
6367 ;; When to show a scheduled item in the calendar:
6368 ;; If it is on or past the date.
6369 (if (and (< diff 0) todayp)
6370 (save-excursion
6371 (setq category (org-get-category))
6372 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6373 (progn
6374 (goto-char (match-end 0))
6375 (setq pos1 (match-end 1))
6376 (setq tags (org-get-tags-at))
6377 (setq head (buffer-substring-no-properties
6378 (point)
6379 (progn (skip-chars-forward "^\r\n") (point))))
6380 (if (string-match org-looking-at-done-regexp head)
6381 (setq txt nil)
6382 (setq txt (org-format-agenda-item
6383 (format "Sched.%2dx: " (- 1 diff)) head
6384 category tags))))
6385 (setq txt org-agenda-no-heading-message))
6386 (when txt
6387 (org-add-props txt props
6388 'org-marker (org-agenda-new-marker pos)
6389 'org-hd-marker (org-agenda-new-marker pos1)
6390 'priority (+ (- 5 diff) (org-get-priority txt))
6391 'category category)
6392 (push txt ee)))))
6393 ee))
6395 (defun org-agenda-get-blocks ()
6396 "Return the date-range information for agenda display."
6397 (let* ((props (list 'face nil
6398 'org-not-done-regexp org-not-done-regexp
6399 'mouse-face 'highlight
6400 'keymap org-agenda-keymap
6401 'help-echo
6402 (format "mouse-2 or RET jump to org file %s"
6403 (abbreviate-file-name buffer-file-name))))
6404 (regexp org-tr-regexp)
6405 (d0 (calendar-absolute-from-gregorian date))
6406 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6407 (goto-char (point-min))
6408 (while (re-search-forward regexp nil t)
6409 (setq timestr (match-string 0)
6410 s1 (match-string 1)
6411 s2 (match-string 2)
6412 d1 (time-to-days (org-time-string-to-time s1))
6413 d2 (time-to-days (org-time-string-to-time s2)))
6414 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6415 ;; Only allow days between the limits, because the normal
6416 ;; date stamps will catch the limits.
6417 (save-excursion
6418 (setq marker (org-agenda-new-marker (point)))
6419 (setq category (org-get-category))
6420 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6421 (progn
6422 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6423 (goto-char (match-end 1))
6424 (setq tags (org-get-tags-at))
6425 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6426 (setq txt (org-format-agenda-item
6427 (format (if (= d1 d2) "" "(%d/%d): ")
6428 (1+ (- d0 d1)) (1+ (- d2 d1)))
6429 (match-string 1) category tags
6430 (if (= d0 d1) timestr))))
6431 (setq txt org-agenda-no-heading-message))
6432 (org-add-props txt props
6433 'org-marker marker 'org-hd-marker hdmarker
6434 'priority (org-get-priority txt) 'category category)
6435 (push txt ee)))
6436 (outline-next-heading))
6437 ;; Sort the entries by expiration date.
6438 (nreverse ee)))
6440 (defconst org-plain-time-of-day-regexp
6441 (concat
6442 "\\(\\<[012]?[0-9]"
6443 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6444 "\\(--?"
6445 "\\(\\<[012]?[0-9]"
6446 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6447 "\\)?")
6448 "Regular expression to match a plain time or time range.
6449 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6450 groups carry important information:
6451 0 the full match
6452 1 the first time, range or not
6453 8 the second time, if it is a range.")
6455 (defconst org-stamp-time-of-day-regexp
6456 (concat
6457 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6458 "\\([012][0-9]:[0-5][0-9]\\)>"
6459 "\\(--?"
6460 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6461 "Regular expression to match a timestamp time or time range.
6462 After a match, the following groups carry important information:
6463 0 the full match
6464 1 date plus weekday, for backreferencing to make sure both times on same day
6465 2 the first time, range or not
6466 4 the second time, if it is a range.")
6468 (defvar org-prefix-has-time nil
6469 "A flag, set by `org-compile-prefix-format'.
6470 The flag is set if the currently compiled format contains a `%t'.")
6471 (defvar org-prefix-has-tag nil
6472 "A flag, set by `org-compile-prefix-format'.
6473 The flag is set if the currently compiled format contains a `%T'.")
6475 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6476 "Format TXT to be inserted into the agenda buffer.
6477 In particular, it adds the prefix and corresponding text properties. EXTRA
6478 must be a string and replaces the `%s' specifier in the prefix format.
6479 CATEGORY (string, symbol or nil) may be used to overrule the default
6480 category taken from local variable or file name. It will replace the `%c'
6481 specifier in the format. DOTIME, when non-nil, indicates that a
6482 time-of-day should be extracted from TXT for sorting of this entry, and for
6483 the `%t' specifier in the format. When DOTIME is a string, this string is
6484 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6485 only the correctly processes TXT should be returned - this is used by
6486 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6487 (save-match-data
6488 ;; Diary entries sometimes have extra whitespace at the beginning
6489 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6490 (let* ((category (or category
6491 org-category
6492 (if buffer-file-name
6493 (file-name-sans-extension
6494 (file-name-nondirectory buffer-file-name))
6495 "")))
6496 (tag (if tags (nth (1- (length tags)) tags) ""))
6497 time ;; needed for the eval of the prefix format
6498 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6499 (time-of-day (and dotime (org-get-time-of-day ts)))
6500 stamp plain s0 s1 s2 rtn)
6501 (when (and dotime time-of-day org-prefix-has-time)
6502 ;; Extract starting and ending time and move them to prefix
6503 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6504 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6505 (setq s0 (match-string 0 ts)
6506 s1 (match-string (if plain 1 2) ts)
6507 s2 (match-string (if plain 8 4) ts))
6509 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6510 ;; them, we might want to remove them there to avoid duplication.
6511 ;; The user can turn this off with a variable.
6512 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6513 (string-match (concat (regexp-quote s0) " *") txt)
6514 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6515 (= (match-beginning 0) 0)
6517 (setq txt (replace-match "" nil nil txt))))
6518 ;; Normalize the time(s) to 24 hour
6519 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6520 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6522 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6523 (and org-agenda-remove-tags-when-in-prefix
6524 org-prefix-has-tag))
6525 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6526 (setq txt (replace-match "" t t txt)))
6528 ;; Create the final string
6529 (if noprefix
6530 (setq rtn txt)
6531 ;; Prepare the variables needed in the eval of the compiled format
6532 (setq time (cond (s2 (concat s1 "-" s2))
6533 (s1 (concat s1 "......"))
6534 (t ""))
6535 extra (or extra "")
6536 category (if (symbolp category) (symbol-name category) category))
6537 ;; Evaluate the compiled format
6538 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6540 ;; And finally add the text properties
6541 (org-add-props rtn nil
6542 'category (downcase category) 'tags tags
6543 'prefix-length (- (length rtn) (length txt))
6544 'time-of-day time-of-day
6545 'dotime dotime))))
6547 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6548 (catch 'exit
6549 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6550 ((and todayp (member 'today (car org-agenda-time-grid))))
6551 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6552 ((member 'weekly (car org-agenda-time-grid)))
6553 (t (throw 'exit list)))
6554 (let* ((have (delq nil (mapcar
6555 (lambda (x) (get-text-property 1 'time-of-day x))
6556 list)))
6557 (string (nth 1 org-agenda-time-grid))
6558 (gridtimes (nth 2 org-agenda-time-grid))
6559 (req (car org-agenda-time-grid))
6560 (remove (member 'remove-match req))
6561 new time)
6562 (if (and (member 'require-timed req) (not have))
6563 ;; don't show empty grid
6564 (throw 'exit list))
6565 (while (setq time (pop gridtimes))
6566 (unless (and remove (member time have))
6567 (setq time (int-to-string time))
6568 (push (org-format-agenda-item
6569 nil string "" nil
6570 (concat (substring time 0 -2) ":" (substring time -2)))
6571 new)
6572 (put-text-property
6573 1 (length (car new)) 'face 'org-time-grid (car new))))
6574 (if (member 'time-up org-agenda-sorting-strategy)
6575 (append new list)
6576 (append list new)))))
6578 (defun org-compile-prefix-format (format)
6579 "Compile the prefix format into a Lisp form that can be evaluated.
6580 The resulting form is returned and stored in the variable
6581 `org-prefix-format-compiled'."
6582 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6583 (let ((start 0) varform vars var (s format)e c f opt)
6584 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6585 s start)
6586 (setq var (cdr (assoc (match-string 4 s)
6587 '(("c" . category) ("t" . time) ("s" . extra)
6588 ("T" . tag))))
6589 c (or (match-string 3 s) "")
6590 opt (match-beginning 1)
6591 start (1+ (match-beginning 0)))
6592 (if (equal var 'time) (setq org-prefix-has-time t))
6593 (if (equal var 'tag) (setq org-prefix-has-tag t))
6594 (setq f (concat "%" (match-string 2 s) "s"))
6595 (if opt
6596 (setq varform
6597 `(if (equal "" ,var)
6599 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6600 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6601 (setq s (replace-match "%s" t nil s))
6602 (push varform vars))
6603 (setq vars (nreverse vars))
6604 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6606 (defun org-get-time-of-day (s &optional string)
6607 "Check string S for a time of day.
6608 If found, return it as a military time number between 0 and 2400.
6609 If not found, return nil.
6610 The optional STRING argument forces conversion into a 5 character wide string
6611 HH:MM."
6612 (save-match-data
6613 (when
6615 (string-match
6616 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6617 (string-match
6618 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6619 (let* ((t0 (+ (* 100
6620 (+ (string-to-number (match-string 1 s))
6621 (if (and (match-beginning 4)
6622 (equal (downcase (match-string 4 s)) "pm"))
6623 12 0)))
6624 (if (match-beginning 3)
6625 (string-to-number (match-string 3 s))
6626 0)))
6627 (t1 (concat " "
6628 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6629 (int-to-string t0))))
6630 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6632 (defun org-finalize-agenda-entries (list)
6633 "Sort and concatenate the agenda items."
6634 (setq list (mapcar 'org-agenda-highlight-todo list))
6635 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6637 (defun org-agenda-highlight-todo (x)
6638 (let (re)
6639 (if (eq x 'line)
6640 (save-excursion
6641 (beginning-of-line 1)
6642 (setq re (get-text-property (point) 'org-not-done-regexp))
6643 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6644 (and (looking-at (concat "[ \t]*" re))
6645 (add-text-properties (match-beginning 0) (match-end 0)
6646 '(face org-todo))))
6647 (setq re (get-text-property 0 'org-not-done-regexp x))
6648 (and re (string-match re x)
6649 (add-text-properties (match-beginning 0) (match-end 0)
6650 '(face org-todo) x))
6651 x)))
6653 (defsubst org-cmp-priority (a b)
6654 "Compare the priorities of string A and B."
6655 (let ((pa (or (get-text-property 1 'priority a) 0))
6656 (pb (or (get-text-property 1 'priority b) 0)))
6657 (cond ((> pa pb) +1)
6658 ((< pa pb) -1)
6659 (t nil))))
6661 (defsubst org-cmp-category (a b)
6662 "Compare the string values of categories of strings A and B."
6663 (let ((ca (or (get-text-property 1 'category a) ""))
6664 (cb (or (get-text-property 1 'category b) "")))
6665 (cond ((string-lessp ca cb) -1)
6666 ((string-lessp cb ca) +1)
6667 (t nil))))
6669 (defsubst org-cmp-time (a b)
6670 "Compare the time-of-day values of strings A and B."
6671 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6672 (ta (or (get-text-property 1 'time-of-day a) def))
6673 (tb (or (get-text-property 1 'time-of-day b) def)))
6674 (cond ((< ta tb) -1)
6675 ((< tb ta) +1)
6676 (t nil))))
6678 (defun org-entries-lessp (a b)
6679 "Predicate for sorting agenda entries."
6680 ;; The following variables will be used when the form is evaluated.
6681 (let* ((time-up (org-cmp-time a b))
6682 (time-down (if time-up (- time-up) nil))
6683 (priority-up (org-cmp-priority a b))
6684 (priority-down (if priority-up (- priority-up) nil))
6685 (category-up (org-cmp-category a b))
6686 (category-down (if category-up (- category-up) nil))
6687 (category-keep (if category-up +1 nil)))
6688 (cdr (assoc
6689 (eval (cons 'or org-agenda-sorting-strategy))
6690 '((-1 . t) (1 . nil) (nil . nil))))))
6692 (defun org-agenda-show-priority ()
6693 "Show the priority of the current item.
6694 This priority is composed of the main priority given with the [#A] cookies,
6695 and by additional input from the age of a schedules or deadline entry."
6696 (interactive)
6697 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6698 (message "Priority is %d" (if pri pri -1000))))
6700 (defun org-agenda-show-tags ()
6701 "Show the tags applicable to the current item."
6702 (interactive)
6703 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6704 (if tags
6705 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6706 (message "No tags associated with this line"))))
6708 (defun org-agenda-goto (&optional highlight)
6709 "Go to the Org-mode file which contains the item at point."
6710 (interactive)
6711 (let* ((marker (or (get-text-property (point) 'org-marker)
6712 (org-agenda-error)))
6713 (buffer (marker-buffer marker))
6714 (pos (marker-position marker)))
6715 (switch-to-buffer-other-window buffer)
6716 (widen)
6717 (goto-char pos)
6718 (when (eq major-mode 'org-mode)
6719 (org-show-hidden-entry)
6720 (save-excursion
6721 (and (outline-next-heading)
6722 (org-flag-heading nil)))) ; show the next heading
6723 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6725 (defun org-agenda-switch-to ()
6726 "Go to the Org-mode file which contains the item at point."
6727 (interactive)
6728 (let* ((marker (or (get-text-property (point) 'org-marker)
6729 (org-agenda-error)))
6730 (buffer (marker-buffer marker))
6731 (pos (marker-position marker)))
6732 (switch-to-buffer buffer)
6733 (delete-other-windows)
6734 (widen)
6735 (goto-char pos)
6736 (when (eq major-mode 'org-mode)
6737 (org-show-hidden-entry)
6738 (save-excursion
6739 (and (outline-next-heading)
6740 (org-flag-heading nil)))))) ; show the next heading
6742 (defun org-agenda-goto-mouse (ev)
6743 "Go to the Org-mode file which contains the item at the mouse click."
6744 (interactive "e")
6745 (mouse-set-point ev)
6746 (org-agenda-goto))
6748 (defun org-agenda-show ()
6749 "Display the Org-mode file which contains the item at point."
6750 (interactive)
6751 (let ((win (selected-window)))
6752 (org-agenda-goto t)
6753 (select-window win)))
6755 (defun org-agenda-recenter (arg)
6756 "Display the Org-mode file which contains the item at point and recenter."
6757 (interactive "P")
6758 (let ((win (selected-window)))
6759 (org-agenda-goto t)
6760 (recenter arg)
6761 (select-window win)))
6763 (defun org-agenda-show-mouse (ev)
6764 "Display the Org-mode file which contains the item at the mouse click."
6765 (interactive "e")
6766 (mouse-set-point ev)
6767 (org-agenda-show))
6769 (defun org-agenda-check-no-diary ()
6770 "Check if the entry is a diary link and abort if yes."
6771 (if (get-text-property (point) 'org-agenda-diary-link)
6772 (org-agenda-error)))
6774 (defun org-agenda-error ()
6775 (error "Command not allowed in this line"))
6777 (defvar org-last-heading-marker (make-marker)
6778 "Marker pointing to the headline that last changed its TODO state
6779 by a remote command from the agenda.")
6781 (defun org-agenda-todo (&optional arg)
6782 "Cycle TODO state of line at point, also in Org-mode file.
6783 This changes the line at point, all other lines in the agenda referring to
6784 the same tree node, and the headline of the tree node in the Org-mode file."
6785 (interactive "P")
6786 (org-agenda-check-no-diary)
6787 (let* ((col (current-column))
6788 (marker (or (get-text-property (point) 'org-marker)
6789 (org-agenda-error)))
6790 (buffer (marker-buffer marker))
6791 (pos (marker-position marker))
6792 (hdmarker (get-text-property (point) 'org-hd-marker))
6793 (buffer-read-only nil)
6794 newhead)
6795 (with-current-buffer buffer
6796 (widen)
6797 (goto-char pos)
6798 (org-show-hidden-entry)
6799 (save-excursion
6800 (and (outline-next-heading)
6801 (org-flag-heading nil))) ; show the next heading
6802 (org-todo arg)
6803 (and (bolp) (forward-char 1))
6804 (setq newhead (org-get-heading))
6805 (save-excursion
6806 (org-back-to-heading)
6807 (move-marker org-last-heading-marker (point))))
6808 (beginning-of-line 1)
6809 (save-excursion
6810 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6811 (move-to-column col)))
6813 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6814 "Change all lines in the agenda buffer which match HDMARKER.
6815 The new content of the line will be NEWHEAD (as modified by
6816 `org-format-agenda-item'). HDMARKER is checked with
6817 `equal' against all `org-hd-marker' text properties in the file.
6818 If FIXFACE is non-nil, the face of each item is modified acording to
6819 the new TODO state."
6820 (let* (props m pl undone-face done-face finish new dotime cat tags)
6821 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6822 (save-excursion
6823 (goto-char (point-max))
6824 (beginning-of-line 1)
6825 (while (not finish)
6826 (setq finish (bobp))
6827 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6828 (equal m hdmarker))
6829 (setq props (text-properties-at (point))
6830 dotime (get-text-property (point) 'dotime)
6831 cat (get-text-property (point) 'category)
6832 tags (get-text-property (point) 'tags)
6833 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6834 pl (get-text-property (point) 'prefix-length)
6835 undone-face (get-text-property (point) 'undone-face)
6836 done-face (get-text-property (point) 'done-face))
6837 (move-to-column pl)
6838 (if (looking-at ".*")
6839 (progn
6840 (replace-match new t t)
6841 (beginning-of-line 1)
6842 (add-text-properties (point-at-bol) (point-at-eol) props)
6843 (when fixface
6844 (add-text-properties
6845 (point-at-bol) (point-at-eol)
6846 (list 'face
6847 (if org-last-todo-state-is-todo
6848 undone-face done-face)))
6849 (org-agenda-highlight-todo 'line))
6850 (beginning-of-line 1))
6851 (error "Line update did not work")))
6852 (beginning-of-line 0)))))
6854 (defun org-agenda-priority-up ()
6855 "Increase the priority of line at point, also in Org-mode file."
6856 (interactive)
6857 (org-agenda-priority 'up))
6859 (defun org-agenda-priority-down ()
6860 "Decrease the priority of line at point, also in Org-mode file."
6861 (interactive)
6862 (org-agenda-priority 'down))
6864 (defun org-agenda-priority (&optional force-direction)
6865 "Set the priority of line at point, also in Org-mode file.
6866 This changes the line at point, all other lines in the agenda referring to
6867 the same tree node, and the headline of the tree node in the Org-mode file."
6868 (interactive)
6869 (org-agenda-check-no-diary)
6870 (let* ((marker (or (get-text-property (point) 'org-marker)
6871 (org-agenda-error)))
6872 (buffer (marker-buffer marker))
6873 (pos (marker-position marker))
6874 (hdmarker (get-text-property (point) 'org-hd-marker))
6875 (buffer-read-only nil)
6876 newhead)
6877 (with-current-buffer buffer
6878 (widen)
6879 (goto-char pos)
6880 (org-show-hidden-entry)
6881 (save-excursion
6882 (and (outline-next-heading)
6883 (org-flag-heading nil))) ; show the next heading
6884 (funcall 'org-priority force-direction)
6885 (end-of-line 1)
6886 (setq newhead (org-get-heading)))
6887 (org-agenda-change-all-lines newhead hdmarker)
6888 (beginning-of-line 1)))
6890 (defun org-get-tags-at (&optional pos)
6891 "Get a list of all headline targs applicable at POS.
6892 POS defaults to point. If tags are inherited, the list contains
6893 the targets in the same sequence as the headlines appear, i.e.
6894 the tags of the current headline come last."
6895 (interactive)
6896 (let (tags)
6897 (save-excursion
6898 (goto-char (or pos (point)))
6899 (save-match-data
6900 (org-back-to-heading t)
6901 (condition-case nil
6902 (while t
6903 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6904 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6905 (or org-use-tag-inheritance (error ""))
6906 (org-up-heading-all 1))
6907 (error nil))))
6908 (message "%s" tags)
6909 tags))
6911 (defun org-agenda-set-tags ()
6912 "Set tags for the current headline."
6913 (interactive)
6914 (org-agenda-check-no-diary)
6915 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6916 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6917 (org-agenda-error)))
6918 (buffer (marker-buffer hdmarker))
6919 (pos (marker-position hdmarker))
6920 (buffer-read-only nil)
6921 newhead)
6922 (with-current-buffer buffer
6923 (widen)
6924 (goto-char pos)
6925 (org-show-hidden-entry)
6926 (save-excursion
6927 (and (outline-next-heading)
6928 (org-flag-heading nil))) ; show the next heading
6929 (call-interactively 'org-set-tags)
6930 (end-of-line 1)
6931 (setq newhead (org-get-heading)))
6932 (org-agenda-change-all-lines newhead hdmarker)
6933 (beginning-of-line 1)))
6935 (defun org-agenda-date-later (arg &optional what)
6936 "Change the date of this item to one day later."
6937 (interactive "p")
6938 (org-agenda-check-type t 'agenda 'timeline)
6939 (org-agenda-check-no-diary)
6940 (let* ((marker (or (get-text-property (point) 'org-marker)
6941 (org-agenda-error)))
6942 (buffer (marker-buffer marker))
6943 (pos (marker-position marker)))
6944 (with-current-buffer buffer
6945 (widen)
6946 (goto-char pos)
6947 (if (not (org-at-timestamp-p))
6948 (error "Cannot find time stamp"))
6949 (org-timestamp-change arg (or what 'day))
6950 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6952 (defun org-agenda-date-earlier (arg &optional what)
6953 "Change the date of this item to one day earlier."
6954 (interactive "p")
6955 (org-agenda-date-later (- arg) what))
6957 (defun org-agenda-date-prompt (arg)
6958 "Change the date of this item. Date is prompted for, with default today.
6959 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6960 be used to request time specification in the time stamp."
6961 (interactive "P")
6962 (org-agenda-check-type t 'agenda 'timeline)
6963 (org-agenda-check-no-diary)
6964 (let* ((marker (or (get-text-property (point) 'org-marker)
6965 (org-agenda-error)))
6966 (buffer (marker-buffer marker))
6967 (pos (marker-position marker)))
6968 (with-current-buffer buffer
6969 (widen)
6970 (goto-char pos)
6971 (if (not (org-at-timestamp-p))
6972 (error "Cannot find time stamp"))
6973 (org-time-stamp arg)
6974 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6976 (defun org-agenda-schedule (arg)
6977 "Schedule the item at point."
6978 (interactive "P")
6979 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
6980 (org-agenda-check-no-diary)
6981 (let* ((marker (or (get-text-property (point) 'org-marker)
6982 (org-agenda-error)))
6983 (buffer (marker-buffer marker))
6984 (pos (marker-position marker))
6986 (with-current-buffer buffer
6987 (widen)
6988 (goto-char pos)
6989 (setq ts (org-schedule))
6990 (message "Item scheduled for %s" ts))))
6992 (defun org-agenda-deadline (arg)
6993 "Schedule the item at point."
6994 (interactive "P")
6995 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
6996 (org-agenda-check-no-diary)
6997 (let* ((marker (or (get-text-property (point) 'org-marker)
6998 (org-agenda-error)))
6999 (buffer (marker-buffer marker))
7000 (pos (marker-position marker))
7002 (with-current-buffer buffer
7003 (widen)
7004 (goto-char pos)
7005 (setq ts (org-deadline))
7006 (message "Deadline for this item set to %s" ts))))
7008 (defun org-get-heading ()
7009 "Return the heading of the current entry, without the stars."
7010 (save-excursion
7011 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
7012 (if (and (re-search-backward "[\r\n]\\*" nil t)
7013 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
7014 (match-string 1)
7015 "")))
7017 (defun org-agenda-diary-entry ()
7018 "Make a diary entry, like the `i' command from the calendar.
7019 All the standard commands work: block, weekly etc."
7020 (interactive)
7021 (org-agenda-check-type t 'agenda 'timeline)
7022 (require 'diary-lib)
7023 (let* ((char (progn
7024 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
7025 (read-char-exclusive)))
7026 (cmd (cdr (assoc char
7027 '((?d . insert-diary-entry)
7028 (?w . insert-weekly-diary-entry)
7029 (?m . insert-monthly-diary-entry)
7030 (?y . insert-yearly-diary-entry)
7031 (?a . insert-anniversary-diary-entry)
7032 (?b . insert-block-diary-entry)
7033 (?c . insert-cyclic-diary-entry)))))
7034 (oldf (symbol-function 'calendar-cursor-to-date))
7035 (point (point))
7036 (mark (or (mark t) (point))))
7037 (unless cmd
7038 (error "No command associated with <%c>" char))
7039 (unless (and (get-text-property point 'day)
7040 (or (not (equal ?b char))
7041 (get-text-property mark 'day)))
7042 (error "Don't know which date to use for diary entry"))
7043 ;; We implement this by hacking the `calendar-cursor-to-date' function
7044 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
7045 (let ((calendar-mark-ring
7046 (list (calendar-gregorian-from-absolute
7047 (or (get-text-property mark 'day)
7048 (get-text-property point 'day))))))
7049 (unwind-protect
7050 (progn
7051 (fset 'calendar-cursor-to-date
7052 (lambda (&optional error)
7053 (calendar-gregorian-from-absolute
7054 (get-text-property point 'day))))
7055 (call-interactively cmd))
7056 (fset 'calendar-cursor-to-date oldf)))))
7059 (defun org-agenda-execute-calendar-command (cmd)
7060 "Execute a calendar command from the agenda, with the date associated to
7061 the cursor position."
7062 (org-agenda-check-type t 'agenda 'timeline)
7063 (require 'diary-lib)
7064 (unless (get-text-property (point) 'day)
7065 (error "Don't know which date to use for calendar command"))
7066 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
7067 (point (point))
7068 (date (calendar-gregorian-from-absolute
7069 (get-text-property point 'day)))
7070 (displayed-day (extract-calendar-day date))
7071 (displayed-month (extract-calendar-month date))
7072 (displayed-year (extract-calendar-year date)))
7073 (unwind-protect
7074 (progn
7075 (fset 'calendar-cursor-to-date
7076 (lambda (&optional error)
7077 (calendar-gregorian-from-absolute
7078 (get-text-property point 'day))))
7079 (call-interactively cmd))
7080 (fset 'calendar-cursor-to-date oldf))))
7082 (defun org-agenda-phases-of-moon ()
7083 "Display the phases of the moon for the 3 months around the cursor date."
7084 (interactive)
7085 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
7087 (defun org-agenda-holidays ()
7088 "Display the holidays for the 3 months around the cursor date."
7089 (interactive)
7090 (org-agenda-execute-calendar-command 'list-calendar-holidays))
7092 (defun org-agenda-sunrise-sunset (arg)
7093 "Display sunrise and sunset for the cursor date.
7094 Latitude and longitude can be specified with the variables
7095 `calendar-latitude' and `calendar-longitude'. When called with prefix
7096 argument, latitude and longitude will be prompted for."
7097 (interactive "P")
7098 (let ((calendar-longitude (if arg nil calendar-longitude))
7099 (calendar-latitude (if arg nil calendar-latitude))
7100 (calendar-location-name
7101 (if arg "the given coordinates" calendar-location-name)))
7102 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
7104 (defun org-agenda-goto-calendar ()
7105 "Open the Emacs calendar with the date at the cursor."
7106 (interactive)
7107 (org-agenda-check-type t 'agenda 'timeline)
7108 (let* ((day (or (get-text-property (point) 'day)
7109 (error "Don't know which date to open in calendar")))
7110 (date (calendar-gregorian-from-absolute day))
7111 (calendar-move-hook nil)
7112 (view-calendar-holidays-initially nil)
7113 (view-diary-entries-initially nil))
7114 (calendar)
7115 (calendar-goto-date date)))
7117 (defun org-calendar-goto-agenda ()
7118 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
7119 This is a command that has to be installed in `calendar-mode-map'."
7120 (interactive)
7121 (org-agenda-list nil (calendar-absolute-from-gregorian
7122 (calendar-cursor-to-date))
7123 nil t))
7125 (defun org-agenda-convert-date ()
7126 (interactive)
7127 (org-agenda-check-type t 'agenda 'timeline)
7128 (let ((day (get-text-property (point) 'day))
7129 date s)
7130 (unless day
7131 (error "Don't know which date to convert"))
7132 (setq date (calendar-gregorian-from-absolute day))
7133 (setq s (concat
7134 "Gregorian: " (calendar-date-string date) "\n"
7135 "ISO: " (calendar-iso-date-string date) "\n"
7136 "Day of Yr: " (calendar-day-of-year-string date) "\n"
7137 "Julian: " (calendar-julian-date-string date) "\n"
7138 "Astron. JD: " (calendar-astro-date-string date)
7139 " (Julian date number at noon UTC)\n"
7140 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
7141 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
7142 "French: " (calendar-french-date-string date) "\n"
7143 "Mayan: " (calendar-mayan-date-string date) "\n"
7144 "Coptic: " (calendar-coptic-date-string date) "\n"
7145 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
7146 "Persian: " (calendar-persian-date-string date) "\n"
7147 "Chinese: " (calendar-chinese-date-string date) "\n"))
7148 (with-output-to-temp-buffer "*Dates*"
7149 (princ s))
7150 (if (fboundp 'fit-window-to-buffer)
7151 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
7153 ;;; Tags
7155 (defun org-scan-tags (action matcher &optional todo-only)
7156 "Scan headline tags with inheritance and produce output ACTION.
7157 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
7158 evaluated, testing if a given set of tags qualifies a headline for
7159 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
7160 are included in the output."
7161 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
7162 (mapconcat 'regexp-quote
7163 (nreverse (cdr (reverse org-todo-keywords)))
7164 "\\|")
7165 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
7166 (props (list 'face nil
7167 'done-face 'org-done
7168 'undone-face nil
7169 'mouse-face 'highlight
7170 'keymap org-agenda-keymap
7171 'help-echo
7172 (format "mouse-2 or RET jump to org file %s"
7173 (abbreviate-file-name buffer-file-name))))
7174 lspos
7175 tags tags-list tags-alist (llast 0) rtn level category i txt
7176 todo marker)
7178 (save-excursion
7179 (goto-char (point-min))
7180 (when (eq action 'sparse-tree) (hide-sublevels 1))
7181 (while (re-search-forward re nil t)
7182 (setq todo (if (match-end 1) (match-string 2))
7183 tags (if (match-end 4) (match-string 4)))
7184 (goto-char (setq lspos (1+ (match-beginning 0))))
7185 (setq level (funcall outline-level)
7186 category (org-get-category))
7187 (setq i llast llast level)
7188 ;; remove tag lists from same and sublevels
7189 (while (>= i level)
7190 (when (setq entry (assoc i tags-alist))
7191 (setq tags-alist (delete entry tags-alist)))
7192 (setq i (1- i)))
7193 ;; add the nex tags
7194 (when tags
7195 (setq tags (mapcar 'downcase (org-split-string tags ":"))
7196 tags-alist
7197 (cons (cons level tags) tags-alist)))
7198 ;; compile tags for current headline
7199 (setq tags-list
7200 (if org-use-tag-inheritance
7201 (apply 'append (mapcar 'cdr tags-alist))
7202 tags))
7203 (when (and (or (not todo-only) todo)
7204 (eval matcher))
7205 ;; list this headline
7206 (if (eq action 'sparse-tree)
7207 (progn
7208 (org-show-hierarchy-above))
7209 (setq txt (org-format-agenda-item
7211 (concat
7212 (if org-tags-match-list-sublevels
7213 (make-string (1- level) ?.) "")
7214 (org-get-heading))
7215 category tags-list))
7216 (goto-char lspos)
7217 (setq marker (org-agenda-new-marker))
7218 (org-add-props txt props
7219 'org-marker marker 'org-hd-marker marker 'category category)
7220 (push txt rtn))
7221 ;; if we are to skip sublevels, jump to end of subtree
7222 (point)
7223 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7224 (nreverse rtn)))
7226 (defun org-tags-sparse-tree (&optional arg match)
7227 "Create a sparse tree according to tags search string MATCH.
7228 MATCH can contain positive and negative selection of tags, like
7229 \"+WORK+URGENT-WITHBOSS\"."
7230 (interactive "P")
7231 (let ((org-show-following-heading nil)
7232 (org-show-hierarchy-above nil))
7233 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7235 (defun org-make-tags-matcher (match)
7236 "Create the TAGS matcher form for the tags-selecting string MATCH."
7237 (unless match
7238 ;; Get a new match request, with completion
7239 (setq org-last-tags-completion-table
7240 (or (org-get-buffer-tags)
7241 org-last-tags-completion-table))
7242 (setq match (completing-read
7243 "Tags: " 'org-tags-completion-function nil nil nil
7244 'org-tags-history)))
7245 ;; parse the string and create a lisp form
7246 (let ((match0 match) minus tag mm matcher orterms term orlist)
7247 (setq orterms (org-split-string match "|"))
7248 (while (setq term (pop orterms))
7249 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7250 (setq minus (and (match-end 1)
7251 (equal (match-string 1 term) "-"))
7252 tag (match-string 2 term)
7253 term (substring term (match-end 0))
7254 mm (list 'member (downcase tag) 'tags-list)
7255 mm (if minus (list 'not mm) mm))
7256 (push mm matcher))
7257 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7258 orlist)
7259 (setq matcher nil))
7260 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7261 ;; Return the string and lisp forms of the matcher
7262 (cons match0 matcher)))
7264 ;;;###autoload
7265 (defun org-tags-view (&optional todo-only match keep-modes)
7266 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7267 The prefix arg TODO-ONLY limits the search to TODO entries."
7268 (interactive "P")
7269 (org-agenda-maybe-reset-markers 'force)
7270 (org-compile-prefix-format org-agenda-prefix-format)
7271 (let* ((org-agenda-keep-modes keep-modes)
7272 (org-tags-match-list-sublevels
7273 (if todo-only t org-tags-match-list-sublevels))
7274 (win (selected-window))
7275 (completion-ignore-case t)
7276 rtn rtnall files file pos matcher
7277 buffer)
7278 (setq matcher (org-make-tags-matcher match)
7279 match (car matcher) matcher (cdr matcher))
7280 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7281 (progn
7282 (delete-other-windows)
7283 (switch-to-buffer-other-window
7284 (get-buffer-create org-agenda-buffer-name))))
7285 (setq buffer-read-only nil)
7286 (erase-buffer)
7287 (org-agenda-mode) (setq buffer-read-only nil)
7288 (set (make-local-variable 'org-agenda-type) 'tags)
7289 (set (make-local-variable 'org-agenda-redo-command)
7290 (list 'org-tags-view (list 'quote todo-only)
7291 (list 'if 'current-prefix-arg nil match) t))
7292 (setq files (org-agenda-files)
7293 rtnall nil)
7294 (while (setq file (pop files))
7295 (catch 'nextfile
7296 (org-check-agenda-file file)
7297 (setq buffer (if (file-exists-p file)
7298 (org-get-agenda-file-buffer file)
7299 (error "No such file %s" file)))
7300 (if (not buffer)
7301 ;; If file does not exist, merror message to agenda
7302 (setq rtn (list
7303 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7304 rtnall (append rtnall rtn))
7305 (with-current-buffer buffer
7306 (unless (eq major-mode 'org-mode)
7307 (error "Agenda file %s is not in `org-mode'" file))
7308 (save-excursion
7309 (save-restriction
7310 (if org-respect-restriction
7311 (if (org-region-active-p)
7312 ;; Respect a region to restrict search
7313 (narrow-to-region (region-beginning) (region-end)))
7314 ;; If we work for the calendar or many files,
7315 ;; get rid of any restriction
7316 (widen))
7317 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7318 (setq rtnall (append rtnall rtn))))))))
7319 (insert "Headlines with TAGS match: ")
7320 (add-text-properties (point-min) (1- (point))
7321 (list 'face 'org-level-3))
7322 (setq pos (point))
7323 (insert match "\n")
7324 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7325 (setq pos (point))
7326 (insert "Press `C-u r' to search again with new search string\n")
7327 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7328 (when rtnall
7329 (insert (mapconcat 'identity rtnall "\n")))
7330 (goto-char (point-min))
7331 (setq buffer-read-only t)
7332 (org-fit-agenda-window)
7333 (if (not org-select-agenda-window) (select-window win))))
7335 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7336 (defun org-set-tags (&optional arg just-align)
7337 "Set the tags for the current headline.
7338 With prefix ARG, realign all tags in headings in the current buffer."
7339 (interactive)
7340 (let* (;(inherit (org-get-inherited-tags))
7341 (re (concat "^" outline-regexp))
7342 (col (current-column))
7343 (current (org-get-tags))
7344 tags hd empty invis)
7345 (if arg
7346 (save-excursion
7347 (goto-char (point-min))
7348 (while (re-search-forward re nil t)
7349 (org-set-tags nil t))
7350 (message "All tags realigned to column %d" org-tags-column))
7351 (if just-align
7352 (setq tags current)
7353 (setq org-last-tags-completion-table
7354 (or (org-get-buffer-tags)
7355 org-last-tags-completion-table))
7356 (setq tags
7357 (let ((org-add-colon-after-tag-completion t))
7358 (completing-read "Tags: " 'org-tags-completion-function
7359 nil nil current 'org-tags-history)))
7360 (while (string-match "[-+&]+" tags)
7361 (setq tags (replace-match ":" t t tags))))
7362 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7363 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7364 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7365 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7366 (if (equal current "")
7367 (progn
7368 (end-of-line 1)
7369 (or empty (insert-before-markers " ")))
7370 (beginning-of-line 1)
7371 (setq invis (org-invisible-p))
7372 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7373 (setq hd (match-string 1))
7374 (delete-region (match-beginning 0) (match-end 0))
7375 (insert-before-markers (org-trim hd) (if empty "" " ")))
7376 (unless (equal tags "")
7377 (move-to-column (max (current-column)
7378 (if (> org-tags-column 0)
7379 org-tags-column
7380 (- (- org-tags-column) (length tags))))
7382 (insert-before-markers tags)
7383 (if (and (not invis) (org-invisible-p))
7384 (outline-flag-region (point-at-bol) (point) nil)))
7385 (move-to-column col))))
7387 (defun org-tags-completion-function (string predicate &optional flag)
7388 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7389 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7390 (setq s1 (match-string 1 string)
7391 s2 (match-string 2 string))
7392 (setq s1 "" s2 string))
7393 (cond
7394 ((eq flag nil)
7395 ;; try completion
7396 (setq rtn (try-completion s2 ctable))
7397 (if (stringp rtn)
7398 (concat s1 s2 (substring rtn (length s2))
7399 (if (and org-add-colon-after-tag-completion
7400 (assoc rtn ctable))
7401 ":" "")))
7403 ((eq flag t)
7404 ;; all-completions
7405 (all-completions s2 ctable)
7407 ((eq flag 'lambda)
7408 ;; exact match?
7409 (assoc s2 ctable)))
7412 (defun org-get-tags ()
7413 "Get the TAGS string in the current headline."
7414 (unless (org-on-heading-p)
7415 (error "Not on a heading"))
7416 (save-excursion
7417 (beginning-of-line 1)
7418 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7419 (org-match-string-no-properties 1)
7420 "")))
7422 (defun org-get-buffer-tags ()
7423 "Get a table of all tags used in the buffer, for completion."
7424 (let (tags)
7425 (save-excursion
7426 (goto-char (point-min))
7427 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7428 (mapc (lambda (x) (add-to-list 'tags x))
7429 (org-split-string (org-match-string-no-properties 1) ":"))))
7430 (mapcar 'list tags)))
7432 ;;; Link Stuff
7434 (defvar org-create-file-search-functions nil
7435 "List of functions to construct the right search string for a file link.
7436 These functions are called in turn with point at the location to
7437 which the link should point.
7439 A function in the hook should first test if it would like to
7440 handle this file type, for example by checking the major-mode or
7441 the file extension. If it decides not to handle this file, it
7442 should just return nil to give other functions a chance. If it
7443 does handle the file, it must return the search string to be used
7444 when following the link. The search string will be part of the
7445 file link, given after a double colon, and `org-open-at-point'
7446 will automatically search for it. If special measures must be
7447 taken to make the search successful, another function should be
7448 added to the companion hook `org-execute-file-search-functions',
7449 which see.
7451 A function in this hook may also use `setq' to set the variable
7452 `description' to provide a suggestion for the descriptive text to
7453 be used for this link when it gets inserted into an Org-mode
7454 buffer with \\[org-insert-link].")
7456 (defvar org-execute-file-search-functions nil
7457 "List of functions to execute a file search triggered by a link.
7459 Functions added to this hook must accept a single argument, the
7460 search string that was part of the file link, the part after the
7461 double colon. The function must first check if it would like to
7462 handle this search, for example by checking the major-mode or the
7463 file extension. If it decides not to handle this search, it
7464 should just return nil to give other functions a chance. If it
7465 does handle the search, it must return a non-nil value to keep
7466 other functions from trying.
7468 Each function can access the current prefix argument through the
7469 variable `current-prefix-argument'. Note that a single prefix is
7470 used to force opening a link in Emacs, so it may be good to only
7471 use a numeric or double prefix to guide the search function.
7473 In case this is needed, a function in this hook can also restore
7474 the window configuration before `org-open-at-point' was called using:
7476 (set-window-configuration org-window-config-before-follow-link)")
7478 (defun org-find-file-at-mouse (ev)
7479 "Open file link or URL at mouse."
7480 (interactive "e")
7481 (mouse-set-point ev)
7482 (org-open-at-point 'in-emacs))
7484 (defun org-open-at-mouse (ev)
7485 "Open file link or URL at mouse."
7486 (interactive "e")
7487 (mouse-set-point ev)
7488 (org-open-at-point))
7490 (defvar org-window-config-before-follow-link nil
7491 "The window configuration before following a link.
7492 This is saved in case the need arises to restore it.")
7494 (defun org-open-at-point (&optional in-emacs)
7495 "Open link at or after point.
7496 If there is no link at point, this function will search forward up to
7497 the end of the current subtree.
7498 Normally, files will be opened by an appropriate application. If the
7499 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7500 (interactive "P")
7501 (setq org-window-config-before-follow-link (current-window-configuration))
7502 (org-remove-occur-highlights nil nil t)
7503 (if (org-at-timestamp-p)
7504 (org-agenda-list nil (time-to-days (org-time-string-to-time
7505 (substring (match-string 1) 0 10)))
7507 (let (type path link line search (pos (point)))
7508 (catch 'match
7509 (save-excursion
7510 (skip-chars-forward "^]\n\r")
7511 (when (and (re-search-backward "\\[\\[" nil t)
7512 (looking-at org-bracket-link-regexp)
7513 (<= (match-beginning 0) pos)
7514 (>= (match-end 0) pos))
7515 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7516 (while (string-match " *\n *" link)
7517 (setq link (replace-match " " t t link)))
7518 (if (string-match org-link-re-with-space2 link)
7519 (setq type (match-string 1 link)
7520 path (match-string 2 link))
7521 (setq type "thisfile"
7522 path link))
7523 (throw 'match t)))
7525 (when (get-text-property (point) 'org-linked-text)
7526 (setq type "thisfile"
7527 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7528 (1+ (point)) (point))
7529 path (buffer-substring
7530 (previous-single-property-change pos 'org-linked-text)
7531 (next-single-property-change pos 'org-linked-text)))
7532 (throw 'match t))
7534 (save-excursion
7535 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7536 (if (equal (char-before) ?<) (backward-char 1))
7537 (when (or (looking-at org-angle-link-re)
7538 (looking-at org-plain-link-re)
7539 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7540 (re-search-forward org-plain-link-re (point-at-eol) t))
7541 (<= (match-beginning 0) pos)
7542 (>= (match-end 0) pos)))
7543 (setq type (match-string 1)
7544 path (match-string 2))
7545 (throw 'match t)))
7546 (save-excursion
7547 (skip-chars-backward "^ \t\n\r")
7548 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7549 (setq type "tags"
7550 path (match-string 1))
7551 (while (string-match ":" path)
7552 (setq path (replace-match "+" t t path)))
7553 (throw 'match t)))
7554 (save-excursion
7555 (skip-chars-backward "a-zA-Z_")
7556 (when (and (memq 'camel org-activate-links)
7557 (looking-at org-camel-regexp))
7558 (setq type "camel" path (match-string 0))
7559 (if (equal (char-before) ?*)
7560 (setq path (concat "*" path))))
7561 (throw 'match t)))
7562 (unless path
7563 (error "No link found"))
7564 ;; Remove any trailing spaces in path
7565 (if (string-match " +\\'" path)
7566 (setq path (replace-match "" t t path)))
7568 (cond
7570 ((member type '("http" "https" "ftp" "mailto" "news"))
7571 (browse-url (concat type ":" path)))
7573 ((string= type "tags")
7574 (org-tags-view in-emacs path))
7575 ((or (string= type "camel")
7576 (string= type "thisfile"))
7577 (org-mark-ring-push)
7578 (org-link-search
7579 path
7580 (cond ((equal in-emacs '(4)) 'occur)
7581 ((equal in-emacs '(16)) 'org-occur)
7582 (t nil))))
7584 ((string= type "file")
7585 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7586 ;; FIXME: It is unsafe to allow a single colon.
7587 (setq line (string-to-number (match-string 1 path))
7588 path (substring path 0 (match-beginning 0)))
7589 (if (string-match "::\\(.+\\)\\'" path)
7590 (setq search (match-string 1 path)
7591 path (substring path 0 (match-beginning 0)))))
7592 (org-open-file path in-emacs line search))
7594 ((string= type "news")
7595 (org-follow-gnus-link path))
7597 ((string= type "bbdb")
7598 (org-follow-bbdb-link path))
7600 ((string= type "gnus")
7601 (let (group article)
7602 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7603 (error "Error in Gnus link"))
7604 (setq group (match-string 1 path)
7605 article (match-string 3 path))
7606 (org-follow-gnus-link group article)))
7608 ((string= type "vm")
7609 (let (folder article)
7610 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7611 (error "Error in VM link"))
7612 (setq folder (match-string 1 path)
7613 article (match-string 3 path))
7614 ;; in-emacs is the prefix arg, will be interpreted as read-only
7615 (org-follow-vm-link folder article in-emacs)))
7617 ((string= type "wl")
7618 (let (folder article)
7619 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7620 (error "Error in Wanderlust link"))
7621 (setq folder (match-string 1 path)
7622 article (match-string 3 path))
7623 (org-follow-wl-link folder article)))
7625 ((string= type "mhe")
7626 (let (folder article)
7627 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7628 (error "Error in MHE link"))
7629 (setq folder (match-string 1 path)
7630 article (match-string 3 path))
7631 (org-follow-mhe-link folder article)))
7633 ((string= type "rmail")
7634 (let (folder article)
7635 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7636 (error "Error in RMAIL link"))
7637 (setq folder (match-string 1 path)
7638 article (match-string 3 path))
7639 (org-follow-rmail-link folder article)))
7641 ((string= type "shell")
7642 (let ((cmd path))
7643 (while (string-match "@{" cmd)
7644 (setq cmd (replace-match "<" t t cmd)))
7645 (while (string-match "@}" cmd)
7646 (setq cmd (replace-match ">" t t cmd)))
7647 (if (or (not org-confirm-shell-links)
7648 (funcall org-confirm-shell-links
7649 (format "Execute \"%s\" in shell? "
7650 (org-add-props cmd nil
7651 'face 'org-warning))))
7652 (progn
7653 (message "Executing %s" cmd)
7654 (shell-command cmd))
7655 (error "Abort"))))
7658 (browse-url-at-point))))))
7660 (defun org-link-search (s &optional type)
7661 "Search for a link search option.
7662 When S is a CamelCaseWord, search for a target, or for a sentence containing
7663 the words. If S is surrounded by forward slashes, it is interpreted as a
7664 regular expression. In org-mode files, this will create an `org-occur'
7665 sparse tree. In ordinary files, `occur' will be used to list matches.
7666 If the current buffer is in `dired-mode', grep will be used to search
7667 in all files."
7668 (let ((case-fold-search t)
7669 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7670 (pos (point))
7671 (pre "") (post "")
7672 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7673 (cond
7674 ;; First check if there are any special
7675 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7676 ;; Now try the builtin stuff
7677 ((save-excursion
7678 (goto-char (point-min))
7679 (and
7680 (re-search-forward
7681 (concat "<<" (regexp-quote s0) ">>") nil t)
7682 (setq pos (match-beginning 0))))
7683 ;; There is an exact target for this
7684 (goto-char pos))
7685 ((string-match "^/\\(.*\\)/$" s)
7686 ;; A regular expression
7687 (cond
7688 ((eq major-mode 'org-mode)
7689 (org-occur (match-string 1 s)))
7690 ;;((eq major-mode 'dired-mode)
7691 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7692 (t (org-do-occur (match-string 1 s)))))
7693 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7695 ;; A camel or a normal search string
7696 (when (equal (string-to-char s) ?*)
7697 ;; Anchor on headlines, post may include tags.
7698 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
7699 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7700 s (substring s 1)))
7701 (remove-text-properties
7702 0 (length s)
7703 '(face nil mouse-face nil keymap nil fontified nil) s)
7704 ;; Make a series of regular expressions to find a match
7705 (setq words
7706 (if camel
7707 (org-camel-to-words s)
7708 (org-split-string s "[ \n\r\t]+"))
7709 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7710 ;; FIXME: The word delimiters in the following are not quite correct.
7711 ; re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7712 ; re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7713 ; re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7714 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
7715 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7716 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7717 re1 (concat pre re2 post)
7718 re3 (concat pre re4 post)
7719 re5 (concat pre ".*" re4)
7720 re2 (concat pre re2)
7721 re2a (concat pre re2a)
7722 re4 (concat pre re4)
7723 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7724 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7725 re5 "\\)"
7727 (cond
7728 ((eq type 'org-occur) (org-occur reall))
7729 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7730 (t (goto-char (point-min))
7731 (if (or (org-search-not-link re0 nil t)
7732 (org-search-not-link re1 nil t)
7733 (org-search-not-link re2 nil t)
7734 (org-search-not-link re2a nil t)
7735 (org-search-not-link re3 nil t)
7736 (org-search-not-link re4 nil t)
7737 (org-search-not-link re5 nil t)
7739 (goto-char (match-beginning 1)) ;; Fixme: does every re have group 1?
7740 (goto-char pos)
7741 (error "No match")))))
7743 ;; Normal string-search
7744 (goto-char (point-min))
7745 (if (search-forward s nil t)
7746 (goto-char (match-beginning 0))
7747 (error "No match"))))
7748 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7750 (defun org-search-not-link (&rest args)
7751 "Execute `re-search-forward', but only accept matches that are not a link."
7752 (catch 'exit
7753 (let ((pos (point)) p1)
7754 (while (apply 're-search-forward args)
7755 (setq p1 (point))
7756 (if (not (save-match-data
7757 (and (re-search-backward "\\[\\[" nil t)
7758 (looking-at org-bracket-link-regexp)
7759 (<= (match-beginning 0) p1)
7760 (>= (match-end 0) p1))))
7761 (progn (goto-char (match-end 0))
7762 (throw 'exit (point)))
7763 (goto-char (match-end 0)))))))
7765 (defun org-do-occur (regexp &optional cleanup)
7766 "Call the Emacs command `occur'.
7767 If CLEANUP is non-nil, remove the printout of the regular expression
7768 in the *Occur* buffer. This is useful if the regex is long and not useful
7769 to read."
7770 (occur regexp)
7771 (when cleanup
7772 (let ((cwin (selected-window)) win beg end)
7773 (when (setq win (get-buffer-window "*Occur*"))
7774 (select-window win))
7775 (goto-char (point-min))
7776 (when (re-search-forward "match[a-z]+" nil t)
7777 (setq beg (match-end 0))
7778 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7779 (setq end (1- (match-beginning 0)))))
7780 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7781 (goto-char (point-min))
7782 (select-window cwin))))
7784 (defvar org-mark-ring nil
7785 "Mark ring for positions before jumps in Org-mode.")
7786 (defvar org-mark-ring-last-goto nil
7787 "Last position in the mark ring used to go back.")
7788 ;; Fill and close the ring
7789 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7790 (loop for i from 1 to org-mark-ring-length do
7791 (push (make-marker) org-mark-ring))
7792 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7793 org-mark-ring)
7795 (defun org-mark-ring-push (&optional pos buffer)
7796 "Put the current position or POS into the mark ring and rotate it."
7797 (interactive)
7798 (setq pos (or pos (point)))
7799 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7800 (move-marker (car org-mark-ring)
7801 (or pos (point))
7802 (or buffer (current-buffer)))
7803 (message
7804 (substitute-command-keys
7805 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7807 (defun org-mark-ring-goto (&optional n)
7808 "Jump to the previous position in the mark ring.
7809 With prefix arg N, jump back that many stored positions. When
7810 called several times in succession, walk through the entire ring.
7811 Org-mode commands jumping to a different position in the current file,
7812 or to another Org-mode file, automatically push the old position
7813 onto the ring."
7814 (interactive "p")
7815 (let (p m)
7816 (if (eq last-command this-command)
7817 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7818 (setq p org-mark-ring))
7819 (setq org-mark-ring-last-goto p)
7820 (setq m (car p))
7821 (switch-to-buffer (marker-buffer m))
7822 (goto-char m)
7823 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7825 (defun org-camel-to-words (s)
7826 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7827 (let ((case-fold-search nil)
7828 words)
7829 (while (string-match "[a-z][A-Z]" s)
7830 (push (substring s 0 (1+ (match-beginning 0))) words)
7831 (setq s (substring s (1+ (match-beginning 0)))))
7832 (nreverse (cons s words))))
7834 (defun org-remove-angle-brackets (s)
7835 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7836 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7838 (defun org-add-angle-brackets (s)
7839 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7840 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7843 (defun org-follow-bbdb-link (name)
7844 "Follow a BBDB link to NAME."
7845 (require 'bbdb)
7846 (let ((inhibit-redisplay t)
7847 (bbdb-electric-p nil))
7848 (catch 'exit
7849 ;; Exact match on name
7850 (bbdb-name (concat "\\`" name "\\'") nil)
7851 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7852 ;; Exact match on name
7853 (bbdb-company (concat "\\`" name "\\'") nil)
7854 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7855 ;; Partial match on name
7856 (bbdb-name name nil)
7857 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7858 ;; Partial match on company
7859 (bbdb-company name nil)
7860 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7861 ;; General match including network address and notes
7862 (bbdb name nil)
7863 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7864 (delete-window (get-buffer-window "*BBDB*"))
7865 (error "No matching BBDB record")))))
7867 (defun org-follow-gnus-link (&optional group article)
7868 "Follow a Gnus link to GROUP and ARTICLE."
7869 (require 'gnus)
7870 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7871 (if group (gnus-fetch-group group))
7872 (if article
7873 (or (gnus-summary-goto-article article nil 'force)
7874 (if (fboundp 'gnus-summary-insert-cached-articles)
7875 (progn
7876 (gnus-summary-insert-cached-articles)
7877 (gnus-summary-goto-article article nil 'force))
7878 (message "Message could not be found.")))))
7880 (defun org-follow-vm-link (&optional folder article readonly)
7881 "Follow a VM link to FOLDER and ARTICLE."
7882 (require 'vm)
7883 (setq article (org-add-angle-brackets article))
7884 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7885 ;; ange-ftp or efs or tramp access
7886 (let ((user (or (match-string 1 folder) (user-login-name)))
7887 (host (match-string 2 folder))
7888 (file (match-string 3 folder)))
7889 (cond
7890 ((featurep 'tramp)
7891 ;; use tramp to access the file
7892 (if (featurep 'xemacs)
7893 (setq folder (format "[%s@%s]%s" user host file))
7894 (setq folder (format "/%s@%s:%s" user host file))))
7896 ;; use ange-ftp or efs
7897 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7898 (setq folder (format "/%s@%s:%s" user host file))))))
7899 (when folder
7900 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7901 (sit-for 0.1)
7902 (when article
7903 (vm-select-folder-buffer)
7904 (widen)
7905 (let ((case-fold-search t))
7906 (goto-char (point-min))
7907 (if (not (re-search-forward
7908 (concat "^" "message-id: *" (regexp-quote article))))
7909 (error "Could not find the specified message in this folder"))
7910 (vm-isearch-update)
7911 (vm-isearch-narrow)
7912 (vm-beginning-of-message)
7913 (vm-summarize)))))
7915 (defun org-follow-wl-link (folder article)
7916 "Follow a Wanderlust link to FOLDER and ARTICLE."
7917 (setq article (org-add-angle-brackets article))
7918 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7919 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7920 (wl-summary-redisplay))
7922 (defun org-follow-rmail-link (folder article)
7923 "Follow an RMAIL link to FOLDER and ARTICLE."
7924 (setq article (org-add-angle-brackets article))
7925 (let (message-number)
7926 (save-excursion
7927 (save-window-excursion
7928 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7929 (setq message-number
7930 (save-restriction
7931 (widen)
7932 (goto-char (point-max))
7933 (if (re-search-backward
7934 (concat "^Message-ID:\\s-+" (regexp-quote
7935 (or article "")))
7936 nil t)
7937 (rmail-what-message))))))
7938 (if message-number
7939 (progn
7940 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7941 (rmail-show-message message-number)
7942 message-number)
7943 (error "Message not found"))))
7945 ;; mh-e integration based on planner-mode
7946 (defun org-mhe-get-message-real-folder ()
7947 "Return the name of the current message real folder, so if you use
7948 sequences, it will now work."
7949 (save-excursion
7950 (let* ((folder
7951 (if (equal major-mode 'mh-folder-mode)
7952 mh-current-folder
7953 ;; Refer to the show buffer
7954 mh-show-folder-buffer))
7955 (end-index
7956 (if (boundp 'mh-index-folder)
7957 (min (length mh-index-folder) (length folder))))
7959 ;; a simple test on mh-index-data does not work, because
7960 ;; mh-index-data is always nil in a show buffer.
7961 (if (and (boundp 'mh-index-folder)
7962 (string= mh-index-folder (substring folder 0 end-index)))
7963 (if (equal major-mode 'mh-show-mode)
7964 (save-window-excursion
7965 (when (buffer-live-p (get-buffer folder))
7966 (progn
7967 (pop-to-buffer folder)
7968 (org-mhe-get-message-folder-from-index)
7971 (org-mhe-get-message-folder-from-index)
7973 folder
7977 (defun org-mhe-get-message-folder-from-index ()
7978 "Returns the name of the message folder in a index folder buffer."
7979 (save-excursion
7980 (mh-index-previous-folder)
7981 (re-search-forward "^\\(+.*\\)$" nil t)
7982 (message (match-string 1))))
7984 (defun org-mhe-get-message-folder ()
7985 "Return the name of the current message folder. Be careful if you
7986 use sequences."
7987 (save-excursion
7988 (if (equal major-mode 'mh-folder-mode)
7989 mh-current-folder
7990 ;; Refer to the show buffer
7991 mh-show-folder-buffer)))
7993 (defun org-mhe-get-message-num ()
7994 "Return the number of the current message. Be careful if you
7995 use sequences."
7996 (save-excursion
7997 (if (equal major-mode 'mh-folder-mode)
7998 (mh-get-msg-num nil)
7999 ;; Refer to the show buffer
8000 (mh-show-buffer-message-number))))
8002 (defun org-mhe-get-header (header)
8003 "Return a header of the message in folder mode. This will create a
8004 show buffer for the corresponding message. If you have a more clever
8005 idea..."
8006 (let* ((folder (org-mhe-get-message-folder))
8007 (num (org-mhe-get-message-num))
8008 (buffer (get-buffer-create (concat "show-" folder)))
8009 (header-field))
8010 (with-current-buffer buffer
8011 (mh-display-msg num folder)
8012 (if (equal major-mode 'mh-folder-mode)
8013 (mh-header-display)
8014 (mh-show-header-display))
8015 (set-buffer buffer)
8016 (setq header-field (mh-get-header-field header))
8017 (if (equal major-mode 'mh-folder-mode)
8018 (mh-show)
8019 (mh-show-show))
8020 header-field)))
8022 (defun org-follow-mhe-link (folder article)
8023 "Follow an MHE link to FOLDER and ARTICLE.
8024 If ARTICLE is nil FOLDER is shown. If the configuration variable
8025 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
8026 ARTICLE is searched in all folders. Indexed searches (swish++,
8027 namazu, and others supported by MH-E) will always search in all
8028 folders."
8029 (require 'mh-e)
8030 (require 'mh-search)
8031 (require 'mh-utils)
8032 (mh-find-path)
8033 (if (not article)
8034 (mh-visit-folder (mh-normalize-folder-name folder))
8035 (setq article (org-add-angle-brackets article))
8036 (mh-search-choose)
8037 (if (equal mh-searcher 'pick)
8038 (progn
8039 (mh-search folder (list "--message-id" article))
8040 (when (and org-mhe-search-all-folders
8041 (not (org-mhe-get-message-real-folder)))
8042 (kill-this-buffer)
8043 (mh-search "+" (list "--message-id" article))))
8044 (mh-search "+" article))
8045 (if (org-mhe-get-message-real-folder)
8046 (mh-show-msg 1)
8047 (kill-this-buffer)
8048 (error "Message not found"))))
8050 ;; BibTeX links
8052 ;; Use the custom search meachnism to construct and use search strings for
8053 ;; file links to BibTeX database entries.
8055 (defun org-create-file-search-in-bibtex ()
8056 "Create the search string and description for a BibTeX database entry."
8057 (when (eq major-mode 'bibtex-mode)
8058 ;; yes, we want to construct this search string.
8059 ;; Make a good description for this entry, using names, year and the title
8060 ;; Put it into the `description' variable which is dynamically scoped.
8061 (let ((bibtex-autokey-names 1)
8062 (bibtex-autokey-names-stretch 1)
8063 (bibtex-autokey-name-case-convert-function 'identity)
8064 (bibtex-autokey-name-separator " & ")
8065 (bibtex-autokey-additional-names " et al.")
8066 (bibtex-autokey-year-length 4)
8067 (bibtex-autokey-name-year-separator " ")
8068 (bibtex-autokey-titlewords 3)
8069 (bibtex-autokey-titleword-separator " ")
8070 (bibtex-autokey-titleword-case-convert-function 'identity)
8071 (bibtex-autokey-titleword-length 'infty)
8072 (bibtex-autokey-year-title-separator ": "))
8073 (setq description (bibtex-generate-autokey)))
8074 ;; Now parse the entry, get the key and return it.
8075 (save-excursion
8076 (bibtex-beginning-of-entry)
8077 (cdr (assoc "=key=" (bibtex-parse-entry))))))
8079 (defun org-execute-file-search-in-bibtex (s)
8080 "Find the link search string S as a key for a database entry."
8081 (when (eq major-mode 'bibtex-mode)
8082 ;; Yes, we want to do the search in this file.
8083 ;; We construct a regexp that searches for "@entrytype{" followed by the key
8084 (goto-char (point-min))
8085 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
8086 (regexp-quote s) "[ \t\n]*,") nil t)
8087 (goto-char (match-beginning 0)))
8088 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
8089 ;; Use double prefix to indicate that any web link should be browsed
8090 (let ((b (current-buffer)) (p (point)))
8091 ;; Restore the window configuration because we just use the web link
8092 (set-window-configuration org-window-config-before-follow-link)
8093 (save-excursion (set-buffer b) (goto-char p)
8094 (bibtex-url)))
8095 (recenter 0)) ; Move entry start to beginning of window
8096 ;; return t to indicate that the search is done.
8099 ;; Finally add the functions to the right hooks.
8100 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
8101 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
8103 ;; end of Bibtex link setup
8105 (defun org-upgrade-old-links (&optional query-description)
8106 "Transfer old <...> style links to new [[...]] style links.
8107 With arg query-description, ask at each match for a description text to use
8108 for this link."
8109 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
8110 (save-excursion
8111 (goto-char (point-min))
8112 (let ((re (concat "\\([^[]\\)<\\("
8113 "\\(" (mapconcat 'identity org-link-types "\\|")
8114 "\\):"
8115 "[^" org-non-link-chars "]+\\)>"))
8116 l1 l2 (cnt 0))
8117 (while (re-search-forward re nil t)
8118 (setq cnt (1+ cnt)
8119 l1 (org-match-string-no-properties 2)
8120 l2 (save-match-data (org-link-escape l1)))
8121 (when query-description (setq l1 (read-string "Desc: " l1)))
8122 (if (equal l1 l2)
8123 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
8124 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
8125 (message "%d matches have beed treated" cnt))))
8127 (defun org-open-file (path &optional in-emacs line search)
8128 "Open the file at PATH.
8129 First, this expands any special file name abbreviations. Then the
8130 configuration variable `org-file-apps' is checked if it contains an
8131 entry for this file type, and if yes, the corresponding command is launched.
8132 If no application is found, Emacs simply visits the file.
8133 With optional argument IN-EMACS, Emacs will visit the file.
8134 Optional LINE specifies a line to go to, optional SEARCH a string to
8135 search for. If LINE or SEARCH is given, the file will always be
8136 opened in Emacs.
8137 If the file does not exist, an error is thrown."
8138 (setq in-emacs (or in-emacs line search))
8139 (let* ((file (if (equal path "")
8140 buffer-file-name
8141 (convert-standard-filename (org-expand-file-name path))))
8142 (dirp (file-directory-p file))
8143 (dfile (downcase file))
8144 (old-buffer (current-buffer))
8145 (old-pos (point))
8146 (old-mode major-mode)
8147 ext cmd apps)
8148 (if (and (not (file-exists-p file))
8149 (not org-open-non-existing-files))
8150 (error "No such file: %s" file))
8151 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8152 (setq ext (match-string 1 dfile))
8153 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8154 (setq ext (match-string 1 dfile))))
8155 (setq apps (append org-file-apps (org-default-apps)))
8156 (if in-emacs
8157 (setq cmd 'emacs)
8158 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
8159 (cdr (assoc ext apps))
8160 (cdr (assoc t apps)))))
8161 (when (eq cmd 'mailcap)
8162 (require 'mailcap)
8163 (mailcap-parse-mailcaps)
8164 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8165 (command (mailcap-mime-info mime-type)))
8166 (if (stringp command)
8167 (setq cmd command)
8168 (setq cmd 'emacs))))
8169 (cond
8170 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8171 ;; Normalize use of quote, this can vary.
8172 (if (string-match "['\"]%s['\"]" cmd)
8173 (setq cmd (replace-match "'%s'" t t cmd)))
8174 (setq cmd (format cmd file))
8175 (save-window-excursion
8176 (shell-command (concat cmd " &"))))
8177 ((or (stringp cmd)
8178 (eq cmd 'emacs))
8179 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
8180 (funcall (cdr (assq 'file org-link-frame-setup)) file))
8181 (if line (goto-line line)
8182 (if search (org-link-search search))))
8183 ((consp cmd)
8184 (eval cmd))
8185 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8186 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
8187 (or (not (equal old-buffer (current-buffer)))
8188 (not (equal old-pos (point))))
8189 (org-mark-ring-push old-pos old-buffer))))
8191 (defun org-default-apps ()
8192 "Return the default applications for this operating system."
8193 (cond
8194 ((eq system-type 'darwin)
8195 org-file-apps-defaults-macosx)
8196 ((eq system-type 'windows-nt)
8197 org-file-apps-defaults-windowsnt)
8198 (t org-file-apps-defaults-gnu)))
8200 (defun org-expand-file-name (path)
8201 "Replace special path abbreviations and expand the file name."
8202 (expand-file-name path))
8205 (defvar org-insert-link-history nil
8206 "Minibuffer history for links inserted with `org-insert-link'.")
8208 (defvar org-stored-links nil
8209 "Contains the links stored with `org-store-link'.")
8211 ;;;###autoload
8212 (defun org-store-link (arg)
8213 "\\<org-mode-map>Store an org-link to the current location.
8214 This link can later be inserted into an org-buffer with
8215 \\[org-insert-link].
8216 For some link types, a prefix arg is interpreted:
8217 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
8218 For file links, arg negates `org-context-in-file-links'."
8219 (interactive "P")
8220 (let (link cpltxt desc description search txt (pos (point)))
8221 (cond
8223 ((eq major-mode 'bbdb-mode)
8224 (setq cpltxt (concat
8225 "bbdb:"
8226 (or (bbdb-record-name (bbdb-current-record))
8227 (bbdb-record-company (bbdb-current-record))))
8228 link (org-make-link cpltxt)))
8230 ((eq major-mode 'calendar-mode)
8231 (let ((cd (calendar-cursor-to-date)))
8232 (setq link
8233 (format-time-string
8234 (car org-time-stamp-formats)
8235 (apply 'encode-time
8236 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8237 nil nil nil))))))
8239 ((or (eq major-mode 'vm-summary-mode)
8240 (eq major-mode 'vm-presentation-mode))
8241 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
8242 (vm-follow-summary-cursor)
8243 (save-excursion
8244 (vm-select-folder-buffer)
8245 (let* ((message (car vm-message-pointer))
8246 (folder buffer-file-name)
8247 (subject (vm-su-subject message))
8248 (author (vm-su-full-name message))
8249 (message-id (vm-su-message-id message)))
8250 (setq message-id (org-remove-angle-brackets message-id))
8251 (setq folder (abbreviate-file-name folder))
8252 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
8253 folder)
8254 (setq folder (replace-match "" t t folder)))
8255 (setq cpltxt (concat author " on: " subject))
8256 (setq link (org-make-link "vm:" folder "#" message-id)))))
8258 ((eq major-mode 'wl-summary-mode)
8259 (let* ((msgnum (wl-summary-message-number))
8260 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
8261 msgnum 'message-id))
8262 (wl-message-entity (elmo-msgdb-overview-get-entity
8263 msgnum (wl-summary-buffer-msgdb)))
8264 (author (wl-summary-line-from)) ; FIXME: correct?
8265 (subject "???")) ; FIXME:
8266 (setq message-id (org-remove-angle-brackets message-id))
8267 (setq cpltxt (concat author " on: " subject))
8268 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8269 "#" message-id))))
8271 ((or (equal major-mode 'mh-folder-mode)
8272 (equal major-mode 'mh-show-mode))
8273 (let ((from-header (org-mhe-get-header "From:"))
8274 (to-header (org-mhe-get-header "To:"))
8275 (subject (org-mhe-get-header "Subject:")))
8276 (setq cpltxt (concat from-header " on: " subject))
8277 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8278 (org-remove-angle-brackets
8279 (org-mhe-get-header "Message-Id:"))))))
8281 ((eq major-mode 'rmail-mode)
8282 (save-excursion
8283 (save-restriction
8284 (rmail-narrow-to-non-pruned-header)
8285 (let ((folder buffer-file-name)
8286 (message-id (mail-fetch-field "message-id"))
8287 (author (mail-fetch-field "from"))
8288 (subject (mail-fetch-field "subject")))
8289 (setq message-id (org-remove-angle-brackets message-id))
8290 (setq cpltxt (concat author " on: " subject))
8291 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8293 ((eq major-mode 'gnus-group-mode)
8294 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8295 (gnus-group-group-name)) ; version
8296 ((fboundp 'gnus-group-name)
8297 (gnus-group-name))
8298 (t "???"))))
8299 (setq cpltxt (concat
8300 (if (org-xor arg org-usenet-links-prefer-google)
8301 "http://groups.google.com/groups?group="
8302 "gnus:")
8303 group)
8304 link (org-make-link cpltxt))))
8306 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8307 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8308 (gnus-summary-beginning-of-article)
8309 (let* ((group (car gnus-article-current))
8310 (article (cdr gnus-article-current))
8311 (header (gnus-summary-article-header article))
8312 (author (mail-header-from header))
8313 (message-id (mail-header-id header))
8314 (date (mail-header-date header))
8315 (subject (gnus-summary-subject-string)))
8316 (setq cpltxt (concat author " on: " subject))
8317 (if (org-xor arg org-usenet-links-prefer-google)
8318 (setq link
8319 (concat
8320 cpltxt "\n "
8321 (format "http://groups.google.com/groups?as_umsgid=%s"
8322 (org-fixup-message-id-for-http message-id))))
8323 (setq link (org-make-link "gnus:" group
8324 "#" (number-to-string article))))))
8326 ((eq major-mode 'w3-mode)
8327 (setq cpltxt (url-view-url t)
8328 link (org-make-link cpltxt)))
8329 ((eq major-mode 'w3m-mode)
8330 (setq cpltxt w3m-current-url
8331 link (org-make-link cpltxt)))
8333 ((setq search (run-hook-with-args-until-success
8334 'org-create-file-search-functions))
8335 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8336 "::" search))
8337 (setq cpltxt (or description link))) ;; FIXME: is this the best way?
8339 ((eq major-mode 'org-mode)
8340 ;; Just link to current headline
8341 (setq cpltxt (concat "file:"
8342 (abbreviate-file-name buffer-file-name)))
8343 ;; Add a context search string
8344 (when (org-xor org-context-in-file-links arg)
8345 ;; Check if we are on a target
8346 (if (save-excursion
8347 (skip-chars-forward "^>\n\r")
8348 (and (re-search-backward "<<" nil t)
8349 (looking-at "<<\\(.*?\\)>>")
8350 (<= (match-beginning 0) pos)
8351 (>= (match-end 0) pos)))
8352 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8353 (setq txt (cond
8354 ((org-on-heading-p) nil)
8355 ((org-region-active-p)
8356 (buffer-substring (region-beginning) (region-end)))
8357 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8358 (setq cpltxt
8359 (concat cpltxt "::"
8360 (if org-file-link-context-use-camel-case
8361 (org-make-org-heading-camel txt)
8362 (org-make-org-heading-search-string txt)))
8363 desc "NONE")))
8364 (if (string-match "::\\'" cpltxt)
8365 (setq cpltxt (substring cpltxt 0 -2)))
8366 (setq link (org-make-link cpltxt)))
8368 (buffer-file-name
8369 ;; Just link to this file here.
8370 (setq cpltxt (concat "file:"
8371 (abbreviate-file-name buffer-file-name)))
8372 ;; Add a context string
8373 (when (org-xor org-context-in-file-links arg)
8374 (setq txt (if (org-region-active-p)
8375 (buffer-substring (region-beginning) (region-end))
8376 (buffer-substring (point-at-bol) (point-at-eol))))
8377 (setq cpltxt
8378 (concat cpltxt "::"
8379 (if org-file-link-context-use-camel-case
8380 (org-make-org-heading-camel txt)
8381 (org-make-org-heading-search-string txt)))
8382 desc "NONE"))
8383 (setq link (org-make-link cpltxt)))
8385 ((interactive-p)
8386 (error "Cannot link to a buffer which is not visiting a file"))
8388 (t (setq link nil)))
8390 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8391 (setq link (or link cpltxt)
8392 desc (or desc cpltxt))
8393 (if (equal desc "NONE") (setq desc nil))
8395 (if (and (interactive-p) link)
8396 (progn
8397 (setq org-stored-links
8398 (cons (list cpltxt link desc) org-stored-links))
8399 (message "Stored: %s" (or cpltxt link)))
8400 (org-make-link-string link desc))))
8402 (defun org-make-org-heading-search-string (&optional string heading)
8403 "Make search string for STRING or current headline."
8404 (interactive)
8405 (let ((s (or string (org-get-heading))))
8406 (unless (and string (not heading))
8407 ;; We are using a headline, clean up garbage in there.
8408 (if (string-match org-todo-regexp s)
8409 (setq s (replace-match "" t t s)))
8410 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8411 (setq s (replace-match "" t t s)))
8412 (setq s (org-trim s))
8413 (if (string-match (concat "^\\(" org-quote-string "\\|"
8414 org-comment-string "\\)") s)
8415 (setq s (replace-match "" t t s)))
8416 (while (string-match org-ts-regexp s)
8417 (setq s (replace-match "" t t s))))
8418 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8419 (setq s (replace-match " " t t s)))
8420 (or string (setq s (concat "*" s))) ; Add * for headlines
8421 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8423 (defun org-make-org-heading-camel (&optional string heading)
8424 "Make a CamelCase string for STRING or the current headline."
8425 (interactive)
8426 (let ((s (or string (org-get-heading))))
8427 (unless (and string (not heading))
8428 ;; We are using a headline, clean up garbage in there.
8429 (if (string-match org-todo-regexp s)
8430 (setq s (replace-match "" t t s)))
8431 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8432 (setq s (replace-match "" t t s)))
8433 (setq s (org-trim s))
8434 (if (string-match (concat "^\\(" org-quote-string "\\|"
8435 org-comment-string "\\)") s)
8436 (setq s (replace-match "" t t s)))
8437 (while (string-match org-ts-regexp s)
8438 (setq s (replace-match "" t t s))))
8439 (while (string-match "[^a-zA-Z_ \t]+" s)
8440 (setq s (replace-match " " t t s)))
8441 (or string (setq s (concat "*" s))) ; Add * for headlines
8442 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8444 (defun org-make-link (&rest strings)
8445 "Concatenate STRINGS, format resulting string with `org-link-format'."
8446 (format org-link-format (apply 'concat strings)))
8448 (defun org-make-link-string (link &optional description)
8449 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8450 (if (eq org-link-style 'plain)
8451 (if (equal description link)
8452 link
8453 (concat description "\n" link))
8454 (when (stringp description)
8455 ;; Remove brackets from the description, they are fatal.
8456 (while (string-match "\\[\\|\\]" description)
8457 (setq description (replace-match "" t t description))))
8458 (when (equal (org-link-escape link) description)
8459 ;; No description needed, it is identical
8460 (setq description nil))
8461 (when (and (not description)
8462 (not (equal link (org-link-escape link))))
8463 (setq description link))
8464 (concat "[[" (org-link-escape link) "]"
8465 (if description (concat "[" description "]") "")
8466 "]")))
8468 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8469 "Association list of escapes for some characters problematic in links.")
8471 (defun org-link-escape (text)
8472 "Escape charaters in TEXT that are problematic for links."
8473 (when text
8474 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8475 org-link-escape-chars "\\|")))
8476 (while (string-match re text)
8477 (setq text
8478 (replace-match
8479 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8480 t t text)))
8481 text)))
8483 (defun org-link-unescape (text)
8484 "Reverse the action of `org-link-escape'."
8485 (when text
8486 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8487 org-link-escape-chars "\\|")))
8488 (while (string-match re text)
8489 (setq text
8490 (replace-match
8491 (car (rassoc (match-string 0 text) org-link-escape-chars))
8492 t t text)))
8493 text)))
8495 (defun org-xor (a b)
8496 "Exclusive or."
8497 (if a (not b) b))
8499 (defun org-get-header (header)
8500 "Find a header field in the current buffer."
8501 (save-excursion
8502 (goto-char (point-min))
8503 (let ((case-fold-search t) s)
8504 (cond
8505 ((eq header 'from)
8506 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8507 (setq s (match-string 1)))
8508 (while (string-match "\"" s)
8509 (setq s (replace-match "" t t s)))
8510 (if (string-match "[<(].*" s)
8511 (setq s (replace-match "" t t s))))
8512 ((eq header 'message-id)
8513 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8514 (setq s (match-string 1))))
8515 ((eq header 'subject)
8516 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8517 (setq s (match-string 1)))))
8518 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8519 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8520 s)))
8523 (defun org-fixup-message-id-for-http (s)
8524 "Replace special characters in a message id, so it can be used in an http query."
8525 (while (string-match "<" s)
8526 (setq s (replace-match "%3C" t t s)))
8527 (while (string-match ">" s)
8528 (setq s (replace-match "%3E" t t s)))
8529 (while (string-match "@" s)
8530 (setq s (replace-match "%40" t t s)))
8533 (defun org-insert-link (&optional complete-file)
8534 "Insert a link. At the prompt, enter the link.
8536 Completion can be used to select a link previously stored with
8537 `org-store-link'. When the empty string is entered (i.e. if you just
8538 press RET at the prompt), the link defaults to the most recently
8539 stored link. As SPC triggers completion in the minibuffer, you need to
8540 use M-SPC or C-q SPC to force the insertion of a space character.
8542 You will also be prompted for a description, and if one is given, it will
8543 be displayed in the buffer instead of the link.
8545 If there is already a link at point, this command will allow you to edit link
8546 and description parts.
8548 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8549 selected using completion. The path to the file will be relative to
8550 the current directory if the file is in the current directory or a
8551 subdirectory. Otherwise, the link will be the absolute path as
8552 completed in the minibuffer (i.e. normally ~/path/to/file).
8554 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8555 is in the current directory or below."
8556 (interactive "P")
8557 (let (link desc entry remove file (pos (point)))
8558 (cond
8559 ((save-excursion
8560 (skip-chars-forward "^]\n\r")
8561 (and (re-search-backward "\\[\\[" nil t)
8562 (looking-at org-bracket-link-regexp)
8563 (<= (match-beginning 0) pos)
8564 (>= (match-end 0) pos)))
8565 ;; We do have a link at point, and we are going to edit it.
8566 (setq remove (list (match-beginning 0) (match-end 0)))
8567 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8568 (setq link (read-string "Link: "
8569 (org-link-unescape
8570 (org-match-string-no-properties 1)))))
8571 (complete-file
8572 ;; Completing read for file names.
8573 (setq file (read-file-name "File: "))
8574 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8575 (pwd1 (file-name-as-directory (abbreviate-file-name
8576 (expand-file-name ".")))))
8577 (cond
8578 ((equal complete-file '(16))
8579 (setq link (org-make-link
8580 "file:"
8581 (abbreviate-file-name (expand-file-name file)))))
8582 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8583 (setq link (org-make-link "file:" (match-string 1 file))))
8584 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8585 (expand-file-name file))
8586 (setq link (org-make-link
8587 "file:" (match-string 1 (expand-file-name file)))))
8588 (t (setq link (org-make-link "file:" file))))))
8590 ;; Read link, with completion for stored links.
8591 (setq link (org-completing-read
8592 "Link: " org-stored-links nil nil nil
8593 org-insert-link-history
8594 (or (car (car org-stored-links)))))
8595 (setq entry (assoc link org-stored-links))
8596 (if (not org-keep-stored-link-after-insertion)
8597 (setq org-stored-links (delq (assoc link org-stored-links)
8598 org-stored-links)))
8599 (setq link (if entry (nth 1 entry) link)
8600 desc (or desc (nth 2 entry)))))
8602 (if (string-match org-plain-link-re link)
8603 ;; URL-like link, normalize the use of angular brackets.
8604 (setq link (org-make-link (org-remove-angle-brackets link))))
8606 ;; Check if we are linking to the current file. If yes, simplify the link.
8607 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8608 (let* ((path (match-string 1 link))
8609 (case-fold-search nil)
8610 (search (match-string 2 link)))
8611 (when (save-match-data
8612 (equal (file-truename buffer-file-name)
8613 (file-truename path)))
8614 ;; We are linking to this same file, with a search option
8615 (setq link search))))
8616 (setq desc (read-string "Description: " desc))
8617 (unless (string-match "\\S-" desc) (setq desc nil))
8618 (if remove (apply 'delete-region remove))
8619 (insert (org-make-link-string link desc))))
8621 (defun org-completing-read (&rest args)
8622 (let ((minibuffer-local-completion-map
8623 (copy-keymap minibuffer-local-completion-map)))
8624 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8625 (apply 'completing-read args)))
8627 ;;; Hooks for remember.el
8629 (defvar org-finish-function nil)
8631 ;;;###autoload
8632 (defun org-remember-annotation ()
8633 "Return a link to the current location as an annotation for remember.el.
8634 If you are using Org-mode files as target for data storage with
8635 remember.el, then the annotations should include a link compatible with the
8636 conventions in Org-mode. This function returns such a link."
8637 (org-store-link nil))
8639 (defconst org-remember-help
8640 "Select a destination location for the note.
8641 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8642 RET at beg-of-buf -> Append to file as level 2 headline
8643 RET on headline -> Store as sublevel entry to current headline
8644 <left>/<right> -> before/after current headline, same headings level")
8646 ;;;###autoload
8647 (defun org-remember-apply-template ()
8648 "Initialize *remember* buffer with template, invode `org-mode'.
8649 This function should be placed into `remember-mode-hook' and in fact requires
8650 to be run from that hook to fucntion properly."
8651 (if org-remember-templates
8653 (let* ((entry (if (= (length org-remember-templates) 1)
8654 (cdar org-remember-templates)
8655 (message "Select template: %s"
8656 (mapconcat
8657 (lambda (x) (char-to-string (car x)))
8658 org-remember-templates " "))
8659 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8660 (tpl (car entry))
8661 (file (if (consp (cdr entry)) (nth 1 entry)))
8662 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8663 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8664 (v-u (concat "[" (substring v-t 1 -1) "]"))
8665 (v-U (concat "[" (substring v-T 1 -1) "]"))
8666 (v-a annotation) ; defined in `remember-mode'
8667 (v-i initial) ; defined in `remember-mode'
8668 (v-n user-full-name)
8670 (unless tpl (setq tpl "") (message "No template") (ding))
8671 (insert tpl) (goto-char (point-min))
8672 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8673 (when (and initial (equal (match-string 0) "%i"))
8674 (save-match-data
8675 (let* ((lead (buffer-substring
8676 (point-at-bol) (match-beginning 0))))
8677 (setq v-i (mapconcat 'identity
8678 (org-split-string initial "\n")
8679 (concat "\n" lead))))))
8680 (replace-match
8681 (or (eval (intern (concat "v-" (match-string 1)))) "")
8682 t t))
8683 (let ((org-startup-folded nil)
8684 (org-startup-with-deadline-check nil))
8685 (org-mode))
8686 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8687 (set (make-local-variable 'org-default-notes-file) file))
8688 (goto-char (point-min))
8689 (if (re-search-forward "%\\?" nil t) (replace-match "")))
8690 (let ((org-startup-folded nil)
8691 (org-startup-with-deadline-check nil))
8692 (org-mode)))
8693 (set (make-local-variable 'org-finish-function) 'remember-buffer))
8695 ;;;###autoload
8696 (defun org-remember-handler ()
8697 "Store stuff from remember.el into an org file.
8698 First prompts for an org file. If the user just presses return, the value
8699 of `org-default-notes-file' is used.
8700 Then the command offers the headings tree of the selected file in order to
8701 file the text at a specific location.
8702 You can either immediately press RET to get the note appended to the
8703 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8704 find a better place. Then press RET or <left> or <right> in insert the note.
8706 Key Cursor position Note gets inserted
8707 -----------------------------------------------------------------------------
8708 RET buffer-start as level 2 heading at end of file
8709 RET on headline as sublevel of the heading at cursor
8710 RET no heading at cursor position, level taken from context.
8711 Or use prefix arg to specify level manually.
8712 <left> on headline as same level, before current heading
8713 <right> on headline as same level, after current heading
8715 So the fastest way to store the note is to press RET RET to append it to
8716 the default file. This way your current train of thought is not
8717 interrupted, in accordance with the principles of remember.el. But with
8718 little extra effort, you can push it directly to the correct location.
8720 Before being stored away, the function ensures that the text has a
8721 headline, i.e. a first line that starts with a \"*\". If not, a headline
8722 is constructed from the current date and some additional data.
8724 If the variable `org-adapt-indentation' is non-nil, the entire text is
8725 also indented so that it starts in the same column as the headline
8726 \(i.e. after the stars).
8728 See also the variable `org-reverse-note-order'."
8729 (catch 'quit
8730 (let* ((txt (buffer-substring (point-min) (point-max)))
8731 (fastp current-prefix-arg)
8732 (file (if fastp org-default-notes-file (org-get-org-file)))
8733 (visiting (find-buffer-visiting file))
8734 (org-startup-with-deadline-check nil)
8735 (org-startup-folded nil)
8736 (org-startup-align-all-tables nil)
8737 spos level indent reversed)
8738 ;; Modify text so that it becomes a nice subtree which can be inserted
8739 ;; into an org tree.
8740 (let* ((lines (split-string txt "\n"))
8741 first)
8742 ;; remove empty lines at the beginning
8743 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8744 (setq lines (cdr lines)))
8745 (setq first (car lines) lines (cdr lines))
8746 (if (string-match "^\\*+" first)
8747 ;; Is already a headline
8748 (setq indent nil)
8749 ;; We need to add a headline: Use time and first buffer line
8750 (setq lines (cons first lines)
8751 first (concat "* " (current-time-string)
8752 " (" (remember-buffer-desc) ")")
8753 indent " "))
8754 (if (and org-adapt-indentation indent)
8755 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8756 (setq txt (concat first "\n"
8757 (mapconcat 'identity lines "\n"))))
8758 ;; Find the file
8759 (if (not visiting)
8760 (find-file-noselect file))
8761 (with-current-buffer (get-file-buffer file)
8762 (save-excursion (and (goto-char (point-min))
8763 (not (re-search-forward "^\\* " nil t))
8764 (insert "\n* Notes\n")))
8765 (setq reversed (org-notes-order-reversed-p))
8766 (save-excursion
8767 (save-restriction
8768 (widen)
8769 ;; Ask the User for a location
8770 (setq spos (if fastp 1 (org-get-location
8771 (current-buffer)
8772 org-remember-help)))
8773 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8774 ; not handle this note
8775 (goto-char spos)
8776 (cond ((bobp)
8777 ;; Put it at the start or end, as level 2
8778 (save-restriction
8779 (widen)
8780 (goto-char (if reversed (point-min) (point-max)))
8781 (if (not (bolp)) (newline))
8782 (org-paste-subtree 2 txt)))
8783 ((and (org-on-heading-p nil) (not current-prefix-arg))
8784 ;; Put it below this entry, at the beg/end of the subtree
8785 (org-back-to-heading)
8786 (setq level (funcall outline-level))
8787 (if reversed
8788 (outline-end-of-heading)
8789 (outline-end-of-subtree))
8790 (if (not (bolp)) (newline))
8791 (beginning-of-line 1)
8792 (org-paste-subtree (1+ level) txt))
8794 ;; Put it right there, with automatic level determined by
8795 ;; org-paste-subtree or from prefix arg
8796 (org-paste-subtree current-prefix-arg txt)))
8797 (when remember-save-after-remembering
8798 (save-buffer)
8799 (if (not visiting) (kill-buffer (current-buffer)))))))))
8800 t) ;; return t to indicate that we took care of this note.
8802 (defun org-get-org-file ()
8803 "Read a filename, with default directory `org-directory'."
8804 (let ((default (or org-default-notes-file remember-data-file)))
8805 (read-file-name (format "File name [%s]: " default)
8806 (file-name-as-directory org-directory)
8807 default)))
8809 (defun org-notes-order-reversed-p ()
8810 "Check if the current file should receive notes in reversed order."
8811 (cond
8812 ((not org-reverse-note-order) nil)
8813 ((eq t org-reverse-note-order) t)
8814 ((not (listp org-reverse-note-order)) nil)
8815 (t (catch 'exit
8816 (let ((all org-reverse-note-order)
8817 entry)
8818 (while (setq entry (pop all))
8819 (if (string-match (car entry) buffer-file-name)
8820 (throw 'exit (cdr entry))))
8821 nil)))))
8823 ;;; Tables
8825 ;; Watch out: Here we are talking about two different kind of tables.
8826 ;; Most of the code is for the tables created with the Org-mode table editor.
8827 ;; Sometimes, we talk about tables created and edited with the table.el
8828 ;; Emacs package. We call the former org-type tables, and the latter
8829 ;; table.el-type tables.
8832 (defun org-before-change-function (beg end)
8833 "Every change indicates that a table might need an update."
8834 (setq org-table-may-need-update t))
8836 (defconst org-table-line-regexp "^[ \t]*|"
8837 "Detects an org-type table line.")
8838 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8839 "Detects an org-type table line.")
8840 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8841 "Detects a table line marked for automatic recalculation.")
8842 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8843 "Detects a table line marked for automatic recalculation.")
8844 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8845 "Detects a table line marked for automatic recalculation.")
8846 (defconst org-table-hline-regexp "^[ \t]*|-"
8847 "Detects an org-type table hline.")
8848 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8849 "Detects a table-type table hline.")
8850 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8851 "Detects an org-type or table-type table.")
8852 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8853 "Searching from within a table (any type) this finds the first line
8854 outside the table.")
8855 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8856 "Searching from within a table (any type) this finds the first line
8857 outside the table.")
8859 (defun org-table-create-with-table.el ()
8860 "Use the table.el package to insert a new table.
8861 If there is already a table at point, convert between Org-mode tables
8862 and table.el tables."
8863 (interactive)
8864 (require 'table)
8865 (cond
8866 ((org-at-table.el-p)
8867 (if (y-or-n-p "Convert table to Org-mode table? ")
8868 (org-table-convert)))
8869 ((org-at-table-p)
8870 (if (y-or-n-p "Convert table to table.el table? ")
8871 (org-table-convert)))
8872 (t (call-interactively 'table-insert))))
8874 (defun org-table-create-or-convert-from-region (arg)
8875 "Convert region to table, or create an empty table.
8876 If there is an active region, convert it to a table. If there is no such
8877 region, create an empty table."
8878 (interactive "P")
8879 (if (org-region-active-p)
8880 (org-table-convert-region (region-beginning) (region-end) arg)
8881 (org-table-create arg)))
8883 (defun org-table-create (&optional size)
8884 "Query for a size and insert a table skeleton.
8885 SIZE is a string Columns x Rows like for example \"3x2\"."
8886 (interactive "P")
8887 (unless size
8888 (setq size (read-string
8889 (concat "Table size Columns x Rows [e.g. "
8890 org-table-default-size "]: ")
8891 "" nil org-table-default-size)))
8893 (let* ((pos (point))
8894 (indent (make-string (current-column) ?\ ))
8895 (split (org-split-string size " *x *"))
8896 (rows (string-to-number (nth 1 split)))
8897 (columns (string-to-number (car split)))
8898 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8899 "\n")))
8900 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8901 (point-at-bol) (point)))
8902 (beginning-of-line 1)
8903 (newline))
8904 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8905 (dotimes (i rows) (insert line))
8906 (goto-char pos)
8907 (if (> rows 1)
8908 ;; Insert a hline after the first row.
8909 (progn
8910 (end-of-line 1)
8911 (insert "\n|-")
8912 (goto-char pos)))
8913 (org-table-align)))
8915 (defun org-table-convert-region (beg0 end0 &optional nspace)
8916 "Convert region to a table.
8917 The region goes from BEG0 to END0, but these borders will be moved
8918 slightly, to make sure a beginning of line in the first line is included.
8919 When NSPACE is non-nil, it indicates the minimum number of spaces that
8920 separate columns (default: just one space)."
8921 (interactive "rP")
8922 (let* ((beg (min beg0 end0))
8923 (end (max beg0 end0))
8924 (tabsep t)
8926 (goto-char beg)
8927 (beginning-of-line 1)
8928 (setq beg (move-marker (make-marker) (point)))
8929 (goto-char end)
8930 (if (bolp) (backward-char 1) (end-of-line 1))
8931 (setq end (move-marker (make-marker) (point)))
8932 ;; Lets see if this is tab-separated material. If every nonempty line
8933 ;; contains a tab, we will assume that it is tab-separated material
8934 (if nspace
8935 (setq tabsep nil)
8936 (goto-char beg)
8937 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8938 (if nspace (setq tabsep nil))
8939 (if tabsep
8940 (setq re "^\\|\t")
8941 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8942 (max 1 (prefix-numeric-value nspace)))))
8943 (goto-char beg)
8944 (while (re-search-forward re end t)
8945 (replace-match "|" t t))
8946 (goto-char beg)
8947 (insert " ")
8948 (org-table-align)))
8950 (defun org-table-import (file arg)
8951 "Import FILE as a table.
8952 The file is assumed to be tab-separated. Such files can be produced by most
8953 spreadsheet and database applications. If no tabs (at least one per line)
8954 are found, lines will be split on whitespace into fields."
8955 (interactive "f\nP")
8956 (or (bolp) (newline))
8957 (let ((beg (point))
8958 (pm (point-max)))
8959 (insert-file-contents file)
8960 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8962 (defun org-table-export ()
8963 "Export table as a tab-separated file.
8964 Such a file can be imported into a spreadsheet program like Excel."
8965 (interactive)
8966 (let* ((beg (org-table-begin))
8967 (end (org-table-end))
8968 (table (buffer-substring beg end))
8969 (file (read-file-name "Export table to: "))
8970 buf)
8971 (unless (or (not (file-exists-p file))
8972 (y-or-n-p (format "Overwrite file %s? " file)))
8973 (error "Abort"))
8974 (with-current-buffer (find-file-noselect file)
8975 (setq buf (current-buffer))
8976 (erase-buffer)
8977 (fundamental-mode)
8978 (insert table)
8979 (goto-char (point-min))
8980 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8981 (replace-match "" t t)
8982 (end-of-line 1))
8983 (goto-char (point-min))
8984 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8985 (replace-match "" t t)
8986 (goto-char (min (1+ (point)) (point-max))))
8987 (goto-char (point-min))
8988 (while (re-search-forward "^-[-+]*$" nil t)
8989 (replace-match "")
8990 (if (looking-at "\n")
8991 (delete-char 1)))
8992 (goto-char (point-min))
8993 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8994 (replace-match "\t" t t))
8995 (save-buffer))
8996 (kill-buffer buf)))
8998 (defvar org-table-aligned-begin-marker (make-marker)
8999 "Marker at the beginning of the table last aligned.
9000 Used to check if cursor still is in that table, to minimize realignment.")
9001 (defvar org-table-aligned-end-marker (make-marker)
9002 "Marker at the end of the table last aligned.
9003 Used to check if cursor still is in that table, to minimize realignment.")
9004 (defvar org-table-last-alignment nil
9005 "List of flags for flushright alignment, from the last re-alignment.
9006 This is being used to correctly align a single field after TAB or RET.")
9007 (defvar org-table-last-column-widths nil
9008 "List of max width of fields in each column.
9009 This is being used to correctly align a single field after TAB or RET.")
9011 (defvar org-last-recalc-line nil)
9012 (defconst org-narrow-column-arrow "=>"
9013 "Used as display property in narrowed table columns.")
9015 (defun org-table-align ()
9016 "Align the table at point by aligning all vertical bars."
9017 (interactive)
9018 (let* (
9019 ;; Limits of table
9020 (beg (org-table-begin))
9021 (end (org-table-end))
9022 ;; Current cursor position
9023 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9024 (colpos (org-table-current-column))
9025 (winstart (window-start))
9026 text lines (new "") lengths l typenums ty fields maxfields i
9027 column
9028 (indent "") cnt frac
9029 rfmt hfmt
9030 (spaces '(1 . 1))
9031 (sp1 (car spaces))
9032 (sp2 (cdr spaces))
9033 (rfmt1 (concat
9034 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
9035 (hfmt1 (concat
9036 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
9037 emptystrings xx links narrow fmax fmin f1 len c e)
9038 (untabify beg end)
9039 (remove-text-properties beg end '(org-cwidth t display t))
9040 ;; Check if we have links
9041 (goto-char beg)
9042 (setq links (re-search-forward org-bracket-link-regexp end t))
9043 ;; Make sure the link properties are right FIXME: Can this be optimized????
9044 (when links (goto-char beg) (while (org-activate-bracket-links end)))
9045 ;; Check if we are narrowing any columns
9046 (goto-char beg)
9047 (setq narrow (and org-format-transports-properties-p
9048 (re-search-forward "<[0-9]+>" end t)))
9049 ;; Get the rows
9050 (setq lines (org-split-string
9051 (buffer-substring beg end) "\n"))
9052 ;; Store the indentation of the first line
9053 (if (string-match "^ *" (car lines))
9054 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
9055 ;; Mark the hlines by setting the corresponding element to nil
9056 ;; At the same time, we remove trailing space.
9057 (setq lines (mapcar (lambda (l)
9058 (if (string-match "^ *|-" l)
9060 (if (string-match "[ \t]+$" l)
9061 (substring l 0 (match-beginning 0))
9062 l)))
9063 lines))
9064 ;; Get the data fields by splitting the lines.
9065 (setq fields (mapcar
9066 (lambda (l)
9067 (org-split-string l " *| *"))
9068 (delq nil (copy-sequence lines))))
9069 ;; How many fields in the longest line?
9070 (condition-case nil
9071 (setq maxfields (apply 'max (mapcar 'length fields)))
9072 (error
9073 (kill-region beg end)
9074 (org-table-create org-table-default-size)
9075 (error "Empty table - created default table")))
9076 ;; A list of empty string to fill any short rows on output
9077 (setq emptystrings (make-list maxfields ""))
9078 ;; Check for special formatting.
9079 (setq i -1)
9080 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
9081 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
9082 ;; Check if there is an explicit width specified
9083 (when (and org-table-limit-column-width narrow)
9084 (setq c column fmax nil)
9085 (while c
9086 (setq e (pop c))
9087 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
9088 (setq fmax (string-to-number (match-string 1 e)) c nil)))
9089 ;; Find fields that are wider than fmax, and shorten them
9090 (when fmax
9091 (loop for xx in column do
9092 (when (and (stringp xx)
9093 (> (org-string-width xx) fmax))
9094 (org-add-props xx nil
9095 'help-echo
9096 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
9097 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
9098 (unless (> f1 1)
9099 (error "Cannot narrow field starting with wide link \"%s\""
9100 (match-string 0 xx)))
9101 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
9102 (add-text-properties (- f1 2) f1
9103 (list 'display org-narrow-column-arrow)
9104 xx)))))
9105 ;; Get the maximum width for each column
9106 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
9107 ;; Get the fraction of numbers, to decide about alignment of the column
9108 (setq cnt 0 frac 0.0)
9109 (loop for x in column do
9110 (if (equal x "")
9112 (setq frac ( / (+ (* frac cnt)
9113 (if (string-match org-table-number-regexp x) 1 0))
9114 (setq cnt (1+ cnt))))))
9115 (push (>= frac org-table-number-fraction) typenums))
9116 (setq lengths (nreverse lengths) typenums (nreverse typenums))
9118 ;; Store the alignment of this table, for later editing of single fields
9119 (setq org-table-last-alignment typenums
9120 org-table-last-column-widths lengths)
9122 ;; With invisible characters, `format' does not get the field width right
9123 ;; So we need to make these fields wide by hand.
9124 (when links
9125 (loop for i from 0 upto (1- maxfields) do
9126 (setq len (nth i lengths))
9127 (loop for j from 0 upto (1- (length fields)) do
9128 (setq c (nthcdr i (car (nthcdr j fields))))
9129 (if (and (stringp (car c))
9130 (string-match org-bracket-link-regexp (car c))
9131 (< (org-string-width (car c)) len))
9132 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
9134 ;; Compute the formats needed for output of the table
9135 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
9136 (while (setq l (pop lengths))
9137 (setq ty (if (pop typenums) "" "-")) ; number types flushright
9138 (setq rfmt (concat rfmt (format rfmt1 ty l))
9139 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
9140 (setq rfmt (concat rfmt "\n")
9141 hfmt (concat (substring hfmt 0 -1) "|\n"))
9143 (setq new (mapconcat
9144 (lambda (l)
9145 (if l (apply 'format rfmt
9146 (append (pop fields) emptystrings))
9147 hfmt))
9148 lines ""))
9149 ;; Replace the old one
9150 (delete-region beg end)
9151 (move-marker end nil)
9152 (move-marker org-table-aligned-begin-marker (point))
9153 (insert new)
9154 (move-marker org-table-aligned-end-marker (point))
9155 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
9156 (goto-char org-table-aligned-begin-marker)
9157 (while (org-hide-wide-columns org-table-aligned-end-marker)))
9158 ;; Try to move to the old location (approximately)
9159 (goto-line linepos)
9160 (set-window-start (selected-window) winstart 'noforce)
9161 (org-table-goto-column colpos)
9162 (setq org-table-may-need-update nil)
9165 (defun org-string-width (s)
9166 "Compute width of string, ignoring invisible characters.
9167 This ignores character with invisibility property `org-link', and also
9168 characters with property `org-cwidth', because these will become invisible
9169 upon the next fontification round."
9170 (let (b)
9171 (when (or (eq t buffer-invisibility-spec)
9172 (assq 'org-link buffer-invisibility-spec))
9173 (while (setq b (text-property-any 0 (length s)
9174 'invisible 'org-link s))
9175 (setq s (concat (substring s 0 b)
9176 (substring s (or (next-single-property-change
9177 b 'invisible s) (length s)))))))
9178 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
9179 (setq s (concat (substring s 0 b)
9180 (substring s (or (next-single-property-change
9181 b 'org-cwidth s) (length s))))))
9182 (string-width s)))
9184 (defun org-table-begin (&optional table-type)
9185 "Find the beginning of the table and return its position.
9186 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
9187 (save-excursion
9188 (if (not (re-search-backward
9189 (if table-type org-table-any-border-regexp
9190 org-table-border-regexp)
9191 nil t))
9192 ; FIXME: OK to just use beginning-of-buffer?
9193 ; (error "Can't find beginning of table")
9194 (progn (goto-char (point-min)) (point))
9195 (goto-char (match-beginning 0))
9196 (beginning-of-line 2)
9197 (point))))
9199 (defun org-table-end (&optional table-type)
9200 "Find the end of the table and return its position.
9201 With argument TABLE-TYPE, go to the end of a table.el-type table."
9202 (save-excursion
9203 (if (not (re-search-forward
9204 (if table-type org-table-any-border-regexp
9205 org-table-border-regexp)
9206 nil t))
9207 (goto-char (point-max))
9208 (goto-char (match-beginning 0)))
9209 (point-marker)))
9211 (defun org-table-justify-field-maybe (&optional new)
9212 "Justify the current field, text to left, number to right.
9213 Optional argument NEW may specify text to replace the current field content."
9214 (cond
9215 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
9216 ((org-at-table-hline-p))
9217 ((and (not new)
9218 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
9219 (current-buffer)))
9220 (< (point) org-table-aligned-begin-marker)
9221 (>= (point) org-table-aligned-end-marker)))
9222 ;; This is not the same table, force a full re-align
9223 (setq org-table-may-need-update t))
9224 (t ;; realign the current field, based on previous full realign
9225 (let* ((pos (point)) s
9226 (col (org-table-current-column))
9227 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
9228 l f n o e)
9229 (when (> col 0)
9230 (skip-chars-backward "^|\n")
9231 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
9232 (progn
9233 (setq s (match-string 1)
9234 o (match-string 0)
9235 l (max 1 (- (match-end 0) (match-beginning 0) 3))
9236 e (not (= (match-beginning 2) (match-end 2))))
9237 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
9238 l (if e "|" (setq org-table-may-need-update t) ""))
9239 n (format f s))
9240 (if new
9241 (if (<= (length new) l) ;; FIXME: length -> str-width?
9242 (setq n (format f new t t)) ;; FIXME: t t?
9243 (setq n (concat new "|") org-table-may-need-update t)))
9244 (or (equal n o)
9245 (let (org-table-may-need-update)
9246 (replace-match n))))
9247 (setq org-table-may-need-update t))
9248 (goto-char pos))))))
9250 (defun org-table-next-field ()
9251 "Go to the next field in the current table, creating new lines as needed.
9252 Before doing so, re-align the table if necessary."
9253 (interactive)
9254 (org-table-maybe-eval-formula)
9255 (org-table-maybe-recalculate-line)
9256 (if (and org-table-automatic-realign
9257 org-table-may-need-update)
9258 (org-table-align))
9259 (let ((end (org-table-end)))
9260 (if (org-at-table-hline-p)
9261 (end-of-line 1))
9262 (condition-case nil
9263 (progn
9264 (re-search-forward "|" end)
9265 (if (looking-at "[ \t]*$")
9266 (re-search-forward "|" end))
9267 (if (and (looking-at "-")
9268 org-table-tab-jumps-over-hlines
9269 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
9270 (goto-char (match-beginning 1)))
9271 (if (looking-at "-")
9272 (progn
9273 (beginning-of-line 0)
9274 (org-table-insert-row 'below))
9275 (if (looking-at " ") (forward-char 1))))
9276 (error
9277 (org-table-insert-row 'below)))))
9279 (defun org-table-previous-field ()
9280 "Go to the previous field in the table.
9281 Before doing so, re-align the table if necessary."
9282 (interactive)
9283 (org-table-justify-field-maybe)
9284 (org-table-maybe-recalculate-line)
9285 (if (and org-table-automatic-realign
9286 org-table-may-need-update)
9287 (org-table-align))
9288 (if (org-at-table-hline-p)
9289 (end-of-line 1))
9290 (re-search-backward "|" (org-table-begin))
9291 (re-search-backward "|" (org-table-begin))
9292 (while (looking-at "|\\(-\\|[ \t]*$\\)")
9293 (re-search-backward "|" (org-table-begin)))
9294 (if (looking-at "| ?")
9295 (goto-char (match-end 0))))
9297 (defun org-table-next-row ()
9298 "Go to the next row (same column) in the current table.
9299 Before doing so, re-align the table if necessary."
9300 (interactive)
9301 (org-table-maybe-eval-formula)
9302 (org-table-maybe-recalculate-line)
9303 (if (or (looking-at "[ \t]*$")
9304 (save-excursion (skip-chars-backward " \t") (bolp)))
9305 (newline)
9306 (if (and org-table-automatic-realign
9307 org-table-may-need-update)
9308 (org-table-align))
9309 (let ((col (org-table-current-column)))
9310 (beginning-of-line 2)
9311 (if (or (not (org-at-table-p))
9312 (org-at-table-hline-p))
9313 (progn
9314 (beginning-of-line 0)
9315 (org-table-insert-row 'below)))
9316 (org-table-goto-column col)
9317 (skip-chars-backward "^|\n\r")
9318 (if (looking-at " ") (forward-char 1)))))
9320 (defun org-table-copy-down (n)
9321 "Copy a field down in the current column.
9322 If the field at the cursor is empty, copy into it the content of the nearest
9323 non-empty field above. With argument N, use the Nth non-empty field.
9324 If the current field is not empty, it is copied down to the next row, and
9325 the cursor is moved with it. Therefore, repeating this command causes the
9326 column to be filled row-by-row.
9327 If the variable `org-table-copy-increment' is non-nil and the field is an
9328 integer, it will be incremented while copying."
9329 (interactive "p")
9330 (let* ((colpos (org-table-current-column))
9331 (field (org-table-get-field))
9332 (non-empty (string-match "[^ \t]" field))
9333 (beg (org-table-begin))
9334 txt)
9335 (org-table-check-inside-data-field)
9336 (if non-empty
9337 (progn
9338 (setq txt (org-trim field))
9339 (org-table-next-row)
9340 (org-table-blank-field))
9341 (save-excursion
9342 (setq txt
9343 (catch 'exit
9344 (while (progn (beginning-of-line 1)
9345 (re-search-backward org-table-dataline-regexp
9346 beg t))
9347 (org-table-goto-column colpos t)
9348 (if (and (looking-at
9349 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9350 (= (setq n (1- n)) 0))
9351 (throw 'exit (match-string 1))))))))
9352 (if txt
9353 (progn
9354 (if (and org-table-copy-increment
9355 (string-match "^[0-9]+$" txt))
9356 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9357 (insert txt)
9358 (org-table-maybe-recalculate-line)
9359 (org-table-align))
9360 (error "No non-empty field found"))))
9362 (defun org-table-check-inside-data-field ()
9363 "Is point inside a table data field?
9364 I.e. not on a hline or before the first or after the last column?
9365 This actually throws an error, so it aborts the current command."
9366 (if (or (not (org-at-table-p))
9367 (= (org-table-current-column) 0)
9368 (org-at-table-hline-p)
9369 (looking-at "[ \t]*$"))
9370 (error "Not in table data field")))
9372 (defvar org-table-clip nil
9373 "Clipboard for table regions.")
9375 (defun org-table-blank-field ()
9376 "Blank the current table field or active region."
9377 (interactive)
9378 (org-table-check-inside-data-field)
9379 (if (and (interactive-p) (org-region-active-p))
9380 (let (org-table-clip)
9381 (org-table-cut-region (region-beginning) (region-end)))
9382 (skip-chars-backward "^|")
9383 (backward-char 1)
9384 (if (looking-at "|[^|\n]+")
9385 (let* ((pos (match-beginning 0))
9386 (match (match-string 0))
9387 (len (org-string-width match)))
9388 (replace-match (concat "|" (make-string (1- len) ?\ )))
9389 (goto-char (+ 2 pos))
9390 (substring match 1)))))
9392 (defun org-table-get-field (&optional n replace)
9393 "Return the value of the field in column N of current row.
9394 N defaults to current field.
9395 If REPLACE is a string, replace field with this value. The return value
9396 is always the old value."
9397 (and n (org-table-goto-column n))
9398 (skip-chars-backward "^|\n")
9399 (backward-char 1)
9400 (if (looking-at "|[^|\r\n]*")
9401 (let* ((pos (match-beginning 0))
9402 (val (buffer-substring (1+ pos) (match-end 0))))
9403 (if replace
9404 (replace-match (concat "|" replace)))
9405 (goto-char (min (point-at-eol) (+ 2 pos)))
9406 val)
9407 (forward-char 1) ""))
9409 (defun org-table-current-column ()
9410 "Find out which column we are in.
9411 When called interactively, column is also displayed in echo area."
9412 (interactive)
9413 (if (interactive-p) (org-table-check-inside-data-field))
9414 (save-excursion
9415 (let ((cnt 0) (pos (point)))
9416 (beginning-of-line 1)
9417 (while (search-forward "|" pos t)
9418 (setq cnt (1+ cnt)))
9419 (if (interactive-p) (message "This is table column %d" cnt))
9420 cnt)))
9422 (defun org-table-goto-column (n &optional on-delim force)
9423 "Move the cursor to the Nth column in the current table line.
9424 With optional argument ON-DELIM, stop with point before the left delimiter
9425 of the field.
9426 If there are less than N fields, just go to after the last delimiter.
9427 However, when FORCE is non-nil, create new columns if necessary."
9428 (interactive "p")
9429 (let ((pos (point-at-eol)))
9430 (beginning-of-line 1)
9431 (when (> n 0)
9432 (while (and (> (setq n (1- n)) -1)
9433 (or (search-forward "|" pos t)
9434 (and force
9435 (progn (end-of-line 1)
9436 (skip-chars-backward "^|")
9437 (insert " | "))))))
9438 ; (backward-char 2) t)))))
9439 (when (and force (not (looking-at ".*|")))
9440 (save-excursion (end-of-line 1) (insert " | ")))
9441 (if on-delim
9442 (backward-char 1)
9443 (if (looking-at " ") (forward-char 1))))))
9445 (defun org-at-table-p (&optional table-type)
9446 "Return t if the cursor is inside an org-type table.
9447 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9448 (if org-enable-table-editor
9449 (save-excursion
9450 (beginning-of-line 1)
9451 (looking-at (if table-type org-table-any-line-regexp
9452 org-table-line-regexp)))
9453 nil))
9455 (defun org-at-table.el-p ()
9456 "Return t if and only if we are at a table.el table."
9457 (and (org-at-table-p 'any)
9458 (save-excursion
9459 (goto-char (org-table-begin 'any))
9460 (looking-at org-table1-hline-regexp))))
9462 (defun org-table-recognize-table.el ()
9463 "If there is a table.el table nearby, recognize it and move into it."
9464 (if org-table-tab-recognizes-table.el
9465 (if (org-at-table.el-p)
9466 (progn
9467 (beginning-of-line 1)
9468 (if (looking-at org-table-dataline-regexp)
9470 (if (looking-at org-table1-hline-regexp)
9471 (progn
9472 (beginning-of-line 2)
9473 (if (looking-at org-table-any-border-regexp)
9474 (beginning-of-line -1)))))
9475 (if (re-search-forward "|" (org-table-end t) t)
9476 (progn
9477 (require 'table)
9478 (if (table--at-cell-p (point))
9480 (message "recognizing table.el table...")
9481 (table-recognize-table)
9482 (message "recognizing table.el table...done")))
9483 (error "This should not happen..."))
9485 nil)
9486 nil))
9488 (defun org-at-table-hline-p ()
9489 "Return t if the cursor is inside a hline in a table."
9490 (if org-enable-table-editor
9491 (save-excursion
9492 (beginning-of-line 1)
9493 (looking-at org-table-hline-regexp))
9494 nil))
9496 (defun org-table-insert-column ()
9497 "Insert a new column into the table."
9498 (interactive)
9499 (if (not (org-at-table-p))
9500 (error "Not at a table"))
9501 (org-table-find-dataline)
9502 (let* ((col (max 1 (org-table-current-column)))
9503 (beg (org-table-begin))
9504 (end (org-table-end))
9505 ;; Current cursor position
9506 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9507 (colpos col))
9508 (goto-char beg)
9509 (while (< (point) end)
9510 (if (org-at-table-hline-p)
9512 (org-table-goto-column col t)
9513 (insert "| "))
9514 (beginning-of-line 2))
9515 (move-marker end nil)
9516 (goto-line linepos)
9517 (org-table-goto-column colpos)
9518 (org-table-align)
9519 (org-table-modify-formulas 'insert col)))
9521 (defun org-table-find-dataline ()
9522 "Find a dataline in the current table, which is needed for column commands."
9523 (if (and (org-at-table-p)
9524 (not (org-at-table-hline-p)))
9526 (let ((col (current-column))
9527 (end (org-table-end)))
9528 (move-to-column col)
9529 (while (and (< (point) end)
9530 (or (not (= (current-column) col))
9531 (org-at-table-hline-p)))
9532 (beginning-of-line 2)
9533 (move-to-column col))
9534 (if (and (org-at-table-p)
9535 (not (org-at-table-hline-p)))
9537 (error
9538 "Please position cursor in a data line for column operations")))))
9540 (defun org-table-delete-column ()
9541 "Delete a column into the table."
9542 (interactive)
9543 (if (not (org-at-table-p))
9544 (error "Not at a table"))
9545 (org-table-find-dataline)
9546 (org-table-check-inside-data-field)
9547 (let* ((col (org-table-current-column))
9548 (beg (org-table-begin))
9549 (end (org-table-end))
9550 ;; Current cursor position
9551 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9552 (colpos col))
9553 (goto-char beg)
9554 (while (< (point) end)
9555 (if (org-at-table-hline-p)
9557 (org-table-goto-column col t)
9558 (and (looking-at "|[^|\n]+|")
9559 (replace-match "|")))
9560 (beginning-of-line 2))
9561 (move-marker end nil)
9562 (goto-line linepos)
9563 (org-table-goto-column colpos)
9564 (org-table-align)
9565 (org-table-modify-formulas 'remove col)))
9567 (defun org-table-move-column-right ()
9568 "Move column to the right."
9569 (interactive)
9570 (org-table-move-column nil))
9571 (defun org-table-move-column-left ()
9572 "Move column to the left."
9573 (interactive)
9574 (org-table-move-column 'left))
9576 (defun org-table-move-column (&optional left)
9577 "Move the current column to the right. With arg LEFT, move to the left."
9578 (interactive "P")
9579 (if (not (org-at-table-p))
9580 (error "Not at a table"))
9581 (org-table-find-dataline)
9582 (org-table-check-inside-data-field)
9583 (let* ((col (org-table-current-column))
9584 (col1 (if left (1- col) col))
9585 (beg (org-table-begin))
9586 (end (org-table-end))
9587 ;; Current cursor position
9588 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9589 (colpos (if left (1- col) (1+ col))))
9590 (if (and left (= col 1))
9591 (error "Cannot move column further left"))
9592 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9593 (error "Cannot move column further right"))
9594 (goto-char beg)
9595 (while (< (point) end)
9596 (if (org-at-table-hline-p)
9598 (org-table-goto-column col1 t)
9599 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9600 (replace-match "|\\2|\\1|")))
9601 (beginning-of-line 2))
9602 (move-marker end nil)
9603 (goto-line linepos)
9604 (org-table-goto-column colpos)
9605 (org-table-align)
9606 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9608 (defun org-table-move-row-down ()
9609 "Move table row down."
9610 (interactive)
9611 (org-table-move-row nil))
9612 (defun org-table-move-row-up ()
9613 "Move table row up."
9614 (interactive)
9615 (org-table-move-row 'up))
9617 (defun org-table-move-row (&optional up)
9618 "Move the current table line down. With arg UP, move it up."
9619 (interactive "P")
9620 (let ((col (current-column))
9621 (pos (point))
9622 (tonew (if up 0 2))
9623 txt)
9624 (beginning-of-line tonew)
9625 (if (not (org-at-table-p))
9626 (progn
9627 (goto-char pos)
9628 (error "Cannot move row further")))
9629 (goto-char pos)
9630 (beginning-of-line 1)
9631 (setq pos (point))
9632 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9633 (delete-region (point) (1+ (point-at-eol)))
9634 (beginning-of-line tonew)
9635 (insert txt)
9636 (beginning-of-line 0)
9637 (move-to-column col)))
9639 (defun org-table-insert-row (&optional arg)
9640 "Insert a new row above the current line into the table.
9641 With prefix ARG, insert below the current line."
9642 (interactive "P")
9643 (if (not (org-at-table-p))
9644 (error "Not at a table"))
9645 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9646 (new (org-table-clean-line line)))
9647 ;; Fix the first field if necessary
9648 (if (string-match "^[ \t]*| *[#$] *|" line)
9649 (setq new (replace-match (match-string 0 line) t t new)))
9650 (beginning-of-line (if arg 2 1))
9651 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9652 (beginning-of-line 0)
9653 (re-search-forward "| ?" (point-at-eol) t)
9654 (and org-table-may-need-update (org-table-align))))
9656 (defun org-table-insert-hline (&optional arg)
9657 "Insert a horizontal-line below the current line into the table.
9658 With prefix ARG, insert above the current line."
9659 (interactive "P")
9660 (if (not (org-at-table-p))
9661 (error "Not at a table"))
9662 (let ((line (org-table-clean-line
9663 (buffer-substring (point-at-bol) (point-at-eol))))
9664 (col (current-column)))
9665 (while (string-match "|\\( +\\)|" line)
9666 (setq line (replace-match
9667 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9668 ?-) "|") t t line)))
9669 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9670 (beginning-of-line (if arg 1 2))
9671 (insert line "\n")
9672 (beginning-of-line (if arg 1 -1))
9673 (move-to-column col)))
9675 (defun org-table-clean-line (s)
9676 "Convert a table line S into a string with only \"|\" and space.
9677 In particular, this does handle wide and invisible characters."
9678 (if (string-match "^[ \t]*|-" s)
9679 ;; It's a hline, just map the characters
9680 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9681 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9682 (setq s (replace-match
9683 (concat "|" (make-string (org-string-width (match-string 1 s))
9684 ?\ ) "|")
9685 t t s)))
9688 (defun org-table-kill-row ()
9689 "Delete the current row or horizontal line from the table."
9690 (interactive)
9691 (if (not (org-at-table-p))
9692 (error "Not at a table"))
9693 (let ((col (current-column)))
9694 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9695 (if (not (org-at-table-p)) (beginning-of-line 0))
9696 (move-to-column col)))
9698 (defun org-table-sort-lines (beg end numericp)
9699 "Sort table lines in region.
9700 Point and mark define the first and last line to include. Both point and
9701 mark should be in the column that is used for sorting. For example, to
9702 sort according to column 3, put the mark in the first line to sort, in
9703 table column 3. Put point into the last line to be included in the sorting,
9704 also in table column 3. The command will prompt for the sorting method
9705 \(n for numerical, a for alphanumeric)."
9706 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9707 (setq numericp (string-match "[nN]" numericp))
9708 (org-table-align) ;; Just to be safe
9709 (let* (bcol ecol cmp column lns)
9710 (goto-char beg)
9711 (org-table-check-inside-data-field)
9712 (setq column (org-table-current-column)
9713 beg (move-marker (make-marker) (point-at-bol)))
9714 (goto-char end)
9715 (org-table-check-inside-data-field)
9716 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9717 (untabify beg end)
9718 (goto-char beg)
9719 (org-table-goto-column column)
9720 (skip-chars-backward "^|")
9721 (setq bcol (current-column))
9722 (org-table-goto-column (1+ column))
9723 (skip-chars-backward "^|")
9724 (setq ecol (1- (current-column)))
9725 (setq cmp (if numericp
9726 (lambda (a b) (< (car a) (car b)))
9727 (lambda (a b) (string< (car a) (car b)))))
9728 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9729 (org-split-string (buffer-substring beg end) "\n")))
9730 (if numericp
9731 (setq lns (mapcar (lambda(x)
9732 (cons (string-to-number (car x)) (cdr x)))
9733 lns)))
9734 (delete-region beg end)
9735 (move-marker beg nil)
9736 (move-marker end nil)
9737 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9738 (message "%d lines sorted %s based on column %d"
9739 (length lns)
9740 (if numericp "numerically" "alphabetically") column)))
9742 (defun org-table-cut-region (beg end)
9743 "Copy region in table to the clipboard and blank all relevant fields."
9744 (interactive "r")
9745 (org-table-copy-region beg end 'cut))
9747 (defun org-table-copy-region (beg end &optional cut)
9748 "Copy rectangular region in table to clipboard.
9749 A special clipboard is used which can only be accessed
9750 with `org-table-paste-rectangle'."
9751 (interactive "rP")
9752 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9753 region cols
9754 (rpl (if cut " " nil)))
9755 (goto-char beg)
9756 (org-table-check-inside-data-field)
9757 (setq l01 (count-lines (point-min) (point))
9758 c01 (org-table-current-column))
9759 (goto-char end)
9760 (org-table-check-inside-data-field)
9761 (setq l02 (count-lines (point-min) (point))
9762 c02 (org-table-current-column))
9763 (setq l1 (min l01 l02) l2 (max l01 l02)
9764 c1 (min c01 c02) c2 (max c01 c02))
9765 (catch 'exit
9766 (while t
9767 (catch 'nextline
9768 (if (> l1 l2) (throw 'exit t))
9769 (goto-line l1)
9770 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9771 (setq cols nil ic1 c1 ic2 c2)
9772 (while (< ic1 (1+ ic2))
9773 (push (org-table-get-field ic1 rpl) cols)
9774 (setq ic1 (1+ ic1)))
9775 (push (nreverse cols) region)
9776 (setq l1 (1+ l1)))))
9777 (setq org-table-clip (nreverse region))
9778 (if cut (org-table-align))
9779 org-table-clip))
9781 (defun org-table-paste-rectangle ()
9782 "Paste a rectangular region into a table.
9783 The upper right corner ends up in the current field. All involved fields
9784 will be overwritten. If the rectangle does not fit into the present table,
9785 the table is enlarged as needed. The process ignores horizontal separator
9786 lines."
9787 (interactive)
9788 (unless (and org-table-clip (listp org-table-clip))
9789 (error "First cut/copy a region to paste!"))
9790 (org-table-check-inside-data-field)
9791 (let* ((clip org-table-clip)
9792 (line (count-lines (point-min) (point)))
9793 (col (org-table-current-column))
9794 (org-enable-table-editor t)
9795 (org-table-automatic-realign nil)
9796 c cols field)
9797 (while (setq cols (pop clip))
9798 (while (org-at-table-hline-p) (beginning-of-line 2))
9799 (if (not (org-at-table-p))
9800 (progn (end-of-line 0) (org-table-next-field)))
9801 (setq c col)
9802 (while (setq field (pop cols))
9803 (org-table-goto-column c nil 'force)
9804 (org-table-get-field nil field)
9805 (setq c (1+ c)))
9806 (beginning-of-line 2))
9807 (goto-line line)
9808 (org-table-goto-column col)
9809 (org-table-align)))
9811 (defun org-table-convert ()
9812 "Convert from `org-mode' table to table.el and back.
9813 Obviously, this only works within limits. When an Org-mode table is
9814 converted to table.el, all horizontal separator lines get lost, because
9815 table.el uses these as cell boundaries and has no notion of horizontal lines.
9816 A table.el table can be converted to an Org-mode table only if it does not
9817 do row or column spanning. Multiline cells will become multiple cells.
9818 Beware, Org-mode does not test if the table can be successfully converted - it
9819 blindly applies a recipe that works for simple tables."
9820 (interactive)
9821 (require 'table)
9822 (if (org-at-table.el-p)
9823 ;; convert to Org-mode table
9824 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9825 (end (move-marker (make-marker) (org-table-end t))))
9826 (table-unrecognize-region beg end)
9827 (goto-char beg)
9828 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9829 (replace-match ""))
9830 (goto-char beg))
9831 (if (org-at-table-p)
9832 ;; convert to table.el table
9833 (let ((beg (move-marker (make-marker) (org-table-begin)))
9834 (end (move-marker (make-marker) (org-table-end))))
9835 ;; first, get rid of all horizontal lines
9836 (goto-char beg)
9837 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9838 (replace-match ""))
9839 ;; insert a hline before first
9840 (goto-char beg)
9841 (org-table-insert-hline 'above)
9842 (beginning-of-line -1)
9843 ;; insert a hline after each line
9844 (while (progn (beginning-of-line 3) (< (point) end))
9845 (org-table-insert-hline))
9846 (goto-char beg)
9847 (setq end (move-marker end (org-table-end)))
9848 ;; replace "+" at beginning and ending of hlines
9849 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9850 (replace-match "\\1+-"))
9851 (goto-char beg)
9852 (while (re-search-forward "-|[ \t]*$" end t)
9853 (replace-match "-+"))
9854 (goto-char beg)))))
9856 (defun org-table-wrap-region (arg)
9857 "Wrap several fields in a column like a paragraph.
9858 This is useful if you'd like to spread the contents of a field over several
9859 lines, in order to keep the table compact.
9861 If there is an active region, and both point and mark are in the same column,
9862 the text in the column is wrapped to minimum width for the given number of
9863 lines. Generally, this makes the table more compact. A prefix ARG may be
9864 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9865 formats the selected text to two lines. If the region was longer than two
9866 lines, the remaining lines remain empty. A negative prefix argument reduces
9867 the current number of lines by that amount. The wrapped text is pasted back
9868 into the table. If you formatted it to more lines than it was before, fields
9869 further down in the table get overwritten - so you might need to make space in
9870 the table first.
9872 If there is no region, the current field is split at the cursor position and
9873 the text fragment to the right of the cursor is prepended to the field one
9874 line down.
9876 If there is no region, but you specify a prefix ARG, the current field gets
9877 blank, and the content is appended to the field above."
9878 (interactive "P")
9879 (org-table-check-inside-data-field)
9880 (if (org-region-active-p)
9881 ;; There is a region: fill as a paragraph
9882 (let ((beg (region-beginning))
9883 nlines)
9884 (org-table-cut-region (region-beginning) (region-end))
9885 (if (> (length (car org-table-clip)) 1)
9886 (error "Region must be limited to single column"))
9887 (setq nlines (if arg
9888 (if (< arg 1)
9889 (+ (length org-table-clip) arg)
9890 arg)
9891 (length org-table-clip)))
9892 (setq org-table-clip
9893 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9894 nil nlines)))
9895 (goto-char beg)
9896 (org-table-paste-rectangle))
9897 ;; No region, split the current field at point
9898 (if arg
9899 ;; combine with field above
9900 (let ((s (org-table-blank-field))
9901 (col (org-table-current-column)))
9902 (beginning-of-line 0)
9903 (while (org-at-table-hline-p) (beginning-of-line 0))
9904 (org-table-goto-column col)
9905 (skip-chars-forward "^|")
9906 (skip-chars-backward " ")
9907 (insert " " (org-trim s))
9908 (org-table-align))
9909 ;; split field
9910 (when (looking-at "\\([^|]+\\)+|")
9911 (let ((s (match-string 1)))
9912 (replace-match " |")
9913 (goto-char (match-beginning 0))
9914 (org-table-next-row)
9915 (insert (org-trim s) " ")
9916 (org-table-align))))))
9918 (defvar org-field-marker nil)
9920 (defun org-table-edit-field (arg)
9921 "Edit table field in a different window.
9922 This is mainly useful for fields that contain hidden parts.
9923 When called with a \\[universal-argument] prefix, just make the full field visible so that
9924 it can be edited in place."
9925 (interactive "P")
9926 (if arg
9927 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9928 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9929 (remove-text-properties b e '(org-cwidth t invisible t
9930 display t intangible t))
9931 (if (and (boundp 'font-lock-mode) font-lock-mode)
9932 (font-lock-fontify-block)))
9933 (let ((pos (move-marker (make-marker) (point)))
9934 (field (org-table-get-field))
9935 (cw (current-window-configuration))
9937 (switch-to-buffer-other-window "*Org tmp*")
9938 (erase-buffer)
9939 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9940 (org-mode)
9941 (goto-char (setq p (point-max)))
9942 (insert (org-trim field))
9943 (remove-text-properties p (point-max)
9944 '(invisible t org-cwidth t display t
9945 intangible t))
9946 (goto-char p)
9947 (set (make-local-variable 'org-finish-function)
9948 'org-table-finish-edit-field)
9949 (set (make-local-variable 'org-window-configuration) cw)
9950 (set (make-local-variable 'org-field-marker) pos)
9951 (message "Edit and finish with C-c C-c"))))
9953 (defun org-table-finish-edit-field ()
9954 "Finish editing a table data field.
9955 Remove all newline characters, insert the result into the table, realign
9956 the table and kill the editing buffer."
9957 (let ((pos org-field-marker)
9958 (cw org-window-configuration)
9959 (cb (current-buffer))
9960 text)
9961 (goto-char (point-min))
9962 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9963 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9964 (replace-match " "))
9965 (setq text (org-trim (buffer-string)))
9966 (set-window-configuration cw)
9967 (kill-buffer cb)
9968 (select-window (get-buffer-window (marker-buffer pos)))
9969 (goto-char pos)
9970 (move-marker pos nil)
9971 (org-table-check-inside-data-field)
9972 (org-table-get-field nil text)
9973 (org-table-align)
9974 (message "New field value inserted")))
9976 (defun org-trim (s)
9977 "Remove whitespace at beginning and end of string."
9978 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9979 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9982 (defun org-wrap (string &optional width lines)
9983 "Wrap string to either a number of lines, or a width in characters.
9984 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9985 that costs. If there is a word longer than WIDTH, the text is actually
9986 wrapped to the length of that word.
9987 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9988 many lines, whatever width that takes.
9989 The return value is a list of lines, without newlines at the end."
9990 (let* ((words (org-split-string string "[ \t\n]+"))
9991 (maxword (apply 'max (mapcar 'org-string-width words)))
9992 w ll)
9993 (cond (width
9994 (org-do-wrap words (max maxword width)))
9995 (lines
9996 (setq w maxword)
9997 (setq ll (org-do-wrap words maxword))
9998 (if (<= (length ll) lines)
10000 (setq ll words)
10001 (while (> (length ll) lines)
10002 (setq w (1+ w))
10003 (setq ll (org-do-wrap words w)))
10004 ll))
10005 (t (error "Cannot wrap this")))))
10008 (defun org-do-wrap (words width)
10009 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
10010 (let (lines line)
10011 (while words
10012 (setq line (pop words))
10013 (while (and words (< (+ (length line) (length (car words))) width))
10014 (setq line (concat line " " (pop words))))
10015 (setq lines (push line lines)))
10016 (nreverse lines)))
10018 (defun org-split-string (string &optional separators)
10019 "Splits STRING into substrings at SEPARATORS.
10020 No empty strings are returned if there are matches at the beginning
10021 and end of string."
10022 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
10023 (start 0)
10024 notfirst
10025 (list nil))
10026 (while (and (string-match rexp string
10027 (if (and notfirst
10028 (= start (match-beginning 0))
10029 (< start (length string)))
10030 (1+ start) start))
10031 (< (match-beginning 0) (length string)))
10032 (setq notfirst t)
10033 (or (eq (match-beginning 0) 0)
10034 (and (eq (match-beginning 0) (match-end 0))
10035 (eq (match-beginning 0) start))
10036 (setq list
10037 (cons (substring string start (match-beginning 0))
10038 list)))
10039 (setq start (match-end 0)))
10040 (or (eq start (length string))
10041 (setq list
10042 (cons (substring string start)
10043 list)))
10044 (nreverse list)))
10046 (defun org-table-map-tables (function)
10047 "Apply FUNCTION to the start of all tables in the buffer."
10048 (save-excursion
10049 (save-restriction
10050 (widen)
10051 (goto-char (point-min))
10052 (while (re-search-forward org-table-any-line-regexp nil t)
10053 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
10054 (beginning-of-line 1)
10055 (if (looking-at org-table-line-regexp)
10056 (save-excursion (funcall function)))
10057 (re-search-forward org-table-any-border-regexp nil 1))))
10058 (message "Mapping tables: done"))
10060 (defun org-table-sum (&optional beg end nlast)
10061 "Sum numbers in region of current table column.
10062 The result will be displayed in the echo area, and will be available
10063 as kill to be inserted with \\[yank].
10065 If there is an active region, it is interpreted as a rectangle and all
10066 numbers in that rectangle will be summed. If there is no active
10067 region and point is located in a table column, sum all numbers in that
10068 column.
10070 If at least one number looks like a time HH:MM or HH:MM:SS, all other
10071 numbers are assumed to be times as well (in decimal hours) and the
10072 numbers are added as such.
10074 If NLAST is a number, only the NLAST fields will actually be summed."
10075 (interactive)
10076 (save-excursion
10077 (let (col (timecnt 0) diff h m s org-table-clip)
10078 (cond
10079 ((and beg end)) ; beg and end given explicitly
10080 ((org-region-active-p)
10081 (setq beg (region-beginning) end (region-end)))
10083 (setq col (org-table-current-column))
10084 (goto-char (org-table-begin))
10085 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
10086 (error "No table data"))
10087 (org-table-goto-column col)
10088 ;not needed? (skip-chars-backward "^|")
10089 (setq beg (point))
10090 (goto-char (org-table-end))
10091 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
10092 (error "No table data"))
10093 (org-table-goto-column col)
10094 ;not needed? (skip-chars-forward "^|")
10095 (setq end (point))))
10096 (let* ((items (apply 'append (org-table-copy-region beg end)))
10097 (items1 (cond ((not nlast) items)
10098 ((>= nlast (length items)) items)
10099 (t (setq items (reverse items))
10100 (setcdr (nthcdr (1- nlast) items) nil)
10101 (nreverse items))))
10102 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
10103 items1)))
10104 (res (apply '+ numbers))
10105 (sres (if (= timecnt 0)
10106 (format "%g" res)
10107 (setq diff (* 3600 res)
10108 h (floor (/ diff 3600)) diff (mod diff 3600)
10109 m (floor (/ diff 60)) diff (mod diff 60)
10110 s diff)
10111 (format "%d:%02d:%02d" h m s))))
10112 (kill-new sres)
10113 (if (interactive-p)
10114 (message "%s"
10115 (substitute-command-keys
10116 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
10117 (length numbers) sres))))
10118 sres))))
10120 (defun org-table-get-number-for-summing (s)
10121 (let (n)
10122 (if (string-match "^ *|? *" s)
10123 (setq s (replace-match "" nil nil s)))
10124 (if (string-match " *|? *$" s)
10125 (setq s (replace-match "" nil nil s)))
10126 (setq n (string-to-number s))
10127 (cond
10128 ((and (string-match "0" s)
10129 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
10130 ((string-match "\\`[ \t]+\\'" s) nil)
10131 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
10132 (let ((h (string-to-number (or (match-string 1 s) "0")))
10133 (m (string-to-number (or (match-string 2 s) "0")))
10134 (s (string-to-number (or (match-string 4 s) "0"))))
10135 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
10136 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
10137 ((equal n 0) nil)
10138 (t n))))
10140 (defun org-table-get-vertical-vector (desc &optional tbeg col)
10141 "Get a calc vector from a column, accorting to descriptor DESC.
10142 Optional arguments TBEG and COL can give the beginning of the table and
10143 the current column, to avoid unnecessary parsing."
10144 (save-excursion
10145 (or tbeg (setq tbeg (org-table-begin)))
10146 (or col (setq col (org-table-current-column)))
10147 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
10148 (cond
10149 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
10150 (setq n1 (- (match-end 1) (match-beginning 1)))
10151 (if (match-beginning 3)
10152 (setq n2 (- (match-end 2) (match-beginning 3))))
10153 (setq n (if n2 (max n1 n2) n1))
10154 (setq n1 (if n2 (min n1 n2)))
10155 (setq nn n)
10156 (while (and (> nn 0)
10157 (re-search-backward org-table-hline-regexp tbeg t))
10158 (push (org-current-line) hline-list)
10159 (setq nn (1- nn)))
10160 (setq hline-list (nreverse hline-list))
10161 (goto-line (nth (1- n) hline-list))
10162 (when (re-search-forward org-table-dataline-regexp)
10163 (org-table-goto-column col)
10164 (setq beg (point)))
10165 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
10166 (when (re-search-backward org-table-dataline-regexp)
10167 (org-table-goto-column col)
10168 (setq end (point)))
10169 (setq l (apply 'append (org-table-copy-region beg end)))
10170 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
10171 (if (equal x "") "0" x))
10172 l ",") "]"))
10173 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
10174 (setq n1 (string-to-number (match-string 1 desc))
10175 n2 (string-to-number (match-string 2 desc)))
10176 (beginning-of-line 1)
10177 (save-excursion
10178 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
10179 (org-table-goto-column col)
10180 (setq beg (point))))
10181 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
10182 (org-table-goto-column col)
10183 (setq end (point)))
10184 (setq l (apply 'append (org-table-copy-region beg end)))
10185 (concat "[" (mapconcat
10186 (lambda (x) (setq x (org-trim x))
10187 (if (equal x "") "0" x))
10188 l ",") "]"))
10189 ((string-match "\\([0-9]+\\)" desc)
10190 (beginning-of-line 1)
10191 (when (re-search-backward org-table-dataline-regexp tbeg t
10192 (string-to-number (match-string 0 desc)))
10193 (org-table-goto-column col)
10194 (org-trim (org-table-get-field))))))))
10196 (defvar org-table-formula-history nil)
10198 (defvar org-table-column-names nil
10199 "Alist with column names, derived from the `!' line.")
10200 (defvar org-table-column-name-regexp nil
10201 "Regular expression matching the current column names.")
10202 (defvar org-table-local-parameters nil
10203 "Alist with parameter names, derived from the `$' line.")
10204 (defvar org-table-named-field-locations nil
10205 "Alist with locations of named fields.")
10207 (defun org-table-get-formula (&optional equation named)
10208 "Read a formula from the minibuffer, offer stored formula as default."
10209 (let* ((name (car (rassoc (list (org-current-line)
10210 (org-table-current-column))
10211 org-table-named-field-locations)))
10212 (scol (if named
10213 (if name name
10214 (error "Not in a named field"))
10215 (int-to-string (org-table-current-column))))
10216 (dummy (and name (not named)
10217 (not (y-or-n-p "Replace named-field formula with column equation? " ))
10218 (error "Abort")))
10219 (org-table-may-need-update nil)
10220 (stored-list (org-table-get-stored-formulas))
10221 (stored (cdr (assoc scol stored-list)))
10222 (eq (cond
10223 ((and stored equation (string-match "^ *=? *$" equation))
10224 stored)
10225 ((stringp equation)
10226 equation)
10227 (t (read-string
10228 (format "%s formula $%s=" (if named "Field" "Column") scol)
10229 (or stored "") 'org-table-formula-history
10230 ;stored
10231 ))))
10232 mustsave)
10233 (when (not (string-match "\\S-" eq))
10234 ;; remove formula
10235 (setq stored-list (delq (assoc scol stored-list) stored-list))
10236 (org-table-store-formulas stored-list)
10237 (error "Formula removed"))
10238 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
10239 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
10240 (if (and name (not named))
10241 ;; We set the column equation, delete the named one.
10242 (setq stored-list (delq (assoc name stored-list) stored-list)
10243 mustsave t))
10244 (if stored
10245 (setcdr (assoc scol stored-list) eq)
10246 (setq stored-list (cons (cons scol eq) stored-list)))
10247 (if (or mustsave (not (equal stored eq)))
10248 (org-table-store-formulas stored-list))
10249 eq))
10251 (defun org-table-store-formulas (alist)
10252 "Store the list of formulas below the current table."
10253 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
10254 (save-excursion
10255 (goto-char (org-table-end))
10256 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
10257 (delete-region (point) (match-end 0)))
10258 (insert "#+TBLFM: "
10259 (mapconcat (lambda (x)
10260 (concat "$" (car x) "=" (cdr x)))
10261 alist "::")
10262 "\n")))
10264 (defun org-table-get-stored-formulas ()
10265 "Return an alist with the t=stored formulas directly after current table."
10266 (interactive)
10267 (let (scol eq eq-alist strings string seen)
10268 (save-excursion
10269 (goto-char (org-table-end))
10270 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10271 (setq strings (org-split-string (match-string 2) " *:: *"))
10272 (while (setq string (pop strings))
10273 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
10274 (setq scol (match-string 1 string)
10275 eq (match-string 2 string)
10276 eq-alist (cons (cons scol eq) eq-alist))
10277 (if (member scol seen)
10278 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10279 (push scol seen))))))
10280 (nreverse eq-alist)))
10282 (defun org-table-modify-formulas (action &rest columns)
10283 "Modify the formulas stored below the current table.
10284 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
10285 expected, for the other actions only a single column number is needed."
10286 (let ((list (org-table-get-stored-formulas))
10287 (nmax (length (org-split-string
10288 (buffer-substring (point-at-bol) (point-at-eol))
10289 "|")))
10290 col col1 col2 scol si sc1 sc2)
10291 (cond
10292 ((null list)) ; No action needed if there are no stored formulas
10293 ((eq action 'remove)
10294 (setq col (car columns)
10295 scol (int-to-string col))
10296 (org-table-replace-in-formulas list scol "INVALID")
10297 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
10298 (loop for i from (1+ col) upto nmax by 1 do
10299 (setq si (int-to-string i))
10300 (org-table-replace-in-formulas list si (int-to-string (1- i)))
10301 (if (assoc si list) (setcar (assoc si list)
10302 (int-to-string (1- i))))))
10303 ((eq action 'insert)
10304 (setq col (car columns))
10305 (loop for i from nmax downto col by 1 do
10306 (setq si (int-to-string i))
10307 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
10308 (if (assoc si list) (setcar (assoc si list)
10309 (int-to-string (1+ i))))))
10310 ((eq action 'swap)
10311 (setq col1 (car columns) col2 (nth 1 columns)
10312 sc1 (int-to-string col1) sc2 (int-to-string col2))
10313 ;; Hopefully, ZqZtZ will never be a name in a table
10314 (org-table-replace-in-formulas list sc1 "ZqZtZ")
10315 (org-table-replace-in-formulas list sc2 sc1)
10316 (org-table-replace-in-formulas list "ZqZtZ" sc2)
10317 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
10318 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
10319 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
10320 (t (error "Invalid action in `org-table-modify-formulas'")))
10321 (if list (org-table-store-formulas list))))
10323 (defun org-table-replace-in-formulas (list s1 s2)
10324 (let (elt re s)
10325 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
10326 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10327 re (concat (regexp-quote s1) "\\>"))
10328 (while (setq elt (pop list))
10329 (setq s (cdr elt))
10330 (while (string-match re s)
10331 (setq s (replace-match s2 t t s)))
10332 (setcdr elt s))))
10334 (defun org-table-get-specials ()
10335 "Get the column names and local parameters for this table."
10336 (save-excursion
10337 (let ((beg (org-table-begin)) (end (org-table-end))
10338 names name fields fields1 field cnt c v line col)
10339 (setq org-table-column-names nil
10340 org-table-local-parameters nil
10341 org-table-named-field-locations nil)
10342 (goto-char beg)
10343 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10344 (setq names (org-split-string (match-string 1) " *| *")
10345 cnt 1)
10346 (while (setq name (pop names))
10347 (setq cnt (1+ cnt))
10348 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10349 (push (cons name (int-to-string cnt)) org-table-column-names))))
10350 (setq org-table-column-names (nreverse org-table-column-names))
10351 (setq org-table-column-name-regexp
10352 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10353 (goto-char beg)
10354 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10355 (setq fields (org-split-string (match-string 1) " *| *"))
10356 (while (setq field (pop fields))
10357 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10358 (push (cons (match-string 1 field) (match-string 2 field))
10359 org-table-local-parameters))))
10360 (goto-char beg)
10361 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10362 (setq c (match-string 1)
10363 fields (org-split-string (match-string 2) " *| *"))
10364 (save-excursion
10365 (beginning-of-line (if (equal c "_") 2 0))
10366 (setq line (org-current-line) col 1)
10367 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10368 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10369 (while (and fields1 (setq field (pop fields)))
10370 (setq v (pop fields1) col (1+ col))
10371 (when (and (stringp field) (stringp v)
10372 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10373 (push (cons field v) org-table-local-parameters)
10374 (push (list field line col) org-table-named-field-locations)))))))
10376 (defun org-this-word ()
10377 ;; Get the current word
10378 (save-excursion
10379 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10380 (end (progn (skip-chars-forward "^ \t\n") (point))))
10381 (buffer-substring-no-properties beg end))))
10383 (defun org-table-maybe-eval-formula ()
10384 "Check if the current field starts with \"=\" or \":=\".
10385 If yes, store the formula and apply it."
10386 ;; We already know we are in a table. Get field will only return a formula
10387 ;; when appropriate. It might return a separator line, but no problem.
10388 (when org-table-formula-evaluate-inline
10389 (let* ((field (org-trim (or (org-table-get-field) "")))
10390 named eq)
10391 (when (string-match "^:?=\\(.*\\)" field)
10392 (setq named (equal (string-to-char field) ?:)
10393 eq (match-string 1 field))
10394 (if (fboundp 'calc-eval)
10395 (org-table-eval-formula (if named '(4) nil) eq))))))
10397 (defvar org-recalc-commands nil
10398 "List of commands triggering the recalculation of a line.
10399 Will be filled automatically during use.")
10401 (defvar org-recalc-marks
10402 '((" " . "Unmarked: no special line, no automatic recalculation")
10403 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10404 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10405 ("!" . "Column name definition line. Reference in formula as $name.")
10406 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10407 ("_" . "Names for values in row below this one.")
10408 ("^" . "Names for values in row above this one.")))
10410 (defun org-table-rotate-recalc-marks (&optional newchar)
10411 "Rotate the recalculation mark in the first column.
10412 If in any row, the first field is not consistent with a mark,
10413 insert a new column for the markers.
10414 When there is an active region, change all the lines in the region,
10415 after prompting for the marking character.
10416 After each change, a message will be displayed indicating the meaning
10417 of the new mark."
10418 (interactive)
10419 (unless (org-at-table-p) (error "Not at a table"))
10420 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10421 (beg (org-table-begin))
10422 (end (org-table-end))
10423 (l (org-current-line))
10424 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10425 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10426 (have-col
10427 (save-excursion
10428 (goto-char beg)
10429 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10430 (col (org-table-current-column))
10431 (forcenew (car (assoc newchar org-recalc-marks)))
10432 epos new)
10433 (when l1
10434 (message "Change region to what mark? Type # * ! $ or SPC: ")
10435 (setq newchar (char-to-string (read-char-exclusive))
10436 forcenew (car (assoc newchar org-recalc-marks))))
10437 (if (and newchar (not forcenew))
10438 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10439 newchar))
10440 (if l1 (goto-line l1))
10441 (save-excursion
10442 (beginning-of-line 1)
10443 (unless (looking-at org-table-dataline-regexp)
10444 (error "Not at a table data line")))
10445 (unless have-col
10446 (org-table-goto-column 1)
10447 (org-table-insert-column)
10448 (org-table-goto-column (1+ col)))
10449 (setq epos (point-at-eol))
10450 (save-excursion
10451 (beginning-of-line 1)
10452 (org-table-get-field
10453 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10454 (concat " "
10455 (setq new (or forcenew
10456 (cadr (member (match-string 1) marks))))
10457 " ")
10458 " # ")))
10459 (if (and l1 l2)
10460 (progn
10461 (goto-line l1)
10462 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10463 (and (looking-at org-table-dataline-regexp)
10464 (org-table-get-field 1 (concat " " new " "))))
10465 (goto-line l1)))
10466 (if (not (= epos (point-at-eol))) (org-table-align))
10467 (goto-line l)
10468 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10470 (defun org-table-maybe-recalculate-line ()
10471 "Recompute the current line if marked for it, and if we haven't just done it."
10472 (interactive)
10473 (and org-table-allow-automatic-line-recalculation
10474 (not (and (memq last-command org-recalc-commands)
10475 (equal org-last-recalc-line (org-current-line))))
10476 (save-excursion (beginning-of-line 1)
10477 (looking-at org-table-auto-recalculate-regexp))
10478 (fboundp 'calc-eval)
10479 (org-table-recalculate) t))
10481 (defvar org-table-formula-debug nil
10482 "Non-nil means, debug table formulas.
10483 When nil, simply write \"#ERROR\" in corrupted fields.")
10485 (defvar modes)
10486 (defsubst org-set-calc-mode (var &optional value)
10487 (if (stringp var)
10488 (setq var (assoc var '(("D" calc-angle-mode deg)
10489 ("R" calc-angle-mode rad)
10490 ("F" calc-prefer-frac t)
10491 ("S" calc-symbolic-mode t)))
10492 value (nth 2 var) var (nth 1 var)))
10493 (if (memq var modes)
10494 (setcar (cdr (memq var modes)) value)
10495 (cons var (cons value modes)))
10496 modes)
10498 (defun org-table-eval-formula (&optional arg equation
10499 suppress-align suppress-const
10500 suppress-store)
10501 "Replace the table field value at the cursor by the result of a calculation.
10503 This function makes use of Dave Gillespie's Calc package, in my view the
10504 most exciting program ever written for GNU Emacs. So you need to have Calc
10505 installed in order to use this function.
10507 In a table, this command replaces the value in the current field with the
10508 result of a formula. It also installs the formula as the \"current\" column
10509 formula, by storing it in a special line below the table. When called
10510 with a `C-u' prefix, the current field must ba a named field, and the
10511 formula is installed as valid in only this specific field.
10513 When called, the command first prompts for a formula, which is read in
10514 the minibuffer. Previously entered formulas are available through the
10515 history list, and the last used formula is offered as a default.
10516 These stored formulas are adapted correctly when moving, inserting, or
10517 deleting columns with the corresponding commands.
10519 The formula can be any algebraic expression understood by the Calc package.
10520 For details, see the Org-mode manual.
10522 This function can also be called from Lisp programs and offers
10523 additional arguments: EQUATION can be the formula to apply. If this
10524 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10525 used to speed-up recursive calls by by-passing unnecessary aligns.
10526 SUPPRESS-CONST suppresses the interpretation of constants in the
10527 formula, assuming that this has been done already outside the function.
10528 SUPPRESS-STORE means the formula should not be stored, either because
10529 it is already stored, or because it is a modified equation that should
10530 not overwrite the stored one."
10531 (interactive "P")
10532 (require 'calc)
10533 (org-table-check-inside-data-field)
10534 (org-table-get-specials)
10535 (let* (fields
10536 (ndown (if (integerp arg) arg 1))
10537 (org-table-automatic-realign nil)
10538 (case-fold-search nil)
10539 (down (> ndown 1))
10540 (formula (if (and equation suppress-store)
10541 equation
10542 (org-table-get-formula equation (equal arg '(4)))))
10543 (n0 (org-table-current-column))
10544 (modes (copy-sequence org-calc-default-modes))
10545 n form fmt x ev orig c lispp)
10546 ;; Parse the format string. Since we have a lot of modes, this is
10547 ;; a lot of work. However, I think calc still uses most of the time.
10548 (if (string-match ";" formula)
10549 (let ((tmp (org-split-string formula ";")))
10550 (setq formula (car tmp)
10551 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10552 (nth 1 tmp)))
10553 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10554 (setq c (string-to-char (match-string 1 fmt))
10555 n (string-to-number (or (match-string 1 fmt) "")))
10556 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10557 (setq modes (org-set-calc-mode
10558 'calc-float-format
10559 (list (cdr (assoc c '((?n . float) (?f . fix)
10560 (?s . sci) (?e . eng))))
10561 n))))
10562 (setq fmt (replace-match "" t t fmt)))
10563 (while (string-match "[DRFS]" fmt)
10564 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10565 (setq fmt (replace-match "" t t fmt)))
10566 (unless (string-match "\\S-" fmt)
10567 (setq fmt nil))))
10568 (if (and (not suppress-const) org-table-formula-use-constants)
10569 (setq formula (org-table-formula-substitute-names formula)))
10570 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10571 (while (> ndown 0)
10572 (setq fields (org-split-string
10573 (buffer-substring
10574 (point-at-bol) (point-at-eol)) " *| *"))
10575 (if org-table-formula-numbers-only
10576 (setq fields (mapcar
10577 (lambda (x) (number-to-string (string-to-number x)))
10578 fields)))
10579 (setq ndown (1- ndown))
10580 (setq form (copy-sequence formula)
10581 lispp (equal (substring form 0 2) "'("))
10582 ;; Insert the references to fields in same row
10583 (while (string-match "\\$\\([0-9]+\\)?" form)
10584 (setq n (if (match-beginning 1)
10585 (string-to-number (match-string 1 form))
10587 x (nth (1- n) fields))
10588 (unless x (error "Invalid field specifier \"%s\""
10589 (match-string 0 form)))
10590 (if (equal x "") (setq x "0"))
10591 (setq form (replace-match
10592 (if lispp x (concat "(" x ")"))
10593 t t form)))
10594 ;; Insert ranges in current column
10595 (while (string-match "\\&[-I0-9]+" form)
10596 (setq form (replace-match
10597 (save-match-data
10598 (org-table-get-vertical-vector (match-string 0 form)
10599 nil n0))
10600 t t form)))
10601 ;; (setq ev (calc-eval (cons form modes)
10602 ;; FIXME (if org-table-formula-numbers-only 'num)))
10604 (if lispp
10605 (setq ev (eval (eval (read form)))
10606 ev (if (numberp ev) (number-to-string ev) ev))
10607 (setq ev (calc-eval (cons form modes)
10608 (if org-table-formula-numbers-only 'num))))
10610 (when org-table-formula-debug
10611 (with-output-to-temp-buffer "*Help*"
10612 (princ (format "Substitution history of formula
10613 Orig: %s
10614 $xyz-> %s
10615 $1-> %s\n" orig formula form))
10616 (if (listp ev)
10617 (princ (format " %s^\nError: %s"
10618 (make-string (car ev) ?\-) (nth 1 ev)))
10619 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10620 ev (or fmt "NONE")
10621 (if fmt (format fmt (string-to-number ev)) ev)))))
10622 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10623 (unless (and (interactive-p) (not ndown))
10624 (unless (let (inhibit-redisplay)
10625 (y-or-n-p "Debugging Formula. Continue to next? "))
10626 (org-table-align)
10627 (error "Abort"))
10628 (delete-window (get-buffer-window "*Help*"))
10629 (message "")))
10630 (if (listp ev) (setq fmt nil ev "#ERROR"))
10631 (org-table-justify-field-maybe
10632 (if fmt (format fmt (string-to-number ev)) ev))
10633 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10634 (call-interactively 'org-return)
10635 (setq ndown 0)))
10636 (and down (org-table-maybe-recalculate-line))
10637 (or suppress-align (and org-table-may-need-update
10638 (org-table-align)))))
10640 (defun org-table-recalculate (&optional all noalign)
10641 "Recalculate the current table line by applying all stored formulas.
10642 With prefix arg ALL, do this for all lines in the table."
10643 (interactive "P")
10644 (or (memq this-command org-recalc-commands)
10645 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10646 (unless (org-at-table-p) (error "Not at a table"))
10647 (org-table-get-specials)
10648 (let* ((eqlist (sort (org-table-get-stored-formulas)
10649 (lambda (a b) (string< (car a) (car b)))))
10650 (inhibit-redisplay t)
10651 (line-re org-table-dataline-regexp)
10652 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10653 (thiscol (org-table-current-column))
10654 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10655 ;; Insert constants in all formulas
10656 (setq eqlist
10657 (mapcar (lambda (x)
10658 (setcdr x (org-table-formula-substitute-names (cdr x)))
10660 eqlist))
10661 ;; Split the equation list
10662 (while (setq eq (pop eqlist))
10663 (if (<= (string-to-char (car eq)) ?9)
10664 (push eq eqlnum)
10665 (push eq eqlname)))
10666 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10667 (if all
10668 (progn
10669 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10670 (goto-char (setq beg (org-table-begin)))
10671 (if (re-search-forward org-table-calculate-mark-regexp end t)
10672 ;; This is a table with marked lines, only compute selected lines
10673 (setq line-re org-table-recalculate-regexp)
10674 ;; Move forward to the first non-header line
10675 (if (and (re-search-forward org-table-dataline-regexp end t)
10676 (re-search-forward org-table-hline-regexp end t)
10677 (re-search-forward org-table-dataline-regexp end t))
10678 (setq beg (match-beginning 0))
10679 nil))) ;; just leave beg where it is
10680 (setq beg (point-at-bol)
10681 end (move-marker (make-marker) (1+ (point-at-eol)))))
10682 (goto-char beg)
10683 (and all (message "Re-applying formulas to full table..."))
10684 (while (re-search-forward line-re end t)
10685 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10686 ;; Unprotected line, recalculate
10687 (and all (message "Re-applying formulas to full table...(line %d)"
10688 (setq cnt (1+ cnt))))
10689 (setq org-last-recalc-line (org-current-line))
10690 (setq eql eqlnum)
10691 (while (setq entry (pop eql))
10692 (goto-line org-last-recalc-line)
10693 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10694 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10695 (goto-line thisline)
10696 (org-table-goto-column thiscol)
10697 (or noalign (and org-table-may-need-update (org-table-align))
10698 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10699 ;; Now do the names fields
10700 (while (setq eq (pop eqlname))
10701 (setq name (car eq)
10702 a (assoc name org-table-named-field-locations))
10703 (when a
10704 (message "Re-applying formula to named field: %s" name)
10705 (goto-line (nth 1 a))
10706 (org-table-goto-column (nth 2 a))
10707 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10708 ;; back to initial position
10709 (goto-line thisline)
10710 (org-table-goto-column thiscol)
10711 (or noalign (and org-table-may-need-update (org-table-align))
10712 (and all (message "Re-applying formulas...done")))))
10714 (defun org-table-formula-substitute-names (f)
10715 "Replace $const with values in string F."
10716 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10717 ;; First, check for column names
10718 (while (setq start (string-match org-table-column-name-regexp f start))
10719 (setq start (1+ start))
10720 (setq a (assoc (match-string 1 f) org-table-column-names))
10721 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10722 ;; Expand ranges to vectors
10723 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10724 (setq n1 (string-to-number (match-string 1 f))
10725 n2 (string-to-number (match-string 2 f))
10726 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10727 s (concat "[($" (number-to-string (1- nn1)) ")"))
10728 (loop for i from nn1 upto nn2 do
10729 (setq s (concat s ",($" (int-to-string i) ")")))
10730 (setq s (concat s "]"))
10731 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10732 (setq f (replace-match s t t f)))
10733 ;; Parameters and constants
10734 (setq start 0)
10735 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10736 (setq start (1+ start))
10737 (if (setq a (save-match-data
10738 (org-table-get-constant (match-string 1 f))))
10739 (setq f (replace-match (concat "(" a ")") t t f))))
10740 (if org-table-formula-debug
10741 (put-text-property 0 (length f) :orig-formula f1 f))
10744 (defun org-table-get-constant (const)
10745 "Find the value for a parameter or constant in a formula.
10746 Parameters get priority."
10747 (or (cdr (assoc const org-table-local-parameters))
10748 (cdr (assoc const org-table-formula-constants))
10749 (and (fboundp 'constants-get) (constants-get const))
10750 "#UNDEFINED_NAME"))
10752 (defvar org-edit-formulas-map (make-sparse-keymap))
10753 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10754 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10755 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10757 (defvar org-pos)
10759 (defun org-table-edit-formulas ()
10760 "Edit the formulas of the current table in a separate buffer."
10761 (interactive)
10762 (unless (org-at-table-p)
10763 (error "Not at a table"))
10764 (org-table-get-specials)
10765 (let ((eql (org-table-get-stored-formulas))
10766 (pos (move-marker (make-marker) (point)))
10767 (wc (current-window-configuration))
10768 entry loc s)
10769 (switch-to-buffer-other-window "*Edit Formulas*")
10770 (erase-buffer)
10771 (fundamental-mode)
10772 (set (make-local-variable 'org-pos) pos)
10773 (set (make-local-variable 'org-window-configuration) wc)
10774 (use-local-map org-edit-formulas-map)
10775 (setq s "# Edit formulas and finish with `C-c C-c'.
10776 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10777 # Use `C-c ?' to get information about $name at point.
10778 # To cancel editing, press `C-c C-q'.\n")
10779 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10780 (insert s)
10781 (while (setq entry (pop eql))
10782 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10783 (setq s (format "# Named formula, referring to column %d in line %d\n"
10784 (nth 2 loc) (nth 1 loc)))
10785 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10786 (insert s))
10787 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10788 (remove-text-properties 0 (length s) '(face nil) s)
10789 (insert s))
10790 (goto-char (point-min))
10791 (message "Edit formulas and finish with `C-c C-c'.")))
10793 (defun org-show-variable ()
10794 "Show the location/value of the $ expression at point."
10795 (interactive)
10796 (let (var (pos org-pos) (win (selected-window)) e)
10797 (save-excursion
10798 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10799 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10800 (setq var (match-string 1))
10801 (error "No variable at point")))
10802 (cond
10803 ((setq e (assoc var org-table-named-field-locations))
10804 (switch-to-buffer-other-window (marker-buffer pos))
10805 (goto-line (nth 1 e))
10806 (org-table-goto-column (nth 2 e))
10807 (select-window win)
10808 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10809 ((setq e (assoc var org-table-column-names))
10810 (switch-to-buffer-other-window (marker-buffer pos))
10811 (goto-char pos)
10812 (goto-char (org-table-begin))
10813 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10814 (org-table-end) t)
10815 (progn
10816 (goto-char (match-beginning 1))
10817 (message "Named column (column %s)" (cdr e)))
10818 (error "Column name not found"))
10819 (select-window win))
10820 ((string-match "^[0-9]$" var)
10821 ;; column number
10822 (switch-to-buffer-other-window (marker-buffer pos))
10823 (goto-char pos)
10824 (goto-char (org-table-begin))
10825 (recenter 1)
10826 (if (re-search-forward org-table-dataline-regexp
10827 (org-table-end) t)
10828 (progn
10829 (goto-char (match-beginning 0))
10830 (org-table-goto-column (string-to-number var))
10831 (message "Column %s" var))
10832 (error "Column name not found"))
10833 (select-window win))
10834 ((setq e (assoc var org-table-local-parameters))
10835 (switch-to-buffer-other-window (marker-buffer pos))
10836 (goto-char pos)
10837 (goto-char (org-table-begin))
10838 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10839 (progn
10840 (goto-char (match-beginning 1))
10841 (message "Local parameter."))
10842 (error "Parameter not found"))
10843 (select-window win))
10845 (cond
10846 ((setq e (assoc var org-table-formula-constants))
10847 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10848 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10849 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10850 (t (error "Undefined name $%s" var)))))))
10852 (defun org-finish-edit-formulas (&optional arg)
10853 "Parse the buffer for formula definitions and install them.
10854 With prefix ARG, apply the new formulas to the table."
10855 (interactive "P")
10856 (let ((pos org-pos) eql)
10857 (goto-char (point-min))
10858 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10859 (push (cons (match-string 1) (match-string 2)) eql))
10860 (set-window-configuration org-window-configuration)
10861 (select-window (get-buffer-window (marker-buffer pos)))
10862 (goto-char pos)
10863 (unless (org-at-table-p)
10864 (error "Lost table position - cannot install formulae"))
10865 (org-table-store-formulas eql)
10866 (move-marker pos nil)
10867 (kill-buffer "*Edit Formulas*")
10868 (if arg
10869 (org-table-recalculate 'all)
10870 (message "New formulas installed - press C-u C-c C-c to apply."))))
10872 (defun org-abort-edit-formulas ()
10873 "Abort editing formulas, without installing the changes."
10874 (interactive)
10875 (let ((pos org-pos))
10876 (set-window-configuration org-window-configuration)
10877 (select-window (get-buffer-window (marker-buffer pos)))
10878 (goto-char pos)
10879 (message "Formula editing aborted without installing changes")))
10881 ;;; The orgtbl minor mode
10883 ;; Define a minor mode which can be used in other modes in order to
10884 ;; integrate the org-mode table editor.
10886 ;; This is really a hack, because the org-mode table editor uses several
10887 ;; keys which normally belong to the major mode, for example the TAB and
10888 ;; RET keys. Here is how it works: The minor mode defines all the keys
10889 ;; necessary to operate the table editor, but wraps the commands into a
10890 ;; function which tests if the cursor is currently inside a table. If that
10891 ;; is the case, the table editor command is executed. However, when any of
10892 ;; those keys is used outside a table, the function uses `key-binding' to
10893 ;; look up if the key has an associated command in another currently active
10894 ;; keymap (minor modes, major mode, global), and executes that command.
10895 ;; There might be problems if any of the keys used by the table editor is
10896 ;; otherwise used as a prefix key.
10898 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10899 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10900 ;; addresses this by checking explicitly for both bindings.
10902 ;; The optimized version (see variable `orgtbl-optimized') takes over
10903 ;; all keys which are bound to `self-insert-command' in the *global map*.
10904 ;; Some modes bind other commands to simple characters, for example
10905 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10906 ;; active, this binding is ignored inside tables and replaced with a
10907 ;; modified self-insert.
10909 (defvar orgtbl-mode nil
10910 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10911 table editor in arbitrary modes.")
10912 (make-variable-buffer-local 'orgtbl-mode)
10914 (defvar orgtbl-mode-map (make-keymap)
10915 "Keymap for `orgtbl-mode'.")
10917 ;;;###autoload
10918 (defun turn-on-orgtbl ()
10919 "Unconditionally turn on `orgtbl-mode'."
10920 (orgtbl-mode 1))
10922 ;;;###autoload
10923 (defun orgtbl-mode (&optional arg)
10924 "The `org-mode' table editor as a minor mode for use in other modes."
10925 (interactive)
10926 (if (eq major-mode 'org-mode)
10927 ;; Exit without error, in case some hook functions calls this
10928 ;; by accident in org-mode.
10929 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10930 (setq orgtbl-mode
10931 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10932 (if orgtbl-mode
10933 (progn
10934 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10935 ;; Make sure we are first in minor-mode-map-alist
10936 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10937 (and c (setq minor-mode-map-alist
10938 (cons c (delq c minor-mode-map-alist)))))
10939 (set (make-local-variable (quote org-table-may-need-update)) t)
10940 (org-add-hook 'before-change-functions 'org-before-change-function
10941 nil 'local)
10942 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10943 auto-fill-inhibit-regexp)
10944 (set (make-local-variable 'auto-fill-inhibit-regexp)
10945 (if auto-fill-inhibit-regexp
10946 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10947 "[ \t]*|"))
10948 (org-add-to-invisibility-spec '(org-cwidth))
10949 (easy-menu-add orgtbl-mode-menu)
10950 (run-hooks 'orgtbl-mode-hook))
10951 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10952 (org-cleanup-narrow-column-properties)
10953 (org-remove-from-invisibility-spec '(org-cwidth))
10954 (remove-hook 'before-change-functions 'org-before-change-function t)
10955 (easy-menu-remove orgtbl-mode-menu)
10956 (force-mode-line-update 'all))))
10958 (defun org-cleanup-narrow-column-properties ()
10959 "Remove all properties related to narrow-column invisibility."
10960 (let ((s 1))
10961 (while (setq s (text-property-any s (point-max)
10962 'display org-narrow-column-arrow))
10963 (remove-text-properties s (1+ s) '(display t)))
10964 (setq s 1)
10965 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10966 (remove-text-properties s (1+ s) '(org-cwidth t)))
10967 (setq s 1)
10968 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10969 (remove-text-properties s (1+ s) '(invisible t)))))
10971 ;; Install it as a minor mode.
10972 (put 'orgtbl-mode :included t)
10973 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10974 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10976 (defun orgtbl-make-binding (fun n &rest keys)
10977 "Create a function for binding in the table minor mode.
10978 FUN is the command to call inside a table. N is used to create a unique
10979 command name. KEYS are keys that should be checked in for a command
10980 to execute outside of tables."
10981 (eval
10982 (list 'defun
10983 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10984 '(arg)
10985 (concat "In tables, run `" (symbol-name fun) "'.\n"
10986 "Outside of tables, run the binding of `"
10987 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10988 "'.")
10989 '(interactive "p")
10990 (list 'if
10991 '(org-at-table-p)
10992 (list 'call-interactively (list 'quote fun))
10993 (list 'let '(orgtbl-mode)
10994 (list 'call-interactively
10995 (append '(or)
10996 (mapcar (lambda (k)
10997 (list 'key-binding k))
10998 keys)
10999 '('orgtbl-error))))))))
11001 (defun orgtbl-error ()
11002 "Error when there is no default binding for a table key."
11003 (interactive)
11004 (error "This key is has no function outside tables"))
11006 (defun orgtbl-setup ()
11007 "Setup orgtbl keymaps."
11008 (let ((nfunc 0)
11009 (bindings
11010 (list
11011 '([(meta shift left)] org-table-delete-column)
11012 '([(meta left)] org-table-move-column-left)
11013 '([(meta right)] org-table-move-column-right)
11014 '([(meta shift right)] org-table-insert-column)
11015 '([(meta shift up)] org-table-kill-row)
11016 '([(meta shift down)] org-table-insert-row)
11017 '([(meta up)] org-table-move-row-up)
11018 '([(meta down)] org-table-move-row-down)
11019 '("\C-c\C-w" org-table-cut-region)
11020 '("\C-c\M-w" org-table-copy-region)
11021 '("\C-c\C-y" org-table-paste-rectangle)
11022 '("\C-c-" org-table-insert-hline)
11023 ; '([(shift tab)] org-table-previous-field)
11024 '("\C-m" org-table-next-row)
11025 (list (org-key 'S-return) 'org-table-copy-down)
11026 '([(meta return)] org-table-wrap-region)
11027 '("\C-c\C-q" org-table-wrap-region)
11028 '("\C-c?" org-table-current-column)
11029 '("\C-c " org-table-blank-field)
11030 '("\C-c+" org-table-sum)
11031 '("\C-c=" org-table-eval-formula)
11032 '("\C-c'" org-table-edit-formulas)
11033 '("\C-c`" org-table-edit-field)
11034 '("\C-c*" org-table-recalculate)
11035 '("\C-c|" org-table-create-or-convert-from-region)
11036 '("\C-c^" org-table-sort-lines)
11037 '([(control ?#)] org-table-rotate-recalc-marks)))
11038 elt key fun cmd)
11039 (while (setq elt (pop bindings))
11040 (setq nfunc (1+ nfunc))
11041 (setq key (car elt)
11042 fun (nth 1 elt)
11043 cmd (orgtbl-make-binding fun nfunc key))
11044 (define-key orgtbl-mode-map key cmd))
11045 ;; Special treatment needed for TAB and RET
11046 (define-key orgtbl-mode-map [(return)]
11047 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11048 (define-key orgtbl-mode-map "\C-m"
11049 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11050 (define-key orgtbl-mode-map [(tab)]
11051 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11052 (define-key orgtbl-mode-map "\C-i"
11053 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
11054 (define-key orgtbl-mode-map "\C-i"
11055 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
11056 (define-key orgtbl-mode-map "\C-c\C-c"
11057 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
11058 (when orgtbl-optimized
11059 ;; If the user wants maximum table support, we need to hijack
11060 ;; some standard editing functions
11061 (org-remap orgtbl-mode-map
11062 'self-insert-command 'orgtbl-self-insert-command
11063 'delete-char 'org-delete-char
11064 'delete-backward-char 'org-delete-backward-char)
11065 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
11066 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11067 '("OrgTbl"
11068 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11069 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11070 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11071 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11072 "--"
11073 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11074 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11075 ["Copy Field from Above"
11076 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11077 "--"
11078 ("Column"
11079 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11080 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11081 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11082 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
11083 "--"
11084 ["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])
11085 ("Row"
11086 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11087 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11088 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11089 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11090 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11091 "--"
11092 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11093 ("Rectangle"
11094 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11095 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11096 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11097 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11098 "--"
11099 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11100 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11101 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11102 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11103 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11104 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11105 ["Sum Column/Rectangle" org-table-sum
11106 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11107 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11108 ["Debug Formulas"
11109 (setq org-table-formula-debug (not org-table-formula-debug))
11110 :style toggle :selected org-table-formula-debug]
11114 (defun orgtbl-tab (arg)
11115 "Justification and field motion for `orgtbl-mode'."
11116 (interactive "P")
11117 (if arg (org-table-edit-field t)
11118 (org-table-justify-field-maybe)
11119 (org-table-next-field)))
11121 (defun orgtbl-ret ()
11122 "Justification and field motion for `orgtbl-mode'."
11123 (interactive)
11124 (org-table-justify-field-maybe)
11125 (org-table-next-row))
11127 (defun orgtbl-self-insert-command (N)
11128 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11129 If the cursor is in a table looking at whitespace, the whitespace is
11130 overwritten, and the table is not marked as requiring realignment."
11131 (interactive "p")
11132 (if (and (org-at-table-p)
11134 (and org-table-auto-blank-field
11135 (member last-command
11136 '(orgtbl-hijacker-command-100
11137 orgtbl-hijacker-command-101
11138 orgtbl-hijacker-command-102
11139 orgtbl-hijacker-command-103
11140 orgtbl-hijacker-command-104
11141 orgtbl-hijacker-command-105))
11142 (org-table-blank-field))
11144 (eq N 1)
11145 (looking-at "[^|\n]* +|"))
11146 (let (org-table-may-need-update)
11147 (goto-char (1- (match-end 0)))
11148 (delete-backward-char 1)
11149 (goto-char (match-beginning 0))
11150 (self-insert-command N))
11151 (setq org-table-may-need-update t)
11152 (let (orgtbl-mode)
11153 (call-interactively (key-binding (vector last-input-event))))))
11155 (defun org-force-self-insert (N)
11156 "Needed to enforce self-insert under remapping."
11157 (interactive "p")
11158 (self-insert-command N))
11160 ;;; Exporting
11162 (defconst org-level-max 20)
11164 (defvar org-export-html-preamble nil
11165 "Preamble, to be inserted just after <body>. Set by publishing functions.")
11166 (defvar org-export-html-postamble nil
11167 "Preamble, to be inserted just before </body>. Set by publishing functions.")
11168 (defvar org-export-html-auto-preamble t
11169 "Should default preamble be inserted? Set by publishing functions.")
11170 (defvar org-export-html-auto-postamble t
11171 "Should default postamble be inserted? Set by publishing functions.")
11173 (defconst org-export-plist-vars
11174 '((:language . org-export-default-language)
11175 (:headline-levels . org-export-headline-levels)
11176 (:section-numbers . org-export-with-section-numbers)
11177 (:table-of-contents . org-export-with-toc)
11178 (:emphasize . org-export-with-emphasize)
11179 (:sub-superscript . org-export-with-sub-superscripts)
11180 (:TeX-macros . org-export-with-TeX-macros)
11181 (:fixed-width . org-export-with-fixed-width)
11182 (:tables . org-export-with-tables)
11183 (:table-auto-headline . org-export-highlight-first-table-line)
11184 (:style . org-export-html-style)
11185 (:convert-org-links . org-export-html-link-org-files-as-html)
11186 (:inline-images . org-export-html-inline-images)
11187 (:expand-quoted-html . org-export-html-expand)
11188 (:timestamp . org-export-html-with-timestamp)
11189 (:publishing-directory . org-export-publishing-directory)
11190 (:preamble . org-export-html-preamble)
11191 (:postamble . org-export-html-postamble)
11192 (:auto-preamble . org-export-html-auto-preamble)
11193 (:auto-postamble . org-export-html-auto-postamble)
11194 (:author . user-full-name)
11195 (:email . user-mail-address)))
11197 (defun org-default-export-plist ()
11198 "Return the property list with default settings for the export variables."
11199 (let ((l org-export-plist-vars) rtn e)
11200 (while (setq e (pop l))
11201 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
11202 rtn))
11204 (defun org-infile-export-plist ()
11205 "Return the property list with file-local settings for export."
11206 (save-excursion
11207 (goto-char 0)
11208 (let ((re (org-make-options-regexp
11209 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11210 (text nil)
11211 p key val text options)
11212 (while (re-search-forward re nil t)
11213 (setq key (org-match-string-no-properties 1)
11214 val (org-match-string-no-properties 2))
11215 (cond
11216 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
11217 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
11218 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
11219 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
11220 ((string-equal key "TEXT")
11221 (setq text (if text (concat text "\n" val) val)))
11222 ((string-equal key "OPTIONS") (setq options val))))
11223 (setq p (plist-put p :text text))
11224 (when options
11225 (let ((op '(("H" . :headline-levels)
11226 ("num" . :section-numbers)
11227 ("toc" . :table-of-contents)
11228 ("\\n" . :preserve-breaks)
11229 ("@" . :expand-quoted-html)
11230 (":" . :fixed-width)
11231 ("|" . :tables)
11232 ("^" . :sub-superscript)
11233 ("*" . :emphasize)
11234 ("TeX" . :TeX-macros)))
11236 (while (setq o (pop op))
11237 (if (string-match (concat (regexp-quote (car o))
11238 ":\\([^ \t\n\r;,.]*\\)")
11239 options)
11240 (setq p (plist-put p (cdr o)
11241 (car (read-from-string
11242 (match-string 1 options)))))))))
11243 p)))
11245 (defun org-combine-plists (&rest plists)
11246 "Create a single property list from all plists in PLISTS.
11247 The process starts by copying the last list, and then setting properties
11248 from the other lists. Settings in the first list are the most significant
11249 ones and overrule settings in the other lists."
11250 (let ((rtn (copy-sequence (pop plists)))
11251 p v ls)
11252 (while plists
11253 (setq ls (pop plists))
11254 (while ls
11255 (setq p (pop ls) v (pop ls))
11256 (setq rtn (plist-put rtn p v))))
11257 rtn))
11259 (defun org-export-find-first-heading-line (list)
11260 "Remove all lines from LIST which are before the first headline."
11261 (let ((orig-list list)
11262 (re (concat "^" outline-regexp)))
11263 (while (and list
11264 (not (string-match re (car list))))
11265 (pop list))
11266 (or list orig-list)))
11268 (defun org-skip-comments (lines)
11269 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
11270 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
11271 (re2 "^\\(\\*+\\)[ \t\n\r]")
11272 rtn line level)
11273 (while (setq line (pop lines))
11274 (cond
11275 ((and (string-match re1 line)
11276 (setq level (- (match-end 1) (match-beginning 1))))
11277 ;; Beginning of a COMMENT subtree. Skip it.
11278 (while (and (setq line (pop lines))
11279 (or (not (string-match re2 line))
11280 (> (- (match-end 1) (match-beginning 1)) level))))
11281 (setq lines (cons line lines)))
11282 ((string-match "^#" line)
11283 ;; an ordinary comment line
11285 ((and org-export-table-remove-special-lines
11286 (string-match "^[ \t]*| *[!_^] *|" line))
11287 ;; a special table line that should be removed
11289 (t (setq rtn (cons line rtn)))))
11290 (nreverse rtn)))
11292 ;; ASCII
11294 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
11295 "Characters for underlining headings in ASCII export.")
11297 (defconst org-html-entities
11298 '(("nbsp")
11299 ("iexcl")
11300 ("cent")
11301 ("pound")
11302 ("curren")
11303 ("yen")
11304 ("brvbar")
11305 ("sect")
11306 ("uml")
11307 ("copy")
11308 ("ordf")
11309 ("laquo")
11310 ("not")
11311 ("shy")
11312 ("reg")
11313 ("macr")
11314 ("deg")
11315 ("plusmn")
11316 ("sup2")
11317 ("sup3")
11318 ("acute")
11319 ("micro")
11320 ("para")
11321 ("middot")
11322 ("odot"."o")
11323 ("star"."*")
11324 ("cedil")
11325 ("sup1")
11326 ("ordm")
11327 ("raquo")
11328 ("frac14")
11329 ("frac12")
11330 ("frac34")
11331 ("iquest")
11332 ("Agrave")
11333 ("Aacute")
11334 ("Acirc")
11335 ("Atilde")
11336 ("Auml")
11337 ("Aring") ("AA"."&Aring;")
11338 ("AElig")
11339 ("Ccedil")
11340 ("Egrave")
11341 ("Eacute")
11342 ("Ecirc")
11343 ("Euml")
11344 ("Igrave")
11345 ("Iacute")
11346 ("Icirc")
11347 ("Iuml")
11348 ("ETH")
11349 ("Ntilde")
11350 ("Ograve")
11351 ("Oacute")
11352 ("Ocirc")
11353 ("Otilde")
11354 ("Ouml")
11355 ("times")
11356 ("Oslash")
11357 ("Ugrave")
11358 ("Uacute")
11359 ("Ucirc")
11360 ("Uuml")
11361 ("Yacute")
11362 ("THORN")
11363 ("szlig")
11364 ("agrave")
11365 ("aacute")
11366 ("acirc")
11367 ("atilde")
11368 ("auml")
11369 ("aring")
11370 ("aelig")
11371 ("ccedil")
11372 ("egrave")
11373 ("eacute")
11374 ("ecirc")
11375 ("euml")
11376 ("igrave")
11377 ("iacute")
11378 ("icirc")
11379 ("iuml")
11380 ("eth")
11381 ("ntilde")
11382 ("ograve")
11383 ("oacute")
11384 ("ocirc")
11385 ("otilde")
11386 ("ouml")
11387 ("divide")
11388 ("oslash")
11389 ("ugrave")
11390 ("uacute")
11391 ("ucirc")
11392 ("uuml")
11393 ("yacute")
11394 ("thorn")
11395 ("yuml")
11396 ("fnof")
11397 ("Alpha")
11398 ("Beta")
11399 ("Gamma")
11400 ("Delta")
11401 ("Epsilon")
11402 ("Zeta")
11403 ("Eta")
11404 ("Theta")
11405 ("Iota")
11406 ("Kappa")
11407 ("Lambda")
11408 ("Mu")
11409 ("Nu")
11410 ("Xi")
11411 ("Omicron")
11412 ("Pi")
11413 ("Rho")
11414 ("Sigma")
11415 ("Tau")
11416 ("Upsilon")
11417 ("Phi")
11418 ("Chi")
11419 ("Psi")
11420 ("Omega")
11421 ("alpha")
11422 ("beta")
11423 ("gamma")
11424 ("delta")
11425 ("epsilon")
11426 ("varepsilon"."&epsilon;")
11427 ("zeta")
11428 ("eta")
11429 ("theta")
11430 ("iota")
11431 ("kappa")
11432 ("lambda")
11433 ("mu")
11434 ("nu")
11435 ("xi")
11436 ("omicron")
11437 ("pi")
11438 ("rho")
11439 ("sigmaf") ("varsigma"."&sigmaf;")
11440 ("sigma")
11441 ("tau")
11442 ("upsilon")
11443 ("phi")
11444 ("chi")
11445 ("psi")
11446 ("omega")
11447 ("thetasym") ("vartheta"."&thetasym;")
11448 ("upsih")
11449 ("piv")
11450 ("bull") ("bullet"."&bull;")
11451 ("hellip") ("dots"."&hellip;")
11452 ("prime")
11453 ("Prime")
11454 ("oline")
11455 ("frasl")
11456 ("weierp")
11457 ("image")
11458 ("real")
11459 ("trade")
11460 ("alefsym")
11461 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
11462 ("uarr") ("uparrow"."&uarr;")
11463 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
11464 ("darr")("downarrow"."&darr;")
11465 ("harr") ("leftrightarrow"."&harr;")
11466 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
11467 ("lArr") ("Leftarrow"."&lArr;")
11468 ("uArr") ("Uparrow"."&uArr;")
11469 ("rArr") ("Rightarrow"."&rArr;")
11470 ("dArr") ("Downarrow"."&dArr;")
11471 ("hArr") ("Leftrightarrow"."&hArr;")
11472 ("forall")
11473 ("part") ("partial"."&part;")
11474 ("exist") ("exists"."&exist;")
11475 ("empty") ("emptyset"."&empty;")
11476 ("nabla")
11477 ("isin") ("in"."&isin;")
11478 ("notin")
11479 ("ni")
11480 ("prod")
11481 ("sum")
11482 ("minus")
11483 ("lowast") ("ast"."&lowast;")
11484 ("radic")
11485 ("prop") ("proptp"."&prop;")
11486 ("infin") ("infty"."&infin;")
11487 ("ang") ("angle"."&ang;")
11488 ("and") ("vee"."&and;")
11489 ("or") ("wedge"."&or;")
11490 ("cap")
11491 ("cup")
11492 ("int")
11493 ("there4")
11494 ("sim")
11495 ("cong") ("simeq"."&cong;")
11496 ("asymp")("approx"."&asymp;")
11497 ("ne") ("neq"."&ne;")
11498 ("equiv")
11499 ("le")
11500 ("ge")
11501 ("sub") ("subset"."&sub;")
11502 ("sup") ("supset"."&sup;")
11503 ("nsub")
11504 ("sube")
11505 ("supe")
11506 ("oplus")
11507 ("otimes")
11508 ("perp")
11509 ("sdot") ("cdot"."&sdot;")
11510 ("lceil")
11511 ("rceil")
11512 ("lfloor")
11513 ("rfloor")
11514 ("lang")
11515 ("rang")
11516 ("loz") ("Diamond"."&loz;")
11517 ("spades") ("spadesuit"."&spades;")
11518 ("clubs") ("clubsuit"."&clubs;")
11519 ("hearts") ("diamondsuit"."&hearts;")
11520 ("diams") ("diamondsuit"."&diams;")
11521 ("quot")
11522 ("amp")
11523 ("lt")
11524 ("gt")
11525 ("OElig")
11526 ("oelig")
11527 ("Scaron")
11528 ("scaron")
11529 ("Yuml")
11530 ("circ")
11531 ("tilde")
11532 ("ensp")
11533 ("emsp")
11534 ("thinsp")
11535 ("zwnj")
11536 ("zwj")
11537 ("lrm")
11538 ("rlm")
11539 ("ndash")
11540 ("mdash")
11541 ("lsquo")
11542 ("rsquo")
11543 ("sbquo")
11544 ("ldquo")
11545 ("rdquo")
11546 ("bdquo")
11547 ("dagger")
11548 ("Dagger")
11549 ("permil")
11550 ("lsaquo")
11551 ("rsaquo")
11552 ("euro")
11554 ("arccos"."arccos")
11555 ("arcsin"."arcsin")
11556 ("arctan"."arctan")
11557 ("arg"."arg")
11558 ("cos"."cos")
11559 ("cosh"."cosh")
11560 ("cot"."cot")
11561 ("coth"."coth")
11562 ("csc"."csc")
11563 ("deg"."deg")
11564 ("det"."det")
11565 ("dim"."dim")
11566 ("exp"."exp")
11567 ("gcd"."gcd")
11568 ("hom"."hom")
11569 ("inf"."inf")
11570 ("ker"."ker")
11571 ("lg"."lg")
11572 ("lim"."lim")
11573 ("liminf"."liminf")
11574 ("limsup"."limsup")
11575 ("ln"."ln")
11576 ("log"."log")
11577 ("max"."max")
11578 ("min"."min")
11579 ("Pr"."Pr")
11580 ("sec"."sec")
11581 ("sin"."sin")
11582 ("sinh"."sinh")
11583 ("sup"."sup")
11584 ("tan"."tan")
11585 ("tanh"."tanh")
11587 "Entities for TeX->HTML translation.
11588 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11589 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11590 In that case, \"\\ent\" will be translated to \"&other;\".
11591 The list contains HTML entities for Latin-1, Greek and other symbols.
11592 It is supplemented by a number of commonly used TeX macros with appropriate
11593 translations. There is currently no way for users to extend this.")
11595 (defun org-cleaned-string-for-export (string)
11596 "Cleanup a buffer substring so that links can be created safely."
11597 (interactive)
11598 (let* ((cb (current-buffer))
11599 (re-radio (and org-target-link-regexp
11600 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11601 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11602 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11603 rtn)
11604 (save-excursion
11605 (set-buffer (get-buffer-create " org-mode-tmp"))
11606 (erase-buffer)
11607 (insert string)
11608 (org-mode)
11609 ;; Find targets in comments and move them out of comments,
11610 ;; but mark them as targets that should be invisible
11611 (goto-char (point-min))
11612 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11613 (replace-match "\\1(INVISIBLE)"))
11614 ;; Find matches for radio targets and turn them into internal links
11615 (goto-char (point-min))
11616 (when re-radio
11617 (while (re-search-forward re-radio nil t)
11618 (replace-match "\\1[[\\2]]")))
11619 ;; Find all links that contain a newline and put them into a single line
11620 (goto-char (point-min))
11621 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11622 (replace-match "\\1 \\3")
11623 (goto-char (match-beginning 0)))
11624 ;; Normalize links: Convert angle and plain links into bracket links
11625 (goto-char (point-min))
11626 (while (re-search-forward re-plain-link nil t)
11627 (replace-match
11628 (concat
11629 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11630 t t))
11631 (goto-char (point-min))
11632 (while (re-search-forward re-angle-link nil t)
11633 (replace-match
11634 (concat
11635 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11636 t t))
11638 ;; Remove comments
11639 (goto-char (point-min))
11640 (while (re-search-forward "^#.*\n?" nil t)
11641 (replace-match ""))
11642 (setq rtn (buffer-string)))
11643 (kill-buffer " org-mode-tmp")
11644 rtn))
11646 (defun org-solidify-link-text (s &optional alist)
11647 "Take link text and make a safe target out of it."
11648 (save-match-data
11649 (let* ((rtn
11650 (mapconcat
11651 'identity
11652 (org-split-string s "[ \t\r\n]+") "--"))
11653 (a (assoc rtn alist)))
11654 (or (cdr a) rtn))))
11656 (defun org-convert-to-odd-levels ()
11657 "Convert an org-mode file with all levels allowed to one with odd levels.
11658 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11659 level 5 etc."
11660 (interactive)
11661 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11662 (let ((org-odd-levels-only nil) n)
11663 (save-excursion
11664 (goto-char (point-min))
11665 (while (re-search-forward "^\\*\\*+" nil t)
11666 (setq n (1- (length (match-string 0))))
11667 (while (>= (setq n (1- n)) 0)
11668 (org-demote))
11669 (end-of-line 1))))))
11672 (defun org-convert-to-oddeven-levels ()
11673 "Convert an org-mode file with only odd levels to one with odd and even levels.
11674 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11675 section with an even level, conversion would destroy the structure of the file. An error
11676 is signaled in this case."
11677 (interactive)
11678 (goto-char (point-min))
11679 ;; First check if there are no even levels
11680 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11681 (org-show-hierarchy-above)
11682 (error "Not all levels are odd in this file. Conversion not possible."))
11683 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11684 (let ((org-odd-levels-only nil) n)
11685 (save-excursion
11686 (goto-char (point-min))
11687 (while (re-search-forward "^\\*\\*+" nil t)
11688 (setq n (/ (length (match-string 0)) 2))
11689 (while (>= (setq n (1- n)) 0)
11690 (org-promote))
11691 (end-of-line 1))))))
11693 (defun org-tr-level (n)
11694 "Make N odd if required."
11695 (if org-odd-levels-only (1+ (/ n 2)) n))
11697 (defvar org-last-level nil) ; dynamically scoped variable
11699 (defun org-export-as-ascii (arg)
11700 "Export the outline as a pretty ASCII file.
11701 If there is an active region, export only the region.
11702 The prefix ARG specifies how many levels of the outline should become
11703 underlined headlines. The default is 3."
11704 (interactive "P")
11705 (setq-default org-todo-line-regexp org-todo-line-regexp)
11706 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
11707 (org-infile-export-plist)))
11708 (region
11709 (buffer-substring
11710 (if (org-region-active-p) (region-beginning) (point-min))
11711 (if (org-region-active-p) (region-end) (point-max))))
11712 (lines (org-export-find-first-heading-line
11713 (org-skip-comments
11714 (org-split-string
11715 (org-cleaned-string-for-export region)
11716 "[\r\n]"))))
11717 (org-startup-with-deadline-check nil)
11718 (level 0) line txt
11719 (umax nil)
11720 (case-fold-search nil)
11721 (filename (concat (file-name-as-directory
11722 (plist-get opt-plist :publishing-directory))
11723 (file-name-sans-extension
11724 (file-name-nondirectory buffer-file-name))
11725 ".txt"))
11726 (buffer (find-file-noselect filename))
11727 (levels-open (make-vector org-level-max nil))
11728 (odd org-odd-levels-only)
11729 (date (format-time-string "%Y/%m/%d" (current-time)))
11730 (time (format-time-string "%X" (org-current-time)))
11731 (author (plist-get opt-plist :author))
11732 (title (or (plist-get opt-plist :title)
11733 (file-name-sans-extension
11734 (file-name-nondirectory buffer-file-name))))
11735 (options nil)
11736 (email (plist-get opt-plist :email))
11737 (language (plist-get opt-plist :language))
11738 (text nil)
11739 (todo nil)
11740 (lang-words nil))
11742 (setq org-last-level 1)
11743 (org-init-section-numbers)
11745 (find-file-noselect filename)
11747 (setq lang-words (or (assoc language org-export-language-setup)
11748 (assoc "en" org-export-language-setup)))
11749 (if org-export-ascii-show-new-buffer
11750 (switch-to-buffer-other-window buffer)
11751 (set-buffer buffer))
11752 (erase-buffer)
11753 (fundamental-mode)
11754 ;; create local variables for all options, to make sure all called
11755 ;; functions get the correct information
11756 (mapcar (lambda (x)
11757 (set (make-local-variable (cdr x))
11758 (plist-get opt-plist (car x))))
11759 org-export-plist-vars)
11760 (set (make-local-variable 'org-odd-levels-only) odd)
11761 (setq umax (if arg (prefix-numeric-value arg)
11762 org-export-headline-levels))
11764 ;; File header
11765 (if title (org-insert-centered title ?=))
11766 (insert "\n")
11767 (if (or author email)
11768 (insert (concat (nth 1 lang-words) ": " (or author "")
11769 (if email (concat " <" email ">") "")
11770 "\n")))
11771 (if (and date time)
11772 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11773 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11775 (insert "\n\n")
11777 (if org-export-with-toc
11778 (progn
11779 (insert (nth 3 lang-words) "\n"
11780 (make-string (length (nth 3 lang-words)) ?=) "\n")
11781 (mapcar '(lambda (line)
11782 (if (string-match org-todo-line-regexp
11783 line)
11784 ;; This is a headline
11785 (progn
11786 (setq level (- (match-end 1) (match-beginning 1))
11787 level (org-tr-level level)
11788 txt (match-string 3 line)
11789 todo
11790 (or (and org-export-mark-todo-in-toc
11791 (match-beginning 2)
11792 (not (equal (match-string 2 line)
11793 org-done-string)))
11794 ; TODO, not DONE
11795 (and org-export-mark-todo-in-toc
11796 (= level umax)
11797 (org-search-todo-below
11798 line lines level))))
11799 (setq txt (org-html-expand-for-ascii txt))
11801 (if org-export-with-section-numbers
11802 (setq txt (concat (org-section-number level)
11803 " " txt)))
11804 (if (<= level umax)
11805 (progn
11806 (insert
11807 (make-string (* (1- level) 4) ?\ )
11808 (format (if todo "%s (*)\n" "%s\n") txt))
11809 (setq org-last-level level))
11810 ))))
11811 lines)))
11813 (org-init-section-numbers)
11814 (while (setq line (pop lines))
11815 ;; Remove the quoted HTML tags.
11816 (setq line (org-html-expand-for-ascii line))
11817 ;; Remove targets
11818 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11819 (setq line (replace-match "" t t line)))
11820 ;; Replace internal links
11821 (while (string-match org-bracket-link-regexp line)
11822 (setq line (replace-match
11823 (if (match-end 3) "[\\3]" "[\\1]")
11824 t nil line)))
11825 (cond
11826 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11827 ;; a Headline
11828 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11829 txt (match-string 2 line))
11830 (org-ascii-level-start level txt umax))
11831 (t (insert line "\n"))))
11832 (normal-mode)
11833 (save-buffer)
11834 (goto-char (point-min))))
11836 (defun org-search-todo-below (line lines level)
11837 "Search the subtree below LINE for any TODO entries."
11838 (let ((rest (cdr (memq line lines)))
11839 (re org-todo-line-regexp)
11840 line lv todo)
11841 (catch 'exit
11842 (while (setq line (pop rest))
11843 (if (string-match re line)
11844 (progn
11845 (setq lv (- (match-end 1) (match-beginning 1))
11846 todo (and (match-beginning 2)
11847 (not (equal (match-string 2 line)
11848 org-done-string))))
11849 ; TODO, not DONE
11850 (if (<= lv level) (throw 'exit nil))
11851 (if todo (throw 'exit t))))))))
11853 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11854 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11855 (defun org-html-expand-for-ascii (line)
11856 "Handle quoted HTML for ASCII export."
11857 (if org-export-html-expand
11858 (while (string-match "@<[^<>\n]*>" line)
11859 ;; We just remove the tags for now.
11860 (setq line (replace-match "" nil nil line))))
11861 line)
11863 (defun org-insert-centered (s &optional underline)
11864 "Insert the string S centered and underline it with character UNDERLINE."
11865 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11866 (insert (make-string ind ?\ ) s "\n")
11867 (if underline
11868 (insert (make-string ind ?\ )
11869 (make-string (string-width s) underline)
11870 "\n"))))
11872 (defun org-ascii-level-start (level title umax)
11873 "Insert a new level in ASCII export."
11874 (let (char)
11875 (if (> level umax)
11876 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11877 (if (or (not (equal (char-before) ?\n))
11878 (not (equal (char-before (1- (point))) ?\n)))
11879 (insert "\n"))
11880 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11881 (if org-export-with-section-numbers
11882 (setq title (concat (org-section-number level) " " title)))
11883 (insert title "\n" (make-string (string-width title) char) "\n"))))
11885 (defun org-export-visible (type arg)
11886 "Create a copy of the visible part of the current buffer, and export it.
11887 The copy is created in a temporary buffer and removed after use.
11888 TYPE is the final key (as a string) of the `C-c C-x' key sequence that will
11889 run the export command - in interactive use, the command prompts for this
11890 key. As a special case, if the you type SPC at the prompt, the temporary
11891 org-mode file will not be removed but presented to you so that you can
11892 continue to use it. The prefix arg ARG is passed through to the exporting
11893 command."
11894 (interactive
11895 (list (progn
11896 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
11897 (char-to-string (read-char-exclusive)))
11898 current-prefix-arg))
11899 (if (not (member type '("a" "\C-a" "b" "\C-b" "h" "x" " ")))
11900 (error "Invalid export key"))
11901 (let* ((binding (key-binding (concat "\C-c\C-x" type)))
11902 (keepp (equal type " "))
11903 (file buffer-file-name)
11904 (buffer (get-buffer-create "*Org Export Visible*"))
11905 s e)
11906 (with-current-buffer buffer (erase-buffer))
11907 (save-excursion
11908 (setq s (goto-char (point-min)))
11909 (while (not (= (point) (point-max)))
11910 (goto-char (org-find-invisible))
11911 (append-to-buffer buffer s (point))
11912 (setq s (goto-char (org-find-visible))))
11913 (set-buffer buffer)
11914 (let ((buffer-file-name file)
11915 (org-inhibit-startup t))
11916 (org-mode)
11917 (show-all)
11918 (unless keepp (funcall binding arg))))
11919 (if (not keepp)
11920 (kill-buffer buffer)
11921 (switch-to-buffer-other-window buffer)
11922 (goto-char (point-min)))))
11924 (defun org-find-visible ()
11925 (if (featurep 'noutline)
11926 (let ((s (point)))
11927 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11928 (get-char-property s 'invisible)))
11930 (skip-chars-forward "^\n")
11931 (point)))
11932 (defun org-find-invisible ()
11933 (if (featurep 'noutline)
11934 (let ((s (point)))
11935 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11936 (not (get-char-property s 'invisible))))
11938 (skip-chars-forward "^\r")
11939 (point)))
11941 ;; HTML
11943 (defun org-get-current-options ()
11944 "Return a string with current options as keyword options.
11945 Does include HTML export options as well as TODO and CATEGORY stuff."
11946 (format
11947 "#+TITLE: %s
11948 #+AUTHOR: %s
11949 #+EMAIL: %s
11950 #+LANGUAGE: %s
11951 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11952 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11953 #+CATEGORY: %s
11954 #+SEQ_TODO: %s
11955 #+TYP_TODO: %s
11956 #+STARTUP: %s %s %s %s %s
11957 #+ARCHIVE: %s
11959 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11960 org-export-headline-levels
11961 org-export-with-section-numbers
11962 org-export-with-toc
11963 org-export-preserve-breaks
11964 org-export-html-expand
11965 org-export-with-fixed-width
11966 org-export-with-tables
11967 org-export-with-sub-superscripts
11968 org-export-with-emphasize
11969 org-export-with-TeX-macros
11970 (file-name-nondirectory buffer-file-name)
11971 (if (equal org-todo-interpretation 'sequence)
11972 (mapconcat 'identity org-todo-keywords " ")
11973 "TODO FEEDBACK VERIFY DONE")
11974 (if (equal org-todo-interpretation 'type)
11975 (mapconcat 'identity org-todo-keywords " ")
11976 "Me Jason Marie DONE")
11977 (cdr (assoc org-startup-folded
11978 '((nil . "showall") (t . "overview") (content . "content"))))
11979 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11980 (if org-odd-levels-only "odd" "oddeven")
11981 (if org-hide-leading-stars "hidestars" "showstars")
11982 (if org-startup-align-all-tables "align" "noalign")
11983 org-archive-location
11986 (defun org-insert-export-options-template ()
11987 "Insert into the buffer a template with information for exporting."
11988 (interactive)
11989 (if (not (bolp)) (newline))
11990 (let ((s (org-get-current-options)))
11991 (and (string-match "#\\+CATEGORY" s)
11992 (setq s (substring s 0 (match-beginning 0))))
11993 (insert s)))
11995 (defun org-toggle-fixed-width-section (arg)
11996 "Toggle the fixed-width export.
11997 If there is no active region, the QUOTE keyword at the current headline is
11998 inserted or removed. When present, it causes the text between this headline
11999 and the next to be exported as fixed-width text, and unmodified.
12000 If there is an active region, this command adds or removes a colon as the
12001 first character of this line. If the first character of a line is a colon,
12002 this line is also exported in fixed-width font."
12003 (interactive "P")
12004 (let* ((cc 0)
12005 (regionp (org-region-active-p))
12006 (beg (if regionp (region-beginning) (point)))
12007 (end (if regionp (region-end)))
12008 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
12009 (re "[ \t]*\\(:\\)")
12010 off)
12011 (if regionp
12012 (save-excursion
12013 (goto-char beg)
12014 (setq cc (current-column))
12015 (beginning-of-line 1)
12016 (setq off (looking-at re))
12017 (while (> nlines 0)
12018 (setq nlines (1- nlines))
12019 (beginning-of-line 1)
12020 (cond
12021 (arg
12022 (move-to-column cc t)
12023 (insert ":\n")
12024 (forward-line -1))
12025 ((and off (looking-at re))
12026 (replace-match "" t t nil 1))
12027 ((not off) (move-to-column cc t) (insert ":")))
12028 (forward-line 1)))
12029 (save-excursion
12030 (org-back-to-heading)
12031 (if (looking-at (concat outline-regexp
12032 "\\( +\\<" org-quote-string "\\>\\)"))
12033 (replace-match "" t t nil 1)
12034 (if (looking-at outline-regexp)
12035 (progn
12036 (goto-char (match-end 0))
12037 (insert " " org-quote-string))))))))
12039 (defun org-export-as-html-and-open (arg)
12040 "Export the outline as HTML and immediately open it with a browser.
12041 If there is an active region, export only the region.
12042 The prefix ARG specifies how many levels of the outline should become
12043 headlines. The default is 3. Lower levels will become bulleted lists."
12044 (interactive "P")
12045 (org-export-as-html arg 'hidden)
12046 (org-open-file buffer-file-name))
12048 (defun org-export-as-html-batch ()
12049 "Call `org-export-as-html', may be used in batch processing as
12050 emacs --batch
12051 --load=$HOME/lib/emacs/org.el
12052 --eval \"(setq org-export-headline-levels 2)\"
12053 --visit=MyFile --funcall org-export-as-html-batch"
12054 (org-export-as-html org-export-headline-levels 'hidden))
12056 (defun org-export-as-html (arg &optional hidden ext-plist)
12057 "Export the outline as a pretty HTML file.
12058 If there is an active region, export only the region.
12059 The prefix ARG specifies how many levels of the outline should become
12060 headlines. The default is 3. Lower levels will become bulleted lists.
12061 When HIDDEN is non-nil, don't display the HTML buffer.
12062 EXT-PLIST is a property list with external parameters overriding
12063 org-mode's default settings, but still inferior to file-local settings."
12064 (interactive "P")
12065 (setq-default org-todo-line-regexp org-todo-line-regexp)
12066 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
12067 (setq-default org-done-string org-done-string)
12068 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12069 ext-plist
12070 (org-infile-export-plist)))
12072 (style (plist-get opt-plist :style))
12073 (odd org-odd-levels-only)
12074 (region-p (org-region-active-p))
12075 (region
12076 (buffer-substring
12077 (if region-p (region-beginning) (point-min))
12078 (if region-p (region-end) (point-max))))
12079 (all_lines
12080 (org-skip-comments (org-split-string
12081 (org-cleaned-string-for-export region)
12082 "[\r\n]")))
12083 (lines (org-export-find-first-heading-line all_lines))
12084 (level 0) (line "") (origline "") txt todo
12085 (umax nil)
12086 (filename (concat (file-name-as-directory
12087 (plist-get opt-plist :publishing-directory))
12088 (file-name-sans-extension
12089 (file-name-nondirectory buffer-file-name))
12090 ".html"))
12091 (buffer (find-file-noselect filename))
12092 (levels-open (make-vector org-level-max nil))
12093 (date (format-time-string "%Y/%m/%d" (current-time)))
12094 (time (format-time-string "%X" (org-current-time)))
12095 (author (plist-get opt-plist :author))
12096 (title (or (plist-get opt-plist :title)
12097 (file-name-sans-extension
12098 (file-name-nondirectory buffer-file-name))))
12099 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
12100 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
12101 (inquote nil)
12102 (infixed nil)
12103 (in-local-list nil)
12104 (local-list-num nil)
12105 (local-list-indent nil)
12106 (llt org-plain-list-ordered-item-terminator)
12107 (email (plist-get opt-plist :email))
12108 (language (plist-get opt-plist :language))
12109 (text (plist-get opt-plist :text))
12110 (lang-words nil)
12111 (target-alist nil) tg
12112 (head-count 0) cnt
12113 (start 0)
12114 ;; FIXME: The following returns always nil under XEmacs
12115 (coding-system (and (fboundp 'coding-system-get)
12116 (boundp 'buffer-file-coding-system)
12117 buffer-file-coding-system))
12118 (coding-system-for-write (or coding-system coding-system-for-write))
12119 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
12120 (charset (and coding-system
12121 (coding-system-get coding-system 'mime-charset)))
12122 table-open type
12123 table-buffer table-orig-buffer
12124 ind start-is-num starter
12125 rpl path desc descp desc1 desc2 link
12127 (message "Exporting...")
12129 (setq org-last-level 1)
12130 (org-init-section-numbers)
12132 ;; Get the language-dependent settings
12133 (setq lang-words (or (assoc language org-export-language-setup)
12134 (assoc "en" org-export-language-setup)))
12136 ;; Switch to the output buffer
12137 (if (or hidden (not org-export-html-show-new-buffer))
12138 (set-buffer buffer)
12139 (switch-to-buffer-other-window buffer))
12140 (erase-buffer)
12141 (fundamental-mode)
12142 (let ((case-fold-search nil)
12143 (org-odd-levels-only odd))
12144 ;; create local variables for all options, to make sure all called
12145 ;; functions get the correct information
12146 (mapcar (lambda (x)
12147 (set (make-local-variable (cdr x))
12148 (plist-get opt-plist (car x))))
12149 org-export-plist-vars)
12150 (setq umax (if arg (prefix-numeric-value arg)
12151 org-export-headline-levels))
12153 ;; File header
12154 (insert (format
12155 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
12156 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
12157 <html lang=\"%s\"><head>
12158 <title>%s</title>
12159 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
12160 <meta name=generator content=\"Org-mode\">
12161 <meta name=generated content=\"%s %s\">
12162 <meta name=author content=\"%s\">
12164 </head><body>
12166 language (org-html-expand title) (or charset "iso-8859-1")
12167 date time author style))
12170 (insert (or (plist-get opt-plist :preamble) ""))
12172 (when (plist-get opt-plist :auto-preamble)
12173 (if title (insert (concat "<H1 class=\"title\">"
12174 (org-html-expand title) "</H1>\n")))
12175 ; (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
12176 ; (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
12177 ; email "&gt;</a>\n")))
12178 ; (if (or author email) (insert "<br>\n"))
12179 ; (if (and date time) (insert (concat (nth 2 lang-words) ": "
12180 ; date " " time "<br>\n")))
12181 (if text (insert (concat "<p>\n" (org-html-expand text)))))
12183 (if org-export-with-toc
12184 (progn
12185 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
12186 (insert "<ul>\n")
12187 (setq lines
12188 (mapcar '(lambda (line)
12189 (if (string-match org-todo-line-regexp line)
12190 ;; This is a headline
12191 (progn
12192 (setq level (- (match-end 1) (match-beginning 1))
12193 level (org-tr-level level)
12194 txt (save-match-data
12195 (org-html-expand
12196 (match-string 3 line)))
12197 todo
12198 (or (and org-export-mark-todo-in-toc
12199 (match-beginning 2)
12200 (not (equal (match-string 2 line)
12201 org-done-string)))
12202 ; TODO, not DONE
12203 (and org-export-mark-todo-in-toc
12204 (= level umax)
12205 (org-search-todo-below
12206 line lines level))))
12207 (if org-export-with-section-numbers
12208 (setq txt (concat (org-section-number level)
12209 " " txt)))
12210 (if (<= level umax)
12211 (progn
12212 (setq head-count (+ head-count 1))
12213 (if (> level org-last-level)
12214 (progn
12215 (setq cnt (- level org-last-level))
12216 (while (>= (setq cnt (1- cnt)) 0)
12217 (insert "<ul>"))
12218 (insert "\n")))
12219 (if (< level org-last-level)
12220 (progn
12221 (setq cnt (- org-last-level level))
12222 (while (>= (setq cnt (1- cnt)) 0)
12223 (insert "</ul>"))
12224 (insert "\n")))
12225 ;; Check for targets
12226 (while (string-match org-target-regexp line)
12227 (setq tg (match-string 1 line)
12228 line (replace-match
12229 (concat "@<span class=\"target\">" tg "@</span> ")
12230 t t line))
12231 (push (cons (org-solidify-link-text tg)
12232 (format "sec-%d" head-count))
12233 target-alist))
12234 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
12235 (setq txt (replace-match "" t t txt)))
12236 (insert
12237 (format
12238 (if todo
12239 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
12240 "<li><a href=\"#sec-%d\">%s</a>\n")
12241 head-count txt))
12243 (setq org-last-level level))
12245 line)
12246 lines))
12247 (while (> org-last-level 0)
12248 (setq org-last-level (1- org-last-level))
12249 (insert "</ul>\n"))
12251 (setq head-count 0)
12252 (org-init-section-numbers)
12254 (while (setq line (pop lines) origline line)
12255 (catch 'nextline
12257 ;; end of quote section?
12258 (when (and inquote (string-match "^\\*+" line))
12259 (insert "</pre>\n")
12260 (setq inquote nil))
12261 ;; inside a quote section?
12262 (when inquote
12263 (insert (org-html-protect line) "\n")
12264 (throw 'nextline nil))
12266 ;; verbatim lines
12267 (when (and org-export-with-fixed-width
12268 (string-match "^[ \t]*:\\(.*\\)" line))
12269 (when (not infixed)
12270 (setq infixed t)
12271 (insert "<pre>\n"))
12272 (insert (org-html-protect (match-string 1 line)) "\n")
12273 (when (and lines
12274 (not (string-match "^[ \t]*\\(:.*\\)"
12275 (car lines))))
12276 (setq infixed nil)
12277 (insert "</pre>\n"))
12278 (throw 'nextline nil))
12281 ;; make targets to anchors
12282 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
12283 (cond
12284 ((match-end 2)
12285 (setq line (replace-match
12286 (concat "@<a name=\""
12287 (org-solidify-link-text (match-string 1 line))
12288 "\">\\nbsp@</a>")
12289 t t line)))
12290 ((and org-export-with-toc (equal (string-to-char line) ?*))
12291 (setq line (replace-match
12292 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
12293 ; (concat "@<i>" (match-string 1 line) "@</i> ")
12294 t t line)))
12296 (setq line (replace-match
12297 (concat "@<a name=\""
12298 (org-solidify-link-text (match-string 1 line))
12299 "\" class=\"target\">" (match-string 1 line) "@</a> ")
12300 t t line)))))
12302 (setq line (org-html-handle-time-stamps line))
12304 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
12305 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
12306 (setq line (org-html-expand line))
12308 ;; Format the links
12309 (setq start 0)
12310 (while (string-match org-bracket-link-analytic-regexp line start)
12311 (setq start (match-beginning 0))
12312 (setq type (if (match-end 2) (match-string 2 line) "internal"))
12313 (setq path (match-string 3 line))
12314 (setq desc1 (if (match-end 5) (match-string 5 line))
12315 desc2 (if (match-end 2) (concat type ":" path) path)
12316 descp (and desc1 (not (equal desc1 desc2)))
12317 desc (or desc1 desc2))
12318 ;; FIXME: do we need to unescape here somewhere?
12319 (cond
12320 ((equal type "internal")
12321 (setq rpl
12322 (concat
12323 "<a href=\"#"
12324 (org-solidify-link-text path target-alist)
12325 "\">" desc "</a>")))
12326 ((member type '("http" "https" "ftp" "mailto" "news"))
12327 ;; standard URL
12328 (setq link (concat type ":" path))
12329 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
12330 ((string= type "file")
12331 ;; FILE link
12332 (let* ((filename path)
12333 (abs-p (file-name-absolute-p filename))
12334 thefile file-is-image-p search)
12335 (save-match-data
12336 (if (string-match "::\\(.*\\)" filename)
12337 (setq search (match-string 1 filename)
12338 filename (replace-match "" nil nil filename)))
12339 (setq file-is-image-p
12340 (string-match (org-image-file-name-regexp) filename))
12341 (setq thefile (if abs-p (expand-file-name filename) filename))
12342 (when (and org-export-html-link-org-files-as-html
12343 (string-match "\\.org$" thefile))
12344 (setq thefile (concat (substring thefile 0
12345 (match-beginning 0))
12346 ".html"))
12347 (if (and search
12348 ;; make sure this is can be used as target search
12349 (not (string-match "^[0-9]*$" search))
12350 (not (string-match "^\\*" search))
12351 (not (string-match "^/.*/$" search)))
12352 (setq thefile (concat thefile "#"
12353 (org-solidify-link-text
12354 (org-link-unescape search)))))
12355 (when (string-match "^file:" desc)
12356 (setq desc (replace-match "" t t desc))
12357 (if (string-match "\\.org$" desc)
12358 (setq desc (replace-match "" t t desc))))))
12359 (setq rpl (if (and file-is-image-p
12360 (or (eq t org-export-html-inline-images)
12361 (and org-export-html-inline-images
12362 (not descp))))
12363 (concat "<img src=\"" thefile "\"/>")
12364 (concat "<a href=\"" thefile "\">" desc "</a>")))))
12365 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
12366 (setq rpl (concat "<i>&lt;" type ":"
12367 (save-match-data (org-link-unescape path))
12368 "&gt;</i>"))))
12369 (setq line (replace-match rpl t t line)
12370 start (+ start (length rpl))))
12371 ;; TODO items
12372 (if (and (string-match org-todo-line-regexp line)
12373 (match-beginning 2))
12374 (if (equal (match-string 2 line) org-done-string)
12375 (setq line (replace-match
12376 "<span class=\"done\">\\2</span>"
12377 nil nil line 2))
12378 (setq line (replace-match "<span class=\"todo\">\\2</span>"
12379 nil nil line 2))))
12381 ;; DEADLINES
12382 (if (string-match org-deadline-line-regexp line)
12383 (progn
12384 (if (save-match-data
12385 (string-match "<a href"
12386 (substring line 0 (match-beginning 0))))
12387 nil ; Don't do the replacement - it is inside a link
12388 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
12389 nil nil line 1)))))
12390 (cond
12391 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
12392 ;; This is a headline
12393 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
12394 txt (match-string 2 line))
12395 (if (string-match quote-re0 txt)
12396 (setq txt (replace-match "" t t txt)))
12397 (if (<= level umax) (setq head-count (+ head-count 1)))
12398 (when in-local-list
12399 ;; Close any local lists before inserting a new header line
12400 (while local-list-num
12401 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12402 (pop local-list-num))
12403 (setq local-list-indent nil
12404 in-local-list nil))
12405 (org-html-level-start level txt umax
12406 (and org-export-with-toc (<= level umax))
12407 head-count)
12408 ;; QUOTES
12409 (when (string-match quote-re line)
12410 (insert "<pre>")
12411 (setq inquote t)))
12413 ((and org-export-with-tables
12414 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
12415 (if (not table-open)
12416 ;; New table starts
12417 (setq table-open t table-buffer nil table-orig-buffer nil))
12418 ;; Accumulate lines
12419 (setq table-buffer (cons line table-buffer)
12420 table-orig-buffer (cons origline table-orig-buffer))
12421 (when (or (not lines)
12422 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
12423 (car lines))))
12424 (setq table-open nil
12425 table-buffer (nreverse table-buffer)
12426 table-orig-buffer (nreverse table-orig-buffer))
12427 (insert (org-format-table-html table-buffer table-orig-buffer))))
12429 ;; Normal lines
12430 (when (and (string-match
12431 (cond
12432 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
12433 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
12434 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
12435 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
12436 line))
12437 (setq ind (org-get-string-indentation line)
12438 start-is-num (match-beginning 4)
12439 starter (if (match-beginning 2) (match-string 2 line))
12440 line (substring line (match-beginning 5)))
12441 (unless (string-match "[^ \t]" line)
12442 ;; empty line. Pretend indentation is large.
12443 (setq ind (1+ (or (car local-list-indent) 1))))
12444 (while (and in-local-list
12445 (or (and (= ind (car local-list-indent))
12446 (not starter))
12447 (< ind (car local-list-indent))))
12448 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12449 (pop local-list-num) (pop local-list-indent)
12450 (setq in-local-list local-list-indent))
12451 (cond
12452 ((and starter
12453 (or (not in-local-list)
12454 (> ind (car local-list-indent))))
12455 ;; Start new (level of ) list
12456 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
12457 (push start-is-num local-list-num)
12458 (push ind local-list-indent)
12459 (setq in-local-list t))
12460 (starter
12461 ;; continue current list
12462 (insert "<li>\n"))))
12463 ;; Empty lines start a new paragraph. If hand-formatted lists
12464 ;; are not fully interpreted, lines starting with "-", "+", "*"
12465 ;; also start a new paragraph.
12466 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
12467 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
12470 ;; Properly close all local lists and other lists
12471 (when inquote (insert "</pre>\n"))
12472 (when in-local-list
12473 ;; Close any local lists before inserting a new header line
12474 (while local-list-num
12475 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12476 (pop local-list-num))
12477 (setq local-list-indent nil
12478 in-local-list nil))
12479 (org-html-level-start 1 nil umax
12480 (and org-export-with-toc (<= level umax))
12481 head-count)
12483 (when (plist-get opt-plist :auto-postamble)
12484 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
12485 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
12486 email "&gt;</a>\n")))
12487 (if (or author email) (insert "<br>\n"))
12488 (if (and date time) (insert (concat (nth 2 lang-words) ": "
12489 date " " time "<br>\n"))))
12491 (if org-export-html-with-timestamp
12492 (insert org-export-html-html-helper-timestamp))
12493 (insert (or (plist-get opt-plist :postamble) ""))
12494 (insert "</body>\n</html>\n")
12495 (normal-mode)
12496 (save-buffer)
12497 (goto-char (point-min)))))
12499 (defun org-format-table-html (lines olines)
12500 "Find out which HTML converter to use and return the HTML code."
12501 (if (string-match "^[ \t]*|" (car lines))
12502 ;; A normal org table
12503 (org-format-org-table-html lines)
12504 ;; Table made by table.el - test for spanning
12505 (let* ((hlines (delq nil (mapcar
12506 (lambda (x)
12507 (if (string-match "^[ \t]*\\+-" x) x
12508 nil))
12509 lines)))
12510 (first (car hlines))
12511 (ll (and (string-match "\\S-+" first)
12512 (match-string 0 first)))
12513 (re (concat "^[ \t]*" (regexp-quote ll)))
12514 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12515 hlines))))
12516 (if (and (not spanning)
12517 (not org-export-prefer-native-exporter-for-tables))
12518 ;; We can use my own converter with HTML conversions
12519 (org-format-table-table-html lines)
12520 ;; Need to use the code generator in table.el, with the original text.
12521 (org-format-table-table-html-using-table-generate-source olines)))))
12523 (defun org-format-org-table-html (lines)
12524 "Format a table into HTML."
12525 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12526 (setq lines (nreverse lines))
12527 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12528 (setq lines (nreverse lines))
12529 (when org-export-table-remove-special-lines
12530 ;; Check if the table has a marking column. If yes remove the
12531 ;; column and the special lines
12532 (let* ((special
12533 (not
12534 (memq nil
12535 (mapcar
12536 (lambda (x)
12537 (or (string-match "^[ \t]*|-" x)
12538 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12539 lines)))))
12540 (if special
12541 (setq lines
12542 (delq nil
12543 (mapcar
12544 (lambda (x)
12545 (if (string-match "^[ \t]*| *[!_^] *|" x)
12546 nil ; ignore this line
12547 (and (or (string-match "^[ \t]*|-+\\+" x)
12548 (string-match "^[ \t]*|[^|]*|" x))
12549 (replace-match "|" t t x))))
12550 lines))))))
12552 (let ((head (and org-export-highlight-first-table-line
12553 (delq nil (mapcar
12554 (lambda (x) (string-match "^[ \t]*|-" x))
12555 (cdr lines)))))
12556 line fields html)
12557 (setq html (concat org-export-html-table-tag "\n"))
12558 (while (setq line (pop lines))
12559 (catch 'next-line
12560 (if (string-match "^[ \t]*|-" line)
12561 (progn
12562 (setq head nil) ;; head ends here, first time around
12563 ;; ignore this line
12564 (throw 'next-line t)))
12565 ;; Break the line into fields
12566 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12567 (setq html (concat
12568 html
12569 "<tr>"
12570 (mapconcat (lambda (x)
12571 (if head
12572 (concat "<th>" x "</th>")
12573 (concat "<td>" x "</td>")))
12574 fields "")
12575 "</tr>\n"))))
12576 (setq html (concat html "</table>\n"))
12577 html))
12579 (defun org-fake-empty-table-line (line)
12580 "Replace everything except \"|\" with spaces."
12581 (let ((i (length line))
12582 (newstr (copy-sequence line)))
12583 (while (> i 0)
12584 (setq i (1- i))
12585 (if (not (eq (aref newstr i) ?|))
12586 (aset newstr i ?\ )))
12587 newstr))
12589 (defun org-format-table-table-html (lines)
12590 "Format a table generated by table.el into HTML.
12591 This conversion does *not* use `table-generate-source' from table.el.
12592 This has the advantage that Org-mode's HTML conversions can be used.
12593 But it has the disadvantage, that no cell- or row-spanning is allowed."
12594 (let (line field-buffer
12595 (head org-export-highlight-first-table-line)
12596 fields html empty)
12597 (setq html (concat org-export-html-table-tag "\n"))
12598 (while (setq line (pop lines))
12599 (setq empty "&nbsp")
12600 (catch 'next-line
12601 (if (string-match "^[ \t]*\\+-" line)
12602 (progn
12603 (if field-buffer
12604 (progn
12605 (setq html (concat
12606 html
12607 "<tr>"
12608 (mapconcat
12609 (lambda (x)
12610 (if (equal x "") (setq x empty))
12611 (if head
12612 (concat "<th>" x "</th>\n")
12613 (concat "<td>" x "</td>\n")))
12614 field-buffer "\n")
12615 "</tr>\n"))
12616 (setq head nil)
12617 (setq field-buffer nil)))
12618 ;; Ignore this line
12619 (throw 'next-line t)))
12620 ;; Break the line into fields and store the fields
12621 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12622 (if field-buffer
12623 (setq field-buffer (mapcar
12624 (lambda (x)
12625 (concat x "<br>" (pop fields)))
12626 field-buffer))
12627 (setq field-buffer fields))))
12628 (setq html (concat html "</table>\n"))
12629 html))
12631 (defun org-format-table-table-html-using-table-generate-source (lines)
12632 "Format a table into html, using `table-generate-source' from table.el.
12633 This has the advantage that cell- or row-spanning is allowed.
12634 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12635 (require 'table)
12636 (with-current-buffer (get-buffer-create " org-tmp1 ")
12637 (erase-buffer)
12638 (insert (mapconcat 'identity lines "\n"))
12639 (goto-char (point-min))
12640 (if (not (re-search-forward "|[^+]" nil t))
12641 (error "Error processing table"))
12642 (table-recognize-table)
12643 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12644 (table-generate-source 'html " org-tmp2 ")
12645 (set-buffer " org-tmp2 ")
12646 (buffer-substring (point-min) (point-max))))
12648 (defun org-html-handle-time-stamps (s)
12649 "FIXME: Format time stamps, or remove them"
12652 (defun org-html-protect (s)
12653 ;; convert & to &amp;, < to &lt; and > to &gt;
12654 (let ((start 0))
12655 (while (string-match "&" s start)
12656 (setq s (replace-match "&amp;" t t s)
12657 start (1+ (match-beginning 0))))
12658 (while (string-match "<" s)
12659 (setq s (replace-match "&lt;" t t s)))
12660 (while (string-match ">" s)
12661 (setq s (replace-match "&gt;" t t s))))
12664 (defun org-html-expand (string)
12665 "Prepare STRING for HTML export. Applies all active conversions.
12666 If there are links in the string, don't modify these."
12667 (let* (m s l res)
12668 (while (setq m (string-match org-bracket-link-regexp string))
12669 (setq s (substring string 0 m)
12670 l (match-string 0 string)
12671 string (substring string (match-end 0)))
12672 (push (org-html-do-expand s) res)
12673 (push l res))
12674 (push (org-html-do-expand string) res)
12675 (apply 'concat (nreverse res))))
12677 (defun org-html-do-expand (s)
12678 "Apply all active conversions to translate special ASCII to HTML."
12679 (setq s (org-html-protect s))
12680 (if org-export-html-expand
12681 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12682 (setq s (replace-match "<\\1>" nil nil s))))
12683 (if org-export-with-emphasize
12684 (setq s (org-export-html-convert-emphasize s)))
12685 (if org-export-with-sub-superscripts
12686 (setq s (org-export-html-convert-sub-super s)))
12687 (if org-export-with-TeX-macros
12688 (let ((start 0) wd ass)
12689 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12690 (setq wd (match-string 1 s))
12691 (if (setq ass (assoc wd org-html-entities))
12692 (setq s (replace-match (or (cdr ass)
12693 (concat "&" (car ass) ";"))
12694 t t s))
12695 (setq start (+ start (length wd)))))))
12698 (defun org-create-multibrace-regexp (left right n)
12699 "Create a regular expression which will match a balanced sexp.
12700 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12701 as single character strings.
12702 The regexp returned will match the entire expression including the
12703 delimiters. It will also define a single group which contains the
12704 match except for the outermost delimiters. The maximum depth of
12705 stacked delimiters is N. Escaping delimiters is not possible."
12706 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12707 (or "\\|")
12708 (re nothing)
12709 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12710 (while (> n 1)
12711 (setq n (1- n)
12712 re (concat re or next)
12713 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12714 (concat left "\\(" re "\\)" right)))
12716 (defvar org-match-substring-regexp
12717 (concat
12718 "\\([^\\]\\)\\([_^]\\)\\("
12719 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12720 "\\|"
12721 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12722 "\\|"
12723 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12724 "The regular expression matching a sub- or superscript.")
12726 (defun org-export-html-convert-sub-super (string)
12727 "Convert sub- and superscripts in STRING to HTML."
12728 (let (key c)
12729 (while (string-match org-match-substring-regexp string)
12730 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12731 (setq c (or (match-string 8 string)
12732 (match-string 6 string)
12733 (match-string 5 string)))
12734 (setq string (replace-match
12735 (concat (match-string 1 string)
12736 "<" key ">" c "</" key ">")
12737 t t string)))
12738 (while (string-match "\\\\\\([_^]\\)" string)
12739 (setq string (replace-match (match-string 1 string) t t string))))
12740 string)
12742 (defun org-export-html-convert-emphasize (string)
12743 (while (string-match org-italic-re string)
12744 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
12745 (while (string-match org-bold-re string)
12746 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
12747 (while (string-match org-underline-re string)
12748 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
12749 string)
12751 (defun org-html-level-start (level title umax with-toc head-count)
12752 "Insert a new level in HTML export.
12753 When TITLE is nil, just close all open levels."
12754 (let ((l (1+ (max level umax))))
12755 (while (<= l org-level-max)
12756 (if (aref levels-open (1- l))
12757 (progn
12758 (org-html-level-close l)
12759 (aset levels-open (1- l) nil)))
12760 (setq l (1+ l)))
12761 (when title
12762 ;; If title is nil, this means this function is called to close
12763 ;; all levels, so the rest is done only if title is given
12764 (if (> level umax)
12765 (progn
12766 (if (aref levels-open (1- level))
12767 (insert "<li>" title "<p>\n")
12768 (aset levels-open (1- level) t)
12769 (insert "<ul><li>" title "<p>\n")))
12770 (if org-export-with-section-numbers
12771 (setq title (concat (org-section-number level) " " title)))
12772 (setq level (+ level 1))
12773 (if with-toc
12774 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12775 level head-count title level))
12776 (insert (format "\n<H%d>%s</H%d>\n" level title level)))))))
12778 (defun org-html-level-close (&rest args)
12779 "Terminate one level in HTML export."
12780 (insert "</ul>"))
12782 ;; Variable holding the vector with section numbers
12783 (defvar org-section-numbers (make-vector org-level-max 0))
12785 (defun org-init-section-numbers ()
12786 "Initialize the vector for the section numbers."
12787 (let* ((level -1)
12788 (numbers (nreverse (org-split-string "" "\\.")))
12789 (depth (1- (length org-section-numbers)))
12790 (i depth) number-string)
12791 (while (>= i 0)
12792 (if (> i level)
12793 (aset org-section-numbers i 0)
12794 (setq number-string (or (car numbers) "0"))
12795 (if (string-match "\\`[A-Z]\\'" number-string)
12796 (aset org-section-numbers i
12797 (- (string-to-char number-string) ?A -1))
12798 (aset org-section-numbers i (string-to-number number-string)))
12799 (pop numbers))
12800 (setq i (1- i)))))
12802 (defun org-section-number (&optional level)
12803 "Return a string with the current section number.
12804 When LEVEL is non-nil, increase section numbers on that level."
12805 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12806 (when level
12807 (when (> level -1)
12808 (aset org-section-numbers
12809 level (1+ (aref org-section-numbers level))))
12810 (setq idx (1+ level))
12811 (while (<= idx depth)
12812 (if (not (= idx 1))
12813 (aset org-section-numbers idx 0))
12814 (setq idx (1+ idx))))
12815 (setq idx 0)
12816 (while (<= idx depth)
12817 (setq n (aref org-section-numbers idx))
12818 (setq string (concat string (if (not (string= string "")) "." "")
12819 (int-to-string n)))
12820 (setq idx (1+ idx)))
12821 (save-match-data
12822 (if (string-match "\\`\\([@0]\\.\\)+" string)
12823 (setq string (replace-match "" nil nil string)))
12824 (if (string-match "\\(\\.0\\)+\\'" string)
12825 (setq string (replace-match "" nil nil string))))
12826 string))
12829 (defun org-export-icalendar-this-file ()
12830 "Export current file as an iCalendar file.
12831 The iCalendar file will be located in the same directory as the Org-mode
12832 file, but with extension `.ics'."
12833 (interactive)
12834 (org-export-icalendar nil buffer-file-name))
12836 (defun org-export-as-xml (arg)
12837 "Export current buffer as XOXO XML buffer."
12838 (interactive "P")
12839 (cond ((eq org-export-xml-type 'xoxo)
12840 (org-export-as-xoxo (current-buffer)))))
12842 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12843 (with-current-buffer buffer
12844 (apply 'insert output)))
12846 (defun org-export-as-xoxo (&optional buffer)
12847 "Export the org buffer as XOXO.
12848 The XOXO buffer is named *xoxo-<source buffer name>*"
12849 (interactive (list (current-buffer)))
12850 ;; A quickie abstraction
12852 ;; Output everything as XOXO
12853 (with-current-buffer (get-buffer buffer)
12854 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12855 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12856 (org-infile-export-plist)))
12857 (filename (concat (file-name-as-directory
12858 (plist-get opt-plist :publishing-directory))
12859 (file-name-sans-extension
12860 (file-name-nondirectory buffer-file-name))
12861 ".xml"))
12862 (out (find-file-noselect filename))
12863 (last-level 1)
12864 (hanging-li nil))
12865 ;; Check the output buffer is empty.
12866 (with-current-buffer out (erase-buffer))
12867 ;; Kick off the output
12868 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12869 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12870 (let* ((hd (match-string-no-properties 1))
12871 (level (length hd))
12872 (text (concat
12873 (match-string-no-properties 2)
12874 (save-excursion
12875 (goto-char (match-end 0))
12876 (let ((str ""))
12877 (catch 'loop
12878 (while 't
12879 (forward-line)
12880 (if (looking-at "^[ \t]\\(.*\\)")
12881 (setq str (concat str (match-string-no-properties 1)))
12882 (throw 'loop str)))))))))
12884 ;; Handle level rendering
12885 (cond
12886 ((> level last-level)
12887 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12889 ((< level last-level)
12890 (dotimes (- (- last-level level) 1)
12891 (if hanging-li
12892 (org-export-as-xoxo-insert-into out "</li>\n"))
12893 (org-export-as-xoxo-insert-into out "</ol>\n"))
12894 (when hanging-li
12895 (org-export-as-xoxo-insert-into out "</li>\n")
12896 (setq hanging-li nil)))
12898 ((equal level last-level)
12899 (if hanging-li
12900 (org-export-as-xoxo-insert-into out "</li>\n")))
12903 (setq last-level level)
12905 ;; And output the new li
12906 (setq hanging-li 't)
12907 (if (equal ?+ (elt text 0))
12908 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12909 (org-export-as-xoxo-insert-into out "<li>" text))))
12911 ;; Finally finish off the ol
12912 (dotimes (- last-level 1)
12913 (if hanging-li
12914 (org-export-as-xoxo-insert-into out "</li>\n"))
12915 (org-export-as-xoxo-insert-into out "</ol>\n"))
12917 ;; Finish the buffer off and clean it up.
12918 (switch-to-buffer-other-window out)
12919 (indent-region (point-min) (point-max) nil)
12920 (save-buffer)
12921 (goto-char (point-min))
12924 ;;;###autoload
12925 (defun org-export-icalendar-all-agenda-files ()
12926 "Export all files in `org-agenda-files' to iCalendar .ics files.
12927 Each iCalendar file will be located in the same directory as the Org-mode
12928 file, but with extension `.ics'."
12929 (interactive)
12930 (apply 'org-export-icalendar nil (org-agenda-files t)))
12932 ;;;###autoload
12933 (defun org-export-icalendar-combine-agenda-files ()
12934 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12935 The file is stored under the name `org-combined-agenda-icalendar-file'."
12936 (interactive)
12937 (apply 'org-export-icalendar t (org-agenda-files t)))
12939 (defun org-export-icalendar (combine &rest files)
12940 "Create iCalendar files for all elements of FILES.
12941 If COMBINE is non-nil, combine all calendar entries into a single large
12942 file and store it under the name `org-combined-agenda-icalendar-file'."
12943 (save-excursion
12944 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12945 (when combine
12946 (setq ical-file org-combined-agenda-icalendar-file
12947 ical-buffer (org-get-agenda-file-buffer ical-file))
12948 (set-buffer ical-buffer) (erase-buffer))
12949 (while (setq file (pop files))
12950 (catch 'nextfile
12951 (org-check-agenda-file file)
12952 (unless combine
12953 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12954 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12955 (set-buffer ical-buffer) (erase-buffer))
12956 (set-buffer (org-get-agenda-file-buffer file))
12957 (setq category (or org-category
12958 (file-name-sans-extension
12959 (file-name-nondirectory buffer-file-name))))
12960 (if (symbolp category) (setq category (symbol-name category)))
12961 (let ((standard-output ical-buffer))
12962 (if combine
12963 (and (not started) (setq started t)
12964 (org-start-icalendar-file org-icalendar-combined-name))
12965 (org-start-icalendar-file category))
12966 (org-print-icalendar-entries combine category)
12967 (when (or (and combine (not files)) (not combine))
12968 (org-finish-icalendar-file)
12969 (set-buffer ical-buffer)
12970 (save-buffer)
12971 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12972 (org-release-buffers org-agenda-new-buffers))))
12974 (defvar org-after-save-iCalendar-file-hook nil
12975 "Hook run after an iCalendar file has been saved.
12976 The iCalendar buffer is still current when this hook is run.
12977 A good way to use this is to tell a desktop calenndar application to re-read
12978 the iCalendar file.")
12980 (defun org-print-icalendar-entries (&optional combine category)
12981 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12982 When COMBINE is non nil, add the category to each line."
12983 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12984 (dts (org-ical-ts-to-string
12985 (format-time-string (cdr org-time-stamp-formats) (current-time))
12986 "DTSTART"))
12987 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12988 (save-excursion
12989 (goto-char (point-min))
12990 (while (re-search-forward org-ts-regexp nil t)
12991 (setq pos (match-beginning 0)
12992 ts (match-string 0)
12993 inc t
12994 hd (org-get-heading))
12995 (if (looking-at re2)
12996 (progn
12997 (goto-char (match-end 0))
12998 (setq ts2 (match-string 1) inc nil))
12999 (setq ts2 ts
13000 tmp (buffer-substring (max (point-min)
13001 (- pos org-ds-keyword-length))
13002 pos)
13003 deadlinep (string-match org-deadline-regexp tmp)
13004 scheduledp (string-match org-scheduled-regexp tmp)
13005 ;; donep (org-entry-is-done-p)
13007 (if (or (string-match org-tr-regexp hd)
13008 (string-match org-ts-regexp hd))
13009 (setq hd (replace-match "" t t hd)))
13010 (if combine
13011 (setq hd (concat hd " (category " category ")")))
13012 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
13013 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
13014 (princ (format "BEGIN:VEVENT
13017 SUMMARY:%s
13018 END:VEVENT\n"
13019 (org-ical-ts-to-string ts "DTSTART")
13020 (org-ical-ts-to-string ts2 "DTEND" inc)
13021 hd)))
13022 (when org-icalendar-include-todo
13023 (goto-char (point-min))
13024 (while (re-search-forward org-todo-line-regexp nil t)
13025 (setq state (match-string 1))
13026 (unless (equal state org-done-string)
13027 (setq hd (match-string 3))
13028 (if (string-match org-priority-regexp hd)
13029 (setq pri (string-to-char (match-string 2 hd))
13030 hd (concat (substring hd 0 (match-beginning 1))
13031 (substring hd (- (match-end 1)))))
13032 (setq pri org-default-priority))
13033 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
13034 (- org-lowest-priority ?A))))))
13036 (princ (format "BEGIN:VTODO
13038 SUMMARY:%s
13039 SEQUENCE:1
13040 PRIORITY:%d
13041 END:VTODO\n"
13042 dts hd pri))))))))
13044 (defun org-start-icalendar-file (name)
13045 "Start an iCalendar file by inserting the header."
13046 (let ((user user-full-name)
13047 (name (or name "unknown"))
13048 (timezone (cadr (current-time-zone))))
13049 (princ
13050 (format "BEGIN:VCALENDAR
13051 VERSION:2.0
13052 X-WR-CALNAME:%s
13053 PRODID:-//%s//Emacs with Org-mode//EN
13054 X-WR-TIMEZONE:%s
13055 CALSCALE:GREGORIAN\n" name user timezone))))
13057 (defun org-finish-icalendar-file ()
13058 "Finish an iCalendar file by inserting the END statement."
13059 (princ "END:VCALENDAR\n"))
13061 (defun org-ical-ts-to-string (s keyword &optional inc)
13062 "Take a time string S and convert it to iCalendar format.
13063 KEYWORD is added in front, to make a complete line like DTSTART....
13064 When INC is non-nil, increase the hour by two (if time string contains
13065 a time), or the day by one (if it does not contain a time)."
13066 (let ((t1 (org-parse-time-string s 'nodefault))
13067 t2 fmt have-time time)
13068 (if (and (car t1) (nth 1 t1) (nth 2 t1))
13069 (setq t2 t1 have-time t)
13070 (setq t2 (org-parse-time-string s)))
13071 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
13072 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
13073 (when inc
13074 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
13075 (setq time (encode-time s mi h d m y)))
13076 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
13077 (concat keyword (format-time-string fmt time))))
13080 ;;; Key bindings
13082 ;; - Bindings in Org-mode map are currently
13083 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
13084 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
13085 ;; e (?) useful from outline-mode
13086 ;; i k @ expendable from outline-mode
13087 ;; 0123456789 % & ()_{} " ` free
13089 ;; Make `C-c C-x' a prefix key
13090 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
13092 ;; TAB key with modifiers
13093 (define-key org-mode-map "\C-i" 'org-cycle)
13094 (define-key org-mode-map [(tab)] 'org-cycle)
13095 (define-key org-mode-map [(meta tab)] 'org-complete)
13096 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
13097 ;; The following line is necessary under Suse GNU/Linux
13098 (unless (featurep 'xemacs)
13099 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
13100 (define-key org-mode-map [(shift tab)] 'org-shifttab)
13102 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
13103 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
13104 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13105 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
13106 (define-key org-mode-map [(meta return)] 'org-meta-return)
13107 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
13108 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
13110 ;; Cursor keys with modifiers
13111 (define-key org-mode-map [(meta left)] 'org-metaleft)
13112 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
13113 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
13114 (define-key org-mode-map [(meta right)] 'org-metaright)
13115 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
13116 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
13117 (define-key org-mode-map [(meta up)] 'org-metaup)
13118 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
13119 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
13120 (define-key org-mode-map [(meta down)] 'org-metadown)
13121 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
13122 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
13124 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13125 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
13126 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
13127 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
13128 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
13129 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
13130 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
13131 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
13132 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
13133 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
13134 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
13135 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
13136 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
13137 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
13138 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
13139 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
13141 ;; All the other keys
13143 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13144 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
13145 (define-key org-mode-map "\C-c\C-j" 'org-goto)
13146 (define-key org-mode-map "\C-c\C-t" 'org-todo)
13147 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
13148 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
13149 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
13150 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13151 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
13152 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
13153 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13154 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
13155 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
13156 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
13157 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
13158 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
13159 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
13160 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
13161 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13162 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13163 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13164 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13165 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
13166 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
13167 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13168 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
13169 (define-key org-mode-map "\C-c]" 'org-remove-file)
13170 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
13171 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
13172 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
13173 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13174 (define-key org-mode-map "\C-m" 'org-return)
13175 (define-key org-mode-map "\C-c?" 'org-table-current-column)
13176 (define-key org-mode-map "\C-c " 'org-table-blank-field)
13177 (define-key org-mode-map "\C-c+" 'org-table-sum)
13178 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
13179 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
13180 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
13181 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13182 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
13183 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13184 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
13185 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
13186 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
13187 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
13188 (define-key org-mode-map "\C-c\C-xv" 'org-export-visible)
13189 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-visible)
13190 ;; OPML support is only an option for the future
13191 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
13192 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
13193 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
13194 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
13195 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
13196 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13197 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
13198 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13199 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
13200 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
13201 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
13202 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
13203 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
13205 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
13206 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13207 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13208 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13210 (when (featurep 'xemacs)
13211 (define-key org-mode-map 'button3 'popup-mode-menu))
13213 (defsubst org-table-p () (org-at-table-p))
13215 (defun org-self-insert-command (N)
13216 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13217 If the cursor is in a table looking at whitespace, the whitespace is
13218 overwritten, and the table is not marked as requiring realignment."
13219 (interactive "p")
13220 (if (and (org-table-p)
13221 (progn
13222 ;; check if we blank the field, and if that triggers align
13223 (and org-table-auto-blank-field
13224 (member last-command
13225 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13226 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13227 ;; got extra space, this field does not determine column width
13228 (let (org-table-may-need-update) (org-table-blank-field))
13229 ;; no extra space, this field may determine column width
13230 (org-table-blank-field)))
13232 (eq N 1)
13233 (looking-at "[^|\n]* |"))
13234 (let (org-table-may-need-update)
13235 (goto-char (1- (match-end 0)))
13236 (delete-backward-char 1)
13237 (goto-char (match-beginning 0))
13238 (self-insert-command N))
13239 (setq org-table-may-need-update t)
13240 (self-insert-command N)))
13242 (defun org-delete-backward-char (N)
13243 "Like `delete-backward-char', insert whitespace at field end in tables.
13244 When deleting backwards, in tables this function will insert whitespace in
13245 front of the next \"|\" separator, to keep the table aligned. The table will
13246 still be marked for re-alignment if the field did fill the entire column,
13247 because, in this case the deletion might narrow the column."
13248 (interactive "p")
13249 (if (and (org-table-p)
13250 (eq N 1)
13251 (string-match "|" (buffer-substring (point-at-bol) (point)))
13252 (looking-at ".*?|"))
13253 (let ((pos (point))
13254 (noalign (looking-at "[^|\n\r]* |"))
13255 (c org-table-may-need-update))
13256 (backward-delete-char N)
13257 (skip-chars-forward "^|")
13258 (insert " ")
13259 (goto-char (1- pos))
13260 ;; noalign: if there were two spaces at the end, this field
13261 ;; does not determine the width of the column.
13262 (if noalign (setq org-table-may-need-update c)))
13263 (backward-delete-char N)))
13265 (defun org-delete-char (N)
13266 "Like `delete-char', but insert whitespace at field end in tables.
13267 When deleting characters, in tables this function will insert whitespace in
13268 front of the next \"|\" separator, to keep the table aligned. The table will
13269 still be marked for re-alignment if the field did fill the entire column,
13270 because, in this case the deletion might narrow the column."
13271 (interactive "p")
13272 (if (and (org-table-p)
13273 (not (bolp))
13274 (not (= (char-after) ?|))
13275 (eq N 1))
13276 (if (looking-at ".*?|")
13277 (let ((pos (point))
13278 (noalign (looking-at "[^|\n\r]* |"))
13279 (c org-table-may-need-update))
13280 (replace-match (concat
13281 (substring (match-string 0) 1 -1)
13282 " |"))
13283 (goto-char pos)
13284 ;; noalign: if there were two spaces at the end, this field
13285 ;; does not determine the width of the column.
13286 (if noalign (setq org-table-may-need-update c)))
13287 (delete-char N))
13288 (delete-char N)))
13290 ;; How to do this: Measure non-white length of current string
13291 ;; If equal to column width, we should realign.
13293 (defun org-remap (map &rest commands)
13294 "In MAP, remap the functions given in COMMANDS.
13295 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13296 (let (new old)
13297 (while commands
13298 (setq old (pop commands) new (pop commands))
13299 (if (fboundp 'command-remapping)
13300 (define-key map (vector 'remap old) new)
13301 (substitute-key-definition old new map global-map)))))
13303 (when (eq org-enable-table-editor 'optimized)
13304 ;; If the user wants maximum table support, we need to hijack
13305 ;; some standard editing functions
13306 (org-remap org-mode-map
13307 'self-insert-command 'org-self-insert-command
13308 'delete-char 'org-delete-char
13309 'delete-backward-char 'org-delete-backward-char)
13310 (define-key org-mode-map "|" 'org-force-self-insert))
13312 (defun org-shiftcursor-error ()
13313 "Throw an error because Shift-Cursor command was applied in wrong context."
13314 (error "This command is active in special context like tables, headlines or timestamps"))
13316 (defun org-shifttab ()
13317 "Global visibility cycling or move to previous table field.
13318 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13319 on context.
13320 See the individual commands for more information."
13321 (interactive)
13322 (cond
13323 ((org-at-table-p) (org-table-previous-field))
13324 (t (org-cycle '(4)))))
13326 (defun org-shiftmetaleft ()
13327 "Promote subtree or delete table column.
13328 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
13329 See the individual commands for more information."
13330 (interactive)
13331 (cond
13332 ((org-at-table-p) (org-table-delete-column))
13333 ((org-on-heading-p) (org-promote-subtree))
13334 ((org-at-item-p) (call-interactively 'org-outdent-item))
13335 (t (org-shiftcursor-error))))
13337 (defun org-shiftmetaright ()
13338 "Demote subtree or insert table column.
13339 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
13340 See the individual commands for more information."
13341 (interactive)
13342 (cond
13343 ((org-at-table-p) (org-table-insert-column))
13344 ((org-on-heading-p) (org-demote-subtree))
13345 ((org-at-item-p) (call-interactively 'org-indent-item))
13346 (t (org-shiftcursor-error))))
13348 (defun org-shiftmetaup (&optional arg)
13349 "Move subtree up or kill table row.
13350 Calls `org-move-subtree-up' or `org-table-kill-row' or
13351 `org-move-item-up' depending on context. See the individual commands
13352 for more information."
13353 (interactive "P")
13354 (cond
13355 ((org-at-table-p) (org-table-kill-row))
13356 ((org-on-heading-p) (org-move-subtree-up arg))
13357 ((org-at-item-p) (org-move-item-up arg))
13358 (t (org-shiftcursor-error))))
13359 (defun org-shiftmetadown (&optional arg)
13360 "Move subtree down or insert table row.
13361 Calls `org-move-subtree-down' or `org-table-insert-row' or
13362 `org-move-item-down', depending on context. See the individual
13363 commands for more information."
13364 (interactive "P")
13365 (cond
13366 ((org-at-table-p) (org-table-insert-row arg))
13367 ((org-on-heading-p) (org-move-subtree-down arg))
13368 ((org-at-item-p) (org-move-item-down arg))
13369 (t (org-shiftcursor-error))))
13371 (defun org-metaleft (&optional arg)
13372 "Promote heading or move table column to left.
13373 Calls `org-do-promote' or `org-table-move-column', depending on context.
13374 With no specific context, calls the Emacs default `backward-word'.
13375 See the individual commands for more information."
13376 (interactive "P")
13377 (cond
13378 ((org-at-table-p) (org-table-move-column 'left))
13379 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
13380 (t (backward-word (prefix-numeric-value arg)))))
13382 (defun org-metaright (&optional arg)
13383 "Demote subtree or move table column to right.
13384 Calls `org-do-demote' or `org-table-move-column', depending on context.
13385 With no specific context, calls the Emacs default `forward-word'.
13386 See the individual commands for more information."
13387 (interactive "P")
13388 (cond
13389 ((org-at-table-p) (org-table-move-column nil))
13390 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
13391 (t (forward-word (prefix-numeric-value arg)))))
13393 (defun org-metaup (&optional arg)
13394 "Move subtree up or move table row up.
13395 Calls `org-move-subtree-up' or `org-table-move-row' or
13396 `org-move-item-up', depending on context. See the individual commands
13397 for more information."
13398 (interactive "P")
13399 (cond
13400 ((org-at-table-p) (org-table-move-row 'up))
13401 ((org-on-heading-p) (org-move-subtree-up arg))
13402 ((org-at-item-p) (org-move-item-up arg))
13403 (t (org-shiftcursor-error))))
13405 (defun org-metadown (&optional arg)
13406 "Move subtree down or move table row down.
13407 Calls `org-move-subtree-down' or `org-table-move-row' or
13408 `org-move-item-down', depending on context. See the individual
13409 commands for more information."
13410 (interactive "P")
13411 (cond
13412 ((org-at-table-p) (org-table-move-row nil))
13413 ((org-on-heading-p) (org-move-subtree-down arg))
13414 ((org-at-item-p) (org-move-item-down arg))
13415 (t (org-shiftcursor-error))))
13417 (defun org-shiftup (&optional arg)
13418 "Increase item in timestamp or increase priority of current item.
13419 Calls `org-timestamp-up' or `org-priority-up', depending on context.
13420 See the individual commands for more information."
13421 (interactive "P")
13422 (cond
13423 ((org-at-timestamp-p) (org-timestamp-up arg))
13424 (t (org-priority-up))))
13426 (defun org-shiftdown (&optional arg)
13427 "Decrease item in timestamp or decrease priority of current item.
13428 Calls `org-timestamp-down' or `org-priority-down', depending on context.
13429 See the individual commands for more information."
13430 (interactive "P")
13431 (cond
13432 ((org-at-timestamp-p) (org-timestamp-down arg))
13433 (t (org-priority-down))))
13435 (defun org-shiftright ()
13436 "Next TODO keyword or timestamp one day later, depending on context."
13437 (interactive)
13438 (cond
13439 ((org-at-timestamp-p) (org-timestamp-up-day))
13440 ((org-on-heading-p) (org-todo 'right))
13441 (t (org-shiftcursor-error))))
13443 (defun org-shiftleft ()
13444 "Previous TODO keyword or timestamp one day earlier, depending on context."
13445 (interactive)
13446 (cond
13447 ((org-at-timestamp-p) (org-timestamp-down-day))
13448 ((org-on-heading-p) (org-todo 'left))
13449 (t (org-shiftcursor-error))))
13451 (defun org-copy-special ()
13452 "Copy region in table or copy current subtree.
13453 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13454 See the individual commands for more information."
13455 (interactive)
13456 (call-interactively
13457 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13459 (defun org-cut-special ()
13460 "Cut region in table or cut current subtree.
13461 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13462 See the individual commands for more information."
13463 (interactive)
13464 (call-interactively
13465 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13467 (defun org-paste-special (arg)
13468 "Paste rectangular region into table, or past subtree relative to level.
13469 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13470 See the individual commands for more information."
13471 (interactive "P")
13472 (if (org-at-table-p)
13473 (org-table-paste-rectangle)
13474 (org-paste-subtree arg)))
13476 (defun org-ctrl-c-ctrl-c (&optional arg)
13477 "Set tags in headline, or update according to changed information at point.
13479 This command does many different things, depending on context:
13481 - If the cursor is in a headline, prompt for tags and insert them
13482 into the current line, aligned to `org-tags-column'. When called
13483 with prefix arg, realign all tags in the current buffer.
13485 - If the cursor is in one of the special #+KEYWORD lines, this
13486 triggers scanning the buffer for these lines and updating the
13487 information.
13489 - If the cursor is inside a table, realign the table. This command
13490 works even if the automatic table editor has been turned off.
13492 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13493 the entire table.
13495 - If the cursor is inside a table created by the table.el package,
13496 activate that table.
13498 - If the current buffer is a remember buffer, close note and file it.
13499 with a prefix argument, file it without further interaction to the default
13500 location.
13502 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13503 links in this buffer.
13505 - If the cursor is on a numbered item in a plain list, renumber the
13506 ordered list."
13507 (interactive "P")
13508 (let ((org-enable-table-editor t))
13509 (cond
13510 ((and (local-variable-p 'org-finish-function (current-buffer))
13511 (fboundp org-finish-function))
13512 (funcall org-finish-function))
13513 ((org-on-target-p) (org-update-radio-target-regexp))
13514 ((org-on-heading-p) (org-set-tags arg))
13515 ((org-at-table.el-p)
13516 (require 'table)
13517 (beginning-of-line 1)
13518 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13519 (table-recognize-table))
13520 ((org-at-table-p)
13521 (org-table-maybe-eval-formula)
13522 (if arg
13523 (org-table-recalculate t)
13524 (org-table-maybe-recalculate-line))
13525 (org-table-align))
13526 ((org-at-item-p)
13527 (org-renumber-ordered-list (prefix-numeric-value arg)))
13528 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13529 (cond
13530 ((equal (match-string 1) "TBLFM")
13531 ;; Recalculate the table before this line
13532 (save-excursion
13533 (beginning-of-line 1)
13534 (skip-chars-backward " \r\n\t")
13535 (if (org-at-table-p) (org-table-recalculate t))))
13537 (org-mode-restart))))
13538 (t (error "C-c C-c can do nothing useful at this location.")))))
13540 (defun org-mode-restart ()
13541 "Restart Org-mode, to scan again for special lines.
13542 Also updates the keyword regular expressions."
13543 (interactive)
13544 (let ((org-inhibit-startup t)) (org-mode))
13545 (message "Org-mode restarted to refresh keyword and special line setup"))
13547 (defun org-return ()
13548 "Goto next table row or insert a newline.
13549 Calls `org-table-next-row' or `newline', depending on context.
13550 See the individual commands for more information."
13551 (interactive)
13552 (cond
13553 ((org-at-table-p)
13554 (org-table-justify-field-maybe)
13555 (org-table-next-row))
13556 (t (newline))))
13558 (defun org-meta-return (&optional arg)
13559 "Insert a new heading or wrap a region in a table.
13560 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13561 See the individual commands for more information."
13562 (interactive "P")
13563 (cond
13564 ((org-at-table-p)
13565 (org-table-wrap-region arg))
13566 (t (org-insert-heading arg))))
13568 ;;; Menu entries
13570 ;; Define the Org-mode menus
13571 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13572 '("Tbl"
13573 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
13574 ["Next Field" org-cycle (org-at-table-p)]
13575 ["Previous Field" org-shifttab (org-at-table-p)]
13576 ["Next Row" org-return (org-at-table-p)]
13577 "--"
13578 ["Blank Field" org-table-blank-field (org-at-table-p)]
13579 ["Edit Field" org-table-edit-field (org-at-table-p)]
13580 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13581 "--"
13582 ("Column"
13583 ["Move Column Left" org-metaleft (org-at-table-p)]
13584 ["Move Column Right" org-metaright (org-at-table-p)]
13585 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13586 ["Insert Column" org-shiftmetaright (org-at-table-p)]
13587 "--"
13588 ["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])
13589 ("Row"
13590 ["Move Row Up" org-metaup (org-at-table-p)]
13591 ["Move Row Down" org-metadown (org-at-table-p)]
13592 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13593 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13594 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13595 "--"
13596 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
13597 ("Rectangle"
13598 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13599 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13600 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13601 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13602 "--"
13603 ("Calculate"
13604 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13605 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13606 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13607 "--"
13608 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13609 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13610 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13611 "--"
13612 ["Sum Column/Rectangle" org-table-sum
13613 (or (org-at-table-p) (org-region-active-p))]
13614 ["Which Column?" org-table-current-column (org-at-table-p)])
13615 ["Debug Formulas"
13616 (setq org-table-formula-debug (not org-table-formula-debug))
13617 :style toggle :selected org-table-formula-debug]
13618 "--"
13619 ["Create" org-table-create (and (not (org-at-table-p))
13620 org-enable-table-editor)]
13621 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13622 ["Import from File" org-table-import (not (org-at-table-p))]
13623 ["Export to File" org-table-export (org-at-table-p)]
13624 "--"
13625 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13627 (easy-menu-define org-org-menu org-mode-map "Org menu"
13628 '("Org"
13629 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13630 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13631 ["Sparse Tree" org-occur t]
13632 ["Show All" show-all t]
13633 "--"
13634 ["New Heading" org-insert-heading t]
13635 ("Navigate Headings"
13636 ["Up" outline-up-heading t]
13637 ["Next" outline-next-visible-heading t]
13638 ["Previous" outline-previous-visible-heading t]
13639 ["Next Same Level" outline-forward-same-level t]
13640 ["Previous Same Level" outline-backward-same-level t]
13641 "--"
13642 ["Jump" org-goto t])
13643 ("Edit Structure"
13644 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13645 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13646 "--"
13647 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13648 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13649 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13650 "--"
13651 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13652 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13653 ["Demote Heading" org-metaright (not (org-at-table-p))]
13654 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13655 "--"
13656 ["Archive Subtree" org-archive-subtree t]
13657 "--"
13658 ["Convert to odd levels" org-convert-to-odd-levels t]
13659 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13660 "--"
13661 ("TODO Lists"
13662 ["TODO/DONE/-" org-todo t]
13663 ["Show TODO Tree" org-show-todo-tree t]
13664 ["Global TODO list" org-todo-list t]
13665 "--"
13666 ["Set Priority" org-priority t]
13667 ["Priority Up" org-shiftup t]
13668 ["Priority Down" org-shiftdown t])
13669 ("Dates and Scheduling"
13670 ["Timestamp" org-time-stamp t]
13671 ["Timestamp (inactive)" org-time-stamp-inactive t]
13672 ("Change Date"
13673 ["1 Day Later" org-timestamp-up-day t]
13674 ["1 Day Earlier" org-timestamp-down-day t]
13675 ["1 ... Later" org-shiftup t]
13676 ["1 ... Earlier" org-shiftdown t])
13677 ["Compute Time Range" org-evaluate-time-range t]
13678 ["Schedule Item" org-schedule t]
13679 ["Deadline" org-deadline t]
13680 "--"
13681 ["Goto Calendar" org-goto-calendar t]
13682 ["Date from Calendar" org-date-from-calendar t])
13683 "--"
13684 ["Agenda Command" org-agenda t]
13685 ("File List for Agenda")
13686 ("Special views current file"
13687 ["TODO Tree" org-show-todo-tree t]
13688 ["Check Deadlines" org-check-deadlines t]
13689 ["Timeline" org-timeline t]
13690 ["Tags Tree" org-tags-sparse-tree t])
13691 "--"
13692 ("Hyperlinks"
13693 ["Store Link (Global)" org-store-link t]
13694 ["Insert Link" org-insert-link t]
13695 ["Follow Link" org-open-at-point t]
13696 "--"
13697 ["Descriptive Links"
13698 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13699 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13700 ["Literal Links"
13701 (progn
13702 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13703 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13704 "--"
13705 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13706 (save-excursion (goto-char (point-min))
13707 (re-search-forward "<[a-z]+:" nil t))])
13708 "--"
13709 ("Export"
13710 ["ASCII" org-export-as-ascii t]
13711 ["Export visible part..." org-export-visible t]
13712 ["HTML" org-export-as-html t]
13713 ["HTML and Open" org-export-as-html-and-open t]
13714 ["XML (XOXO)" org-export-as-xml t]
13715 "--"
13716 ["iCalendar this file" org-export-icalendar-this-file t]
13717 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13718 :active t :keys "C-c C-x C-i"]
13719 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13720 "--"
13721 ["Option Template" org-insert-export-options-template t]
13722 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13723 ("Publish"
13724 ["Current File" org-publish-current-file t]
13725 ["Current Project" org-publish-current-project t]
13726 ["Project..." org-publish t]
13727 ["All Projects" org-publish-all t])
13728 "--"
13729 ("Documentation"
13730 ["Show Version" org-version t]
13731 ["Info Documentation" org-info t])
13732 ("Customize"
13733 ["Browse Org Group" org-customize t]
13734 "--"
13735 ["Expand This Menu" org-create-customize-menu
13736 (fboundp 'customize-menu-create)])
13737 "--"
13738 ["Refresh setup" org-mode-restart t]
13741 (defun org-info (&optional node)
13742 "Read documentation for Org-mode in the info system.
13743 With optional NODE, go directly to that node."
13744 (interactive)
13745 (require 'info)
13746 (Info-goto-node (format "(org)%s" (or node ""))))
13748 (defun org-install-agenda-files-menu ()
13749 (let ((bl (buffer-list)))
13750 (save-excursion
13751 (while bl
13752 (set-buffer (pop bl))
13753 (if (eq major-mode 'org-mode) (setq bl nil)))
13754 (when (eq major-mode 'org-mode)
13755 (easy-menu-change
13756 '("Org") "File List for Agenda"
13757 (append
13758 (list
13759 ["Edit File List" (org-edit-agenda-file-list) t]
13760 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13761 ["Remove Current File from List" org-remove-file t]
13762 ["Cycle through agenda files" org-cycle-agenda-files t]
13763 "--")
13764 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13766 ;;; Documentation
13768 (defun org-customize ()
13769 "Call the customize function with org as argument."
13770 (interactive)
13771 (customize-browse 'org))
13773 (defun org-create-customize-menu ()
13774 "Create a full customization menu for Org-mode, insert it into the menu."
13775 (interactive)
13776 (if (fboundp 'customize-menu-create)
13777 (progn
13778 (easy-menu-change
13779 '("Org") "Customize"
13780 `(["Browse Org group" org-customize t]
13781 "--"
13782 ,(customize-menu-create 'org)
13783 ["Set" Custom-set t]
13784 ["Save" Custom-save t]
13785 ["Reset to Current" Custom-reset-current t]
13786 ["Reset to Saved" Custom-reset-saved t]
13787 ["Reset to Standard Settings" Custom-reset-standard t]))
13788 (message "\"Org\"-menu now contains full customization menu"))
13789 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13791 ;;; Miscellaneous stuff
13793 (defun org-move-line-down (arg)
13794 "Move the current line down. With prefix argument, move it past ARG lines."
13795 (interactive "p")
13796 (let ((col (current-column))
13797 beg end pos)
13798 (beginning-of-line 1) (setq beg (point))
13799 (beginning-of-line 2) (setq end (point))
13800 (beginning-of-line (+ 1 arg))
13801 (setq pos (move-marker (make-marker) (point)))
13802 (insert (delete-and-extract-region beg end))
13803 (goto-char pos)
13804 (move-to-column col)))
13806 (defun org-move-line-up (arg)
13807 "Move the current line up. With prefix argument, move it past ARG lines."
13808 (interactive "p")
13809 (let ((col (current-column))
13810 beg end pos)
13811 (beginning-of-line 1) (setq beg (point))
13812 (beginning-of-line 2) (setq end (point))
13813 (beginning-of-line (- arg))
13814 (setq pos (move-marker (make-marker) (point)))
13815 (insert (delete-and-extract-region beg end))
13816 (goto-char pos)
13817 (move-to-column col)))
13819 ;; Paragraph filling stuff.
13820 ;; We want this to be just right, so use the full arsenal.
13821 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13822 ;; filladapt package works slightly differently.
13824 (defun org-set-autofill-regexps ()
13825 (interactive)
13826 ;; In the paragraph separator we include headlines, because filling
13827 ;; text in a line directly attached to a headline would otherwise
13828 ;; fill the headline as well.
13829 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13830 ;; The paragraph starter includes hand-formatted lists.
13831 (set (make-local-variable 'paragraph-start)
13832 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13833 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13834 ;; But only if the user has not turned off tables or fixed-width regions
13835 (set (make-local-variable 'auto-fill-inhibit-regexp)
13836 (concat "\\*\\|#"
13837 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13838 (concat
13839 "\\|[ \t]*["
13840 (if org-enable-table-editor "|" "")
13841 (if org-enable-fixed-width-editor ":" "")
13842 "]"))))
13843 ;; We use our own fill-paragraph function, to make sure that tables
13844 ;; and fixed-width regions are not wrapped. That function will pass
13845 ;; through to `fill-paragraph' when appropriate.
13846 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13847 ;; Adaptive filling: To get full control, first make sure that
13848 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13849 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13850 (set (make-local-variable 'adaptive-fill-function)
13851 'org-adaptive-fill-function))
13853 (defun org-fill-paragraph (&optional justify)
13854 "Re-align a table, pass through to fill-paragraph if no table."
13855 (let ((table-p (org-at-table-p))
13856 (table.el-p (org-at-table.el-p)))
13857 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13858 (table.el-p t) ; skip table.el tables
13859 (table-p (org-table-align) t) ; align org-mode tables
13860 (t nil)))) ; call paragraph-fill
13862 ;; For reference, this is the default value of adaptive-fill-regexp
13863 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13865 (defun org-adaptive-fill-function ()
13866 "Return a fill prefix for org-mode files.
13867 In particular, this makes sure hanging paragraphs for hand-formatted lists
13868 work correctly."
13869 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13870 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13872 ;; Functions needed for Emacs/XEmacs region compatibility
13874 (defun org-add-hook (hook function &optional append local)
13875 "Add-hook, compatible with both Emacsen."
13876 (if (and local (featurep 'xemacs))
13877 (add-local-hook hook function append)
13878 (add-hook hook function append local)))
13880 (defun org-region-active-p ()
13881 "Is `transient-mark-mode' on and the region active?
13882 Works on both Emacs and XEmacs."
13883 (if org-ignore-region
13885 (if (featurep 'xemacs)
13886 (and zmacs-regions (region-active-p))
13887 (and transient-mark-mode mark-active))))
13889 (defun org-add-to-invisibility-spec (arg)
13890 "Add elements to `buffer-invisibility-spec'.
13891 See documentation for `buffer-invisibility-spec' for the kind of elements
13892 that can be added."
13893 (cond
13894 ((fboundp 'add-to-invisibility-spec)
13895 (add-to-invisibility-spec arg))
13896 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13897 (setq buffer-invisibility-spec (list arg)))
13899 (setq buffer-invisibility-spec
13900 (cons arg buffer-invisibility-spec)))))
13902 (defun org-remove-from-invisibility-spec (arg)
13903 "Remove elements from `buffer-invisibility-spec'."
13904 (if (fboundp 'remove-from-invisibility-spec)
13905 (remove-from-invisibility-spec arg)
13906 (if (consp buffer-invisibility-spec)
13907 (setq buffer-invisibility-spec
13908 (delete arg buffer-invisibility-spec)))))
13910 (defun org-in-invisibility-spec-p (arg)
13911 "Is ARG a member of `buffer-invisibility-spec'?"
13912 (if (consp buffer-invisibility-spec)
13913 (member arg buffer-invisibility-spec)
13914 nil))
13916 (defun org-image-file-name-regexp ()
13917 "Return regexp matching the file names of images."
13918 (if (fboundp 'image-file-name-regexp)
13919 (image-file-name-regexp)
13920 (let ((image-file-name-extensions
13921 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13922 "xbm" "xpm" "pbm" "pgm" "ppm")))
13923 (concat "\\."
13924 (regexp-opt (nconc (mapcar 'upcase
13925 image-file-name-extensions)
13926 image-file-name-extensions)
13928 "\\'"))))
13930 ;; Functions needed for compatibility with old outline.el.
13932 ;; Programming for the old outline.el (that uses selective display
13933 ;; instead of `invisible' text properties) is a nightmare, mostly
13934 ;; because regular expressions can no longer be anchored at
13935 ;; beginning/end of line. Therefore a number of function need special
13936 ;; treatment when the old outline.el is being used.
13938 ;; The following functions capture almost the entire compatibility code
13939 ;; between the different versions of outline-mode. The only other
13940 ;; places where this is important are the font-lock-keywords, and in
13941 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
13943 ;; C-a should go to the beginning of a *visible* line, also in the
13944 ;; new outline.el. I guess this should be patched into Emacs?
13945 (defun org-beginning-of-line ()
13946 "Go to the beginning of the current line. If that is invisible, continue
13947 to a visible line beginning. This makes the function of C-a more intuitive."
13948 (interactive)
13949 (beginning-of-line 1)
13950 (if (bobp)
13952 (backward-char 1)
13953 (if (org-invisible-p)
13954 (while (and (not (bobp)) (org-invisible-p))
13955 (backward-char 1)
13956 (beginning-of-line 1))
13957 (forward-char 1))))
13959 (when org-noutline-p
13960 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13961 ;; FIXME: should I use substitute-key-definition to reach other bindings
13962 ;; of beginning-of-line?
13964 (defun org-invisible-p ()
13965 "Check if point is at a character currently not visible."
13966 (if org-noutline-p
13967 ;; Early versions of noutline don't have `outline-invisible-p'.
13968 (if (fboundp 'outline-invisible-p)
13969 (outline-invisible-p)
13970 (get-char-property (point) 'invisible))
13971 (save-excursion
13972 (skip-chars-backward "^\r\n")
13973 (equal (char-before) ?\r))))
13975 (defun org-invisible-p2 ()
13976 "Check if point is at a character currently not visible."
13977 (save-excursion
13978 (if org-noutline-p
13979 (progn
13980 (if (and (eolp) (not (bobp))) (backward-char 1))
13981 ;; Early versions of noutline don't have `outline-invisible-p'.
13982 (if (fboundp 'outline-invisible-p)
13983 (outline-invisible-p)
13984 (get-char-property (point) 'invisible)))
13985 (skip-chars-backward "^\r\n")
13986 (equal (char-before) ?\r))))
13988 (defun org-back-to-heading (&optional invisible-ok)
13989 "Move to previous heading line, or beg of this line if it's a heading.
13990 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13991 (if org-noutline-p
13992 (outline-back-to-heading invisible-ok)
13993 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
13994 (looking-at outline-regexp))
13996 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13997 outline-regexp)
13998 nil t)
13999 (if invisible-ok
14000 (progn (goto-char (or (match-end 1) (match-beginning 0)))
14001 (looking-at outline-regexp)))
14002 (error "Before first heading")))))
14004 (defun org-on-heading-p (&optional invisible-ok)
14005 "Return t if point is on a (visible) heading line.
14006 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
14007 (if org-noutline-p
14008 (outline-on-heading-p 'invisible-ok)
14009 (save-excursion
14010 (skip-chars-backward "^\n\r")
14011 (and (looking-at outline-regexp)
14012 (or invisible-ok
14013 (bobp)
14014 (equal (char-before) ?\n))))))
14016 (defun org-on-target-p ()
14017 (let ((pos (point)))
14018 (save-excursion
14019 (skip-chars-forward "<")
14020 (and (re-search-backward "<<" nil t)
14021 (or (looking-at org-radio-target-regexp)
14022 (looking-at org-target-regexp))
14023 (<= (match-beginning 0) pos)
14024 (>= (1+ (match-end 0)) pos)))))
14026 (defun org-up-heading-all (arg)
14027 "Move to the heading line of which the present line is a subheading.
14028 This function considers both visible and invisible heading lines.
14029 With argument, move up ARG levels."
14030 (if org-noutline-p
14031 (if (fboundp 'outline-up-heading-all)
14032 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14033 (outline-up-heading arg t)) ; emacs 22 version of outline.el
14034 (org-back-to-heading t)
14035 (looking-at outline-regexp)
14036 (if (<= (- (match-end 0) (match-beginning 0)) arg)
14037 (error "Cannot move up %d levels" arg)
14038 (re-search-backward
14039 (concat "[\n\r]" (regexp-quote
14040 (make-string (- (match-end 0) (match-beginning 0) arg)
14041 ?*))
14042 "[^*]"))
14043 (forward-char 1))))
14045 (defun org-show-hidden-entry ()
14046 "Show an entry where even the heading is hidden."
14047 (save-excursion
14048 (if (not org-noutline-p)
14049 (progn
14050 (org-back-to-heading t)
14051 (org-flag-heading nil)))
14052 (org-show-entry)))
14054 (defun org-check-occur-regexp (regexp)
14055 "If REGEXP starts with \"^\", modify it to check for \\r as well.
14056 Of course, only for the old outline mode."
14057 (if org-noutline-p
14058 regexp
14059 (if (string-match "^\\^" regexp)
14060 (concat "[\n\r]" (substring regexp 1))
14061 regexp)))
14063 (defun org-flag-heading (flag &optional entry)
14064 "Flag the current heading. FLAG non-nil means make invisible.
14065 When ENTRY is non-nil, show the entire entry."
14066 (save-excursion
14067 (org-back-to-heading t)
14068 (if (not org-noutline-p)
14069 ;; Make the current headline visible
14070 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
14071 ;; Check if we should show the entire entry
14072 (if entry
14073 (progn
14074 (org-show-entry)
14075 (save-excursion ;; FIXME: Is this the fix for points in the -|
14076 ;; middle of text? |
14077 (and (outline-next-heading) ;; |
14078 (org-flag-heading nil)))) ; show the next heading _|
14079 (outline-flag-region (max 1 (1- (point)))
14080 (save-excursion (outline-end-of-heading) (point))
14081 (if org-noutline-p
14082 flag
14083 (if flag ?\r ?\n))))))
14085 (defun org-end-of-subtree (&optional invisible-OK)
14086 ;; This is an exact copy of the original function, but it uses
14087 ;; `org-back-to-heading', to make it work also in invisible
14088 ;; trees. And is uses an invisible-OK argument.
14089 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14090 (org-back-to-heading invisible-OK)
14091 (let ((first t)
14092 (level (funcall outline-level)))
14093 (while (and (not (eobp))
14094 (or first (> (funcall outline-level) level)))
14095 (setq first nil)
14096 (outline-next-heading))
14097 (if (memq (preceding-char) '(?\n ?\^M))
14098 (progn
14099 ;; Go to end of line before heading
14100 (forward-char -1)
14101 (if (memq (preceding-char) '(?\n ?\^M))
14102 ;; leave blank line before heading
14103 (forward-char -1))))))
14105 (defun org-show-subtree ()
14106 "Show everything after this heading at deeper levels."
14107 (outline-flag-region
14108 (point)
14109 (save-excursion
14110 (outline-end-of-subtree) (outline-next-heading) (point))
14111 (if org-noutline-p nil ?\n)))
14113 (defun org-show-entry ()
14114 "Show the body directly following this heading.
14115 Show the heading too, if it is currently invisible."
14116 (interactive)
14117 (save-excursion
14118 (org-back-to-heading t)
14119 (outline-flag-region
14120 (max 1 (1- (point)))
14121 (save-excursion
14122 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14123 (or (match-beginning 1) (point-max)))
14124 (if org-noutline-p nil ?\n))))
14126 (defun org-make-options-regexp (kwds)
14127 "Make a regular expression for keyword lines."
14128 (concat
14129 (if org-noutline-p "^" "[\n\r]")
14130 "#?[ \t]*\\+\\("
14131 (mapconcat 'regexp-quote kwds "\\|")
14132 "\\):[ \t]*"
14133 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
14135 ;; Make `bookmark-jump' show the jump location if it was hidden.
14136 (eval-after-load "bookmark"
14137 '(if (boundp 'bookmark-after-jump-hook)
14138 ;; We can use the hook
14139 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14140 ;; Hook not available, use advice
14141 (defadvice bookmark-jump (after org-make-visible activate)
14142 "Make the position visible."
14143 (org-bookmark-jump-unhide))))
14145 (defun org-bookmark-jump-unhide ()
14146 "Unhide the current position, to show the bookmark location."
14147 (and (eq major-mode 'org-mode)
14148 (or (org-invisible-p)
14149 (save-excursion (goto-char (max (point-min) (1- (point))))
14150 (org-invisible-p)))
14151 (org-show-hierarchy-above)))
14153 ;;; Finish up
14155 (provide 'org)
14157 (run-hooks 'org-load-hook)
14160 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14161 ;;; org.el ends here