Release 4.26
[org-mode/org-mode-NeilSmithlineMods.git] / org.el
blob36836fe6ad82dd05082b44319430050c4cb80a14
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.26
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.26
85 ;; - Bug fixes.
87 ;; Version 4.25
88 ;; - Revision of the font-lock faces section, with better tty support.
89 ;; - TODO keywords in Agenda buffer are fontified.
90 ;; - Export converts links between .org files to links between .html files.
91 ;; - Better support for bold/italic/underline emphasis.
93 ;; Version 4.24
94 ;; - Bug fixes.
96 ;; Version 4.23
97 ;; - Bug fixes.
99 ;; Version 4.22
100 ;; - Bug fixes.
101 ;; - In agenda buffer, mouse-1 no longer follows link.
102 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
104 ;; Version 4.20
105 ;; - Links use now the [[link][description]] format by default.
106 ;; When inserting links, the user is prompted for a description.
107 ;; - If a link has a description, only the description is displayed
108 ;; the link part is hidden. Use C-c C-l to edit the link part.
109 ;; - TAGS are now bold, but in the same color as the headline.
110 ;; - The width of a table column can be limited by using a field "<N>".
111 ;; - New structure for the customization tree.
112 ;; - Bug fixes.
114 ;; Version 4.13
115 ;; - The list of agenda files can be maintainted in an external file.
116 ;; - Bug fixes.
118 ;; Version 4.12
119 ;; - Templates for remember buffer. Note that the remember setup changes.
120 ;; To set up templates, see `org-remember-templates'.
121 ;; - The time in new time stamps can be rounded, see new option
122 ;; `org-time-stamp-rounding-minutes'.
123 ;; - Bug fixes (there are *always* more bugs).
125 ;;; Code:
127 (eval-when-compile
128 (require 'cl)
129 (require 'calendar))
130 (require 'outline)
131 (require 'time-date)
132 (require 'easymenu)
134 (defvar calc-embedded-close-formula) ; defined by the calc package
135 (defvar calc-embedded-open-formula) ; defined by the calc package
136 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
138 ;;; Customization variables
140 (defvar org-version "4.26"
141 "The version number of the file org.el.")
142 (defun org-version ()
143 (interactive)
144 (message "Org-mode version %s" org-version))
146 ;; The following constant is for compatibility with different versions
147 ;; of outline.el.
148 (defconst org-noutline-p (featurep 'noutline)
149 "Are we using the new outline mode?")
150 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
151 (defconst org-format-transports-properties-p
152 (let ((x "a"))
153 (add-text-properties 0 1 '(test t) x)
154 (get-text-property 0 'test (format "%s" x)))
155 "Does format transport text properties?")
157 (defgroup org nil
158 "Outline-based notes management and organizer."
159 :tag "Org"
160 :group 'outlines
161 :group 'hypermedia
162 :group 'calendar)
164 (defgroup org-startup nil
165 "Options concerning startup of Org-mode."
166 :tag "Org Startup"
167 :group 'org)
169 (defcustom org-startup-folded t
170 "Non-nil means, entering Org-mode will switch to OVERVIEW.
171 This can also be configured on a per-file basis by adding one of
172 the following lines anywhere in the buffer:
174 #+STARTUP: fold
175 #+STARTUP: nofold
176 #+STARTUP: content"
177 :group 'org-startup
178 :type '(choice
179 (const :tag "nofold: show all" nil)
180 (const :tag "fold: overview" t)
181 (const :tag "content: all headlines" content)))
183 (defcustom org-startup-truncated t
184 "Non-nil means, entering Org-mode will set `truncate-lines'.
185 This is useful since some lines containing links can be very long and
186 uninteresting. Also tables look terrible when wrapped."
187 :group 'org-startup
188 :type 'boolean)
190 (defcustom org-startup-align-all-tables nil
191 "Non-nil means, align all tables when visiting a file.
192 This is useful when the column width in tables is forced with <N> cookies
193 in table fields. Such tables will look correct only after the first re-align.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
196 #+STARTUP: align
197 #+STARTUP: noalign"
198 :group 'org-startup
199 :type 'boolean)
201 (defcustom org-startup-with-deadline-check nil
202 "Non-nil means, entering Org-mode will run the deadline check.
203 This means, if you start editing an org file, you will get an
204 immediate reminder of any due deadlines.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
207 #+STARTUP: dlcheck
208 #+STARTUP: nodlcheck"
209 :group 'org-startup
210 :type 'boolean)
212 (defcustom org-insert-mode-line-in-empty-file nil
213 "Non-nil means insert the first line setting Org-mode in empty files.
214 When the function `org-mode' is called interactively in an empty file, this
215 normally means that the file name does not automatically trigger Org-mode.
216 To ensure that the file will always be in Org-mode in the future, a
217 line enforcing Org-mode will be inserted into the buffer, if this option
218 has been set."
219 :group 'org-startup
220 :type 'boolean)
222 (defcustom org-CUA-compatible nil
223 "Non-nil means use alternative key bindings for S-<cursor movement>.
224 Org-mode used S-<cursor movement> for changing timestamps and priorities.
225 S-<cursor movement> is also used for example by `CUA-mode' to select text.
226 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
227 alternative bindings. Setting this variable to t will replace the following
228 keys both in Org-mode and in the Org-agenda buffer.
230 S-RET -> C-S-RET
231 S-up -> M-p
232 S-down -> M-n
233 S-left -> M--
234 S-right -> M-+
236 If you do not like the alternative keys, take a look at the variable
237 `org-disputed-keys'.
239 This option is only relevant at load-time of Org-mode. Changing it requires
240 a restart of Emacs to become effective."
241 :group 'org-startup
242 :type 'boolean)
244 (defvar org-disputed-keys
245 '((S-up [(shift up)] [(meta ?p)])
246 (S-down [(shift down)] [(meta ?n)])
247 (S-left [(shift left)] [(meta ?-)])
248 (S-right [(shift right)] [(meta ?+)])
249 (S-return [(shift return)] [(control shift return)]))
250 "Keys for which Org-mode and other modes compete.
251 This is an alist, cars are symbols for lookup, 1st element is the default key,
252 second element will be used when `org-CUA-compatible' is t.")
254 (defun org-key (key)
255 "Select a key according to `org-CUA-compatible'."
256 (nth (if org-CUA-compatible 2 1)
257 (or (assq key org-disputed-keys)
258 (error "Invalid Key %s in `org-key'" key))))
260 (defcustom org-ellipsis nil
261 "The ellipsis to use in the Org-mode outline.
262 When nil, just use the standard three dots. When a string, use that instead,
263 and just in Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (string :tag "String" :value "...#")))
270 (defvar org-display-table nil
271 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
273 (defgroup org-keywords nil
274 "Keywords in Org-mode."
275 :tag "Org Keywords"
276 :group 'org)
278 (defcustom org-deadline-string "DEADLINE:"
279 "String to mark deadline entries.
280 A deadline is this string, followed by a time stamp. Should be a word,
281 terminated by a colon. You can insert a schedule keyword and
282 a timestamp with \\[org-deadline].
283 Changes become only effective after restarting Emacs."
284 :group 'org-keywords
285 :type 'string)
287 (defcustom org-scheduled-string "SCHEDULED:"
288 "String to mark scheduled TODO entries.
289 A schedule is this string, followed by a time stamp. Should be a word,
290 terminated by a colon. You can insert a schedule keyword and
291 a timestamp with \\[org-schedule].
292 Changes become only effective after restarting Emacs."
293 :group 'org-keywords
294 :type 'string)
296 (defcustom org-closed-string "CLOSED:"
297 "String used as the prefix for timestamps logging closing a TODO entry."
298 :group 'org-keywords
299 :type 'string)
301 (defcustom org-comment-string "COMMENT"
302 "Entries starting with this keyword will never be exported.
303 An entry can be toggled between COMMENT and normal with
304 \\[org-toggle-comment].
305 Changes become only effective after restarting Emacs."
306 :group 'org-keywords
307 :type 'string)
309 (defcustom org-quote-string "QUOTE"
310 "Entries starting with this keyword will be exported in fixed-width font.
311 Quoting applies only to the text in the entry following the headline, and does
312 not extend beyond the next headline, even if that is lower level.
313 An entry can be toggled between QUOTE and normal with
314 \\[org-toggle-fixed-width-section]."
315 :group 'org-keywords
316 :type 'string)
318 (defgroup org-structure nil
319 "Options concerning the general structure of Org-mode files."
320 :tag "Org Structure"
321 :group 'org)
323 (defgroup org-cycle nil
324 "Options concerning visibility cycling in Org-mode."
325 :tag "Org Cycle"
326 :group 'org-structure)
328 (defcustom org-cycle-emulate-tab t
329 "Where should `org-cycle' emulate TAB.
330 nil Never
331 white Only in completely white lines
332 t Everywhere except in headlines"
333 :group 'org-cycle
334 :type '(choice (const :tag "Never" nil)
335 (const :tag "Only in completely white lines" white)
336 (const :tag "Everywhere except in headlines" t)
339 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
340 "Hook that is run after `org-cycle' has changed the buffer visibility.
341 The function(s) in this hook must accept a single argument which indicates
342 the new state that was set by the most recent `org-cycle' command. The
343 argument is a symbol. After a global state change, it can have the values
344 `overview', `content', or `all'. After a local state change, it can have
345 the values `folded', `children', or `subtree'."
346 :group 'org-cycle
347 :type 'hook)
349 (defgroup org-edit-structure nil
350 "Options concerning structure editing in Org-mode."
351 :tag "Org Edit Structure"
352 :group 'org-structure)
354 (defcustom org-odd-levels-only nil
355 "Non-nil means, skip even levels and only use odd levels for the outline.
356 This has the effect that two stars are being added/taken away in
357 promotion/demotion commands. It also influences how levels are
358 handled by the exporters.
359 Changing it requires restart of `font-lock-mode' to become effective
360 for fontification also in regions already fontified.
361 You may also set this on a per-file basis by adding one of the following
362 lines to the buffer:
364 #+STARTUP: odd
365 #+STARTUP: oddeven"
366 :group 'org-edit-structure
367 :group 'org-font-lock
368 :type 'boolean)
370 (defcustom org-adapt-indentation t
371 "Non-nil means, adapt indentation when promoting and demoting.
372 When this is set and the *entire* text in an entry is indented, the
373 indentation is increased by one space in a demotion command, and
374 decreased by one in a promotion command. If any line in the entry
375 body starts at column 0, indentation is not changed at all."
376 :group 'org-edit-structure
377 :type 'boolean)
379 (defcustom org-enable-fixed-width-editor t
380 "Non-nil means, lines starting with \":\" are treated as fixed-width.
381 This currently only means, they are never auto-wrapped.
382 When nil, such lines will be treated like ordinary lines.
383 See also the QUOTE keyword."
384 :group 'org-edit-structure
385 :type 'boolean)
387 (defgroup org-sparse-trees nil
388 "Options concerning sparse trees in Org-mode."
389 :tag "Org Sparse Trees"
390 :group 'org-structure)
392 (defcustom org-highlight-sparse-tree-matches t
393 "Non-nil means, highlight all matches that define a sparse tree.
394 The highlights will automatically disappear the next time the buffer is
395 changed by an edit command."
396 :group 'org-sparse-trees
397 :type 'boolean)
399 (defcustom org-show-hierarchy-above t
400 "Non-nil means, show full hierarchy when showing a spot in the tree.
401 Turning this off makes sparse trees more compact, but also less clear."
402 :group 'org-sparse-trees
403 :type 'boolean)
405 (defcustom org-show-following-heading t
406 "Non-nil means, show heading following match in `org-occur'.
407 When doing an `org-occur' it is useful to show the headline which
408 follows the match, even if they do not match the regexp. This makes it
409 easier to edit directly inside the sparse tree. However, if you use
410 `org-occur' mainly as an overview, the following headlines are
411 unnecessary clutter."
412 :group 'org-sparse-trees
413 :type 'boolean)
415 (defcustom org-occur-hook '(org-first-headline-recenter)
416 "Hook that is run after `org-occur' has constructed a sparse tree.
417 This can be used to recenter the window to show as much of the structure
418 as possible."
419 :group 'org-sparse-trees
420 :type 'hook)
422 (defgroup org-plain-lists nil
423 "Options concerning plain lists in Org-mode."
424 :tag "Org Plain lists"
425 :group 'org-structure)
427 (defcustom org-cycle-include-plain-lists nil
428 "Non-nil means, include plain lists into visibility cycling.
429 This means that during cycling, plain list items will *temporarily* be
430 interpreted as outline headlines with a level given by 1000+i where i is the
431 indentation of the bullet. In all other operations, plain list items are
432 not seen as headlines. For example, you cannot assign a TODO keyword to
433 such an item."
434 :group 'org-plain-lists
435 :type 'boolean)
438 (defcustom org-plain-list-ordered-item-terminator t
439 "The character that makes a line with leading number an ordered list item.
440 Valid values are ?. and ?\). To get both terminators, use t. While
441 ?. may look nicer, it creates the danger that a line with leading
442 number may be incorrectly interpreted as an item. ?\) therefore is
443 the safe choice."
444 :group 'org-plain-lists
445 :type '(choice (const :tag "dot like in \"2.\"" ?.)
446 (const :tag "paren like in \"2)\"" ?\))
447 (const :tab "both" t)))
449 (defcustom org-auto-renumber-ordered-lists t
450 "Non-nil means, automatically renumber ordered plain lists.
451 Renumbering happens when the sequence have been changed with
452 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
453 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
454 :group 'org-plain-lists
455 :type 'boolean)
457 (defgroup org-archive nil
458 "Options concerning archiving in Org-mode."
459 :tag "Org Archive"
460 :group 'org-structure)
462 (defcustom org-archive-location "%s_archive::"
463 "The location where subtrees should be archived.
464 This string consists of two parts, separated by a double-colon.
466 The first part is a file name - when omitted, archiving happens in the same
467 file. %s will be replaced by the current file name (without directory part).
468 Archiving to a different file is useful to keep archived entries from
469 contributing to the Org-mode Agenda.
471 The part after the double colon is a headline. The archived entries will be
472 filed under that headline. When omitted, the subtrees are simply filed away
473 at the end of the file, as top-level entries.
475 Here are a few examples:
476 \"%s_archive::\"
477 If the current file is Projects.org, archive in file
478 Projects.org_archive, as top-level trees. This is the default.
480 \"::* Archived Tasks\"
481 Archive in the current file, under the top-level headline
482 \"* Archived Tasks\".
484 \"~/org/archive.org::\"
485 Archive in file ~/org/archive.org (absolute path), as top-level trees.
487 \"basement::** Finished Tasks\"
488 Archive in file ./basement (relative path), as level 3 trees
489 below the level 2 heading \"** Finished Tasks\".
491 You may set this option on a per-file basis by adding to the buffer a
492 line like
494 #+ARCHIVE: basement::** Finished Tasks"
495 :group 'org-archive
496 :type 'string)
498 (defcustom org-archive-mark-done t
499 "Non-nil means, mark archived entries as DONE."
500 :group 'org-archive
501 :type 'boolean)
503 (defcustom org-archive-stamp-time t
504 "Non-nil means, add a time stamp to archived entries.
505 The time stamp will be added directly after the TODO state keyword in the
506 first line, so it is probably best to use this in combinations with
507 `org-archive-mark-done'."
508 :group 'org-archive
509 :type 'boolean)
511 (defgroup org-table nil
512 "Options concerning tables in Org-mode."
513 :tag "Org Table"
514 :group 'org)
516 (defcustom org-enable-table-editor 'optimized
517 "Non-nil means, lines starting with \"|\" are handled by the table editor.
518 When nil, such lines will be treated like ordinary lines.
520 When equal to the symbol `optimized', the table editor will be optimized to
521 do the following:
522 - Use automatic overwrite mode in front of whitespace in table fields.
523 This make the structure of the table stay in tact as long as the edited
524 field does not exceed the column width.
525 - Minimize the number of realigns. Normally, the table is aligned each time
526 TAB or RET are pressed to move to another field. With optimization this
527 happens only if changes to a field might have changed the column width.
528 Optimization requires replacing the functions `self-insert-command',
529 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
530 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
531 very good at guessing when a re-align will be necessary, but you can always
532 force one with \\[org-ctrl-c-ctrl-c].
534 If you would like to use the optimized version in Org-mode, but the
535 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
537 This variable can be used to turn on and off the table editor during a session,
538 but in order to toggle optimization, a restart is required.
540 See also the variable `org-table-auto-blank-field'."
541 :group 'org-table
542 :type '(choice
543 (const :tag "off" nil)
544 (const :tag "on" t)
545 (const :tag "on, optimized" optimized)))
547 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
548 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
549 In the optimized version, the table editor takes over all simple keys that
550 normally just insert a character. In tables, the characters are inserted
551 in a way to minimize disturbing the table structure (i.e. in overwrite mode
552 for empty fields). Outside tables, the correct binding of the keys is
553 restored.
555 The default for this option is t if the optimized version is also used in
556 Org-mode. See the variable `org-enable-table-editor' for details. Changing
557 this variable requires a restart of Emacs to become effective."
558 :group 'org-table
559 :type 'boolean)
561 (defgroup org-table-settings nil
562 "Settings for tables in Org-mode."
563 :tag "Org Table Settings"
564 :group 'org-table)
566 (defcustom org-table-default-size "5x2"
567 "The default size for newly created tables, Columns x Rows."
568 :group 'org-table-settings
569 :type 'string)
571 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
572 "Regular expression for recognizing numbers in table columns.
573 If a table column contains mostly numbers, it will be aligned to the
574 right. If not, it will be aligned to the left.
576 The default value of this option is a regular expression which allows
577 anything which looks remotely like a number as used in scientific
578 context. For example, all of the following will be considered a
579 number:
580 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
582 Other options offered by the customize interface are more restrictive."
583 :group 'org-table-settings
584 :type '(choice
585 (const :tag "Positive Integers"
586 "^[0-9]+$")
587 (const :tag "Integers"
588 "^[-+]?[0-9]+$")
589 (const :tag "Floating Point Numbers"
590 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
591 (const :tag "Floating Point Number or Integer"
592 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
593 (const :tag "Exponential, Floating point, Integer"
594 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
595 (const :tag "Very General Number-Like"
596 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
597 (string :tag "Regexp:")))
599 (defcustom org-table-number-fraction 0.5
600 "Fraction of numbers in a column required to make the column align right.
601 In a column all non-white fields are considered. If at least this
602 fraction of fields is matched by `org-table-number-fraction',
603 alignment to the right border applies."
604 :group 'org-table-settings
605 :type 'number)
607 (defgroup org-table-editing nil
608 "Bahavior of tables during editing in Org-mode."
609 :tag "Org Table Editing"
610 :group 'org-table)
612 (defcustom org-table-automatic-realign t
613 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
614 When nil, aligning is only done with \\[org-table-align], or after column
615 removal/insertion."
616 :group 'org-table-editing
617 :type 'boolean)
619 (defcustom org-table-limit-column-width t ;kw
620 "Non-nil means, allow to limit the width of table columns with <N> fields."
621 :group 'org-table-editing
622 :type 'boolean)
624 (defcustom org-table-auto-blank-field t
625 "Non-nil means, automatically blank table field when starting to type into it.
626 This only happens when typing immediately after a field motion
627 command (TAB, S-TAB or RET).
628 Only relevant when `org-enable-table-editor' is equal to `optimized'."
629 :group 'org-table-editing
630 :type 'boolean)
632 (defcustom org-table-tab-jumps-over-hlines t
633 "Non-nil means, tab in the last column of a table with jump over a hline.
634 If a horizontal separator line is following the current line,
635 `org-table-next-field' can either create a new row before that line, or jump
636 over the line. When this option is nil, a new line will be created before
637 this line."
638 :group 'org-table-editing
639 :type 'boolean)
641 (defcustom org-table-tab-recognizes-table.el t
642 "Non-nil means, TAB will automatically notice a table.el table.
643 When it sees such a table, it moves point into it and - if necessary -
644 calls `table-recognize-table'."
645 :group 'org-table-editing
646 :type 'boolean)
648 (defgroup org-table-calculation nil
649 "Options concerning tables in Org-mode."
650 :tag "Org Table Calculation"
651 :group 'org-table)
653 (defcustom org-table-copy-increment t
654 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
655 :group 'org-table-calculation
656 :type 'boolean)
658 (defcustom org-calc-default-modes
659 '(calc-internal-prec 12
660 calc-float-format (float 5)
661 calc-angle-mode deg
662 calc-prefer-frac nil
663 calc-symbolic-mode nil
664 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
665 calc-display-working-message t
667 "List with Calc mode settings for use in calc-eval for table formulas.
668 The list must contain alternating symbols (Calc modes variables and values).
669 Don't remove any of the default settings, just change the values. Org-mode
670 relies on the variables to be present in the list."
671 :group 'org-table-calculation
672 :type 'plist)
674 (defcustom org-table-formula-evaluate-inline t
675 "Non-nil means, TAB and RET evaluate a formula in current table field.
676 If the current field starts with an equal sign, it is assumed to be a formula
677 which should be evaluated as described in the manual and in the documentation
678 string of the command `org-table-eval-formula'. This feature requires the
679 Emacs calc package.
680 When this variable is nil, formula calculation is only available through
681 the command \\[org-table-eval-formula]."
682 :group 'org-table-calculation
683 :type 'boolean)
686 (defcustom org-table-formula-use-constants t
687 "Non-nil means, interpret constants in formulas in tables.
688 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
689 by the value given in `org-table-formula-constants', or by a value obtained
690 from the `constants.el' package."
691 :group 'org-table-calculation
692 :type 'boolean)
694 (defcustom org-table-formula-constants nil
695 "Alist with constant names and values, for use in table formulas.
696 The car of each element is a name of a constant, without the `$' before it.
697 The cdr is the value as a string. For example, if you'd like to use the
698 speed of light in a formula, you would configure
700 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
702 and then use it in an equation like `$1*$c'."
703 :group 'org-table-calculation
704 :type '(repeat
705 (cons (string :tag "name")
706 (string :tag "value"))))
708 (defcustom org-table-formula-numbers-only nil
709 "Non-nil means, calculate only with numbers in table formulas.
710 Then all input fields will be converted to a number, and the result
711 must also be a number. When nil, calc's full potential is available
712 in table calculations, including symbolics etc."
713 :group 'org-table-calculation
714 :type 'boolean)
716 (defcustom org-table-allow-automatic-line-recalculation t
717 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
718 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
719 :group 'org-table-calculation
720 :type 'boolean)
722 (defgroup org-link nil
723 "Options concerning links in Org-mode."
724 :tag "Org Link"
725 :group 'org)
727 (defcustom org-descriptive-links t
728 "Non-nil means, hide link part and only show description of bracket links.
729 Bracket links are like [[link][descritpion]]. This variable sets the initial
730 state in new org-mode buffers. The setting can then be toggled on a
731 per-buffer basis from the Org->Hyperlinks menu."
732 :group 'org-link
733 :type 'boolean)
735 (defcustom org-link-style 'bracket
736 "The style of links to be inserted with \\[org-insert-link].
737 Possible values are:
738 bracket [[link][description]]. This is recommended
739 plain Description \\n link. The old way, no longer recommended."
740 :group 'org-link
741 :type '(choice
742 (const :tag "Bracket (recommended)" bracket)
743 (const :tag "Plain (no longer recommended)" plain)))
745 (defcustom org-link-format "%s"
746 "Default format for external, URL-like linkes in the buffer.
747 This is a format string for printf, %s will be replaced by the link text.
748 The recommended value is just \"%s\", since links will be protected by
749 enclosing them in double brackets. If you prefer plain links (see variable
750 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
751 additional URL: prefix, so the format would be \"<URL:%s>\"."
752 :group 'org-link
753 :type '(choice
754 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
755 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
756 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
757 (string :tag "Other" :value "<%s>")))
759 (defcustom org-activate-links '(bracket angle plain radio tag date)
760 "Types of links that should be activated in Org-mode files.
761 This is a list of symbols, each leading to the activation of a certain link
762 type. In principle, it does not hurt to turn on most link types - there may
763 be a small gain when turning off unused link types. The types are:
765 bracket The recommended [[link][description]] or [[link]] links with hiding.
766 angular Links in angular brackes that may contain whitespace like
767 <bbdb:Carsten Dominik>.
768 plain Plain links in normal text, no whitespace, like http://google.com.
769 radio Text that is matched by a radio target, see manual for details.
770 tag Tag settings in a headline (link to tag search).
771 date Time stamps (link to calendar).
772 camel CamelCase words defining text searches.
774 Changing this variable requires a restart of Emacs to become effective."
775 :group 'org-link
776 :type '(set (const :tag "Double bracket links (new style)" bracket)
777 (const :tag "Angular bracket links (old style)" angular)
778 (const :tag "plain text links" plain)
779 (const :tag "Radio target matches" radio)
780 (const :tag "Tags" tag)
781 (const :tag "Timestamps" date)
782 (const :tag "CamelCase words" camel)))
784 (defgroup org-link-store nil
785 "Options concerning storing links in Org-mode"
786 :tag "Org Store Link"
787 :group 'org-link)
789 (defcustom org-context-in-file-links t
790 "Non-nil means, file links from `org-store-link' contain context.
791 A search string will be added to the file name with :: as separator and
792 used to find the context when the link is activated by the command
793 `org-open-at-point'.
794 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
795 negates this setting for the duration of the command."
796 :group 'org-link-store
797 :type 'boolean)
799 (defcustom org-file-link-context-use-camel-case nil
800 "Non-nil means, use CamelCase to store a search context in a file link.
801 When nil, the search string simply consists of the words of the string.
802 CamelCase is deprecated, and support for it may be dropped in the future."
803 :group 'org-link-store
804 :type 'boolean)
806 (defcustom org-keep-stored-link-after-insertion nil
807 "Non-nil means, keep link in list for entire session.
809 The command `org-store-link' adds a link pointing to the current
810 location to an internal list. These links accumulate during a session.
811 The command `org-insert-link' can be used to insert links into any
812 Org-mode file (offering completion for all stored links). When this
813 option is nil, every link which has been inserted once using \\[org-insert-link]
814 will be removed from the list, to make completing the unused links
815 more efficient."
816 :group 'org-link-store
817 :type 'boolean)
819 (defcustom org-usenet-links-prefer-google nil
820 "Non-nil means, `org-store-link' will create web links to Google groups.
821 When nil, Gnus will be used for such links.
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 (defgroup org-link-follow nil
828 "Options concerning following links in Org-mode"
829 :tag "Org Follow Link"
830 :group 'org-link)
832 (defcustom org-tab-follows-link nil
833 "Non-nil means, on links TAB will follow the link.
834 Needs to be set before org.el is loaded."
835 :group 'org-link-follow
836 :type 'boolean)
838 (defcustom org-return-follows-link nil
839 "Non-nil means, on links RET will follow the link.
840 Needs to be set before org.el is loaded."
841 :group 'org-link-follow
842 :type 'boolean)
844 (defcustom org-mouse-1-follows-link t
845 "Non-nil means, mouse-1 on a link will follow the link.
846 A longer mouse click will still set point. Does not wortk on XEmacs.
847 Needs to be set before org.el is loaded."
848 :group 'org-link-follow
849 :type 'boolean)
851 (defcustom org-mark-ring-length 4
852 "Number of different positions to be recorded in the ring
853 Changing this requires a restart of Emacs to work correctly."
854 :group 'org-link-follow
855 :type 'interger)
857 (defcustom org-link-frame-setup
858 '((vm . vm-visit-folder-other-frame)
859 (gnus . gnus-other-frame)
860 (file . find-file-other-window))
861 "Setup the frame configuration for following links.
862 When following a link with Emacs, it may often be useful to display
863 this link in another window or frame. This variable can be used to
864 set this up for the different types of links.
865 For VM, use any of
866 `vm-visit-folder'
867 `vm-visit-folder-other-frame'
868 For Gnus, use any of
869 `gnus'
870 `gnus-other-frame'
871 For FILE, use any of
872 `find-file'
873 `find-file-other-window'
874 `find-file-other-frame'
875 For the calendar, use the variable `calendar-setup'.
876 For BBDB, it is currently only possible to display the matches in
877 another window."
878 :group 'org-link-follow
879 :type '(list
880 (cons (const vm)
881 (choice
882 (const vm-visit-folder)
883 (const vm-visit-folder-other-window)
884 (const vm-visit-folder-other-frame)))
885 (cons (const gnus)
886 (choice
887 (const gnus)
888 (const gnus-other-frame)))
889 (cons (const file)
890 (choice
891 (const find-file)
892 (const find-file-other-window)
893 (const find-file-other-frame)))))
895 (defcustom org-open-non-existing-files nil
896 "Non-nil means, `org-open-file' will open non-existing file.
897 When nil, an error will be generated."
898 :group 'org-link-follow
899 :type 'boolean)
901 (defcustom org-confirm-shell-links 'yes-or-no-p
902 "Non-nil means, ask for confirmation before executing shell links.
903 Shell links can be dangerous, just thing about a link
905 [[shell:rm -rf ~/*][Google Search]]
907 This link would show up in your Org-mode document as \"Google Search\"
908 but really it would remove your entire home directory. Dangerous indeed.
909 Therefore I *definitely* advise agains setting this varaiable to nil.
910 Just change it to `y-or-n-p' of you want to confirm with a single key press
911 rather than having to type \"yes\"."
912 :group 'org-link-follow
913 :type '(choice
914 (const :tag "with yes-or-no (safer)" yes-or-no-p)
915 (const :tag "with y-or-n (faster)" y-or-n-p)
916 (const :tag "no confirmation (dangerous)" nil)))
918 (defconst org-file-apps-defaults-gnu
919 '((t . mailcap))
920 "Default file applications on a UNIX or GNU/Linux system.
921 See `org-file-apps'.")
923 (defconst org-file-apps-defaults-macosx
924 '((t . "open %s")
925 ("ps" . "gv %s")
926 ("ps.gz" . "gv %s")
927 ("eps" . "gv %s")
928 ("eps.gz" . "gv %s")
929 ("dvi" . "xdvi %s")
930 ("fig" . "xfig %s"))
931 "Default file applications on a MacOS X system.
932 The system \"open\" is known as a default, but we use X11 applications
933 for some files for which the OS does not have a good default.
934 See `org-file-apps'.")
936 (defconst org-file-apps-defaults-windowsnt
937 '((t . (w32-shell-execute "open" file)))
938 "Default file applications on a Windows NT system.
939 The system \"open\" is used for most files.
940 See `org-file-apps'.")
942 (defcustom org-file-apps
944 ("txt" . emacs)
945 ("tex" . emacs)
946 ("ltx" . emacs)
947 ("org" . emacs)
948 ("el" . emacs)
950 "External applications for opening `file:path' items in a document.
951 Org-mode uses system defaults for different file types, but
952 you can use this variable to set the application for a given file
953 extension. The entries in this list are cons cells with a file extension
954 and the corresponding command. Possible values for the command are:
955 `emacs' The file will be visited by the current Emacs process.
956 `default' Use the default application for this file type.
957 string A command to be executed by a shell; %s will be replaced
958 by the path to the file.
959 sexp A Lisp form which will be evaluated. The file path will
960 be available in the Lisp variable `file'.
961 For more examples, see the system specific constants
962 `org-file-apps-defaults-macosx'
963 `org-file-apps-defaults-windowsnt'
964 `org-file-apps-defaults-gnu'."
965 :group 'org-link-follow
966 :type '(repeat
967 (cons (choice :value ""
968 (string :tag "Extension")
969 (const :tag "Default for unrecognized files" t)
970 (const :tag "Links to a directory" directory))
971 (choice :value ""
972 (const :tag "Visit with Emacs" emacs)
973 (const :tag "Use system default" default)
974 (string :tag "Command")
975 (sexp :tag "Lisp form")))))
977 (defcustom org-mhe-search-all-folders nil
978 "Non-nil means, that the search for the mh-message will be extended to
979 all folders if the message cannot be found in the folder given in the link.
980 Searching all folders is very effective with one of the search engines
981 supported by MH-E, but will be slow with pick."
982 :group 'org-link-follow
983 :type 'boolean)
985 (defgroup org-remember nil
986 "Options concerning interaction with remember.el."
987 :tag "Org Remember"
988 :group 'org)
990 (defcustom org-directory "~/org"
991 "Directory with org files.
992 This directory will be used as default to prompt for org files.
993 Used by the hooks for remember.el."
994 :group 'org-remember
995 :type 'directory)
997 (defcustom org-default-notes-file "~/.notes"
998 "Default target for storing notes.
999 Used by the hooks for remember.el. This can be a string, or nil to mean
1000 the value of `remember-data-file'."
1001 :group 'org-remember
1002 :type '(choice
1003 (const :tag "Default from remember-data-file" nil)
1004 file))
1006 (defcustom org-remember-templates nil
1007 "Templates for the creation of remember buffers.
1008 When nil, just let remember make the buffer.
1009 When not nil, this is a list of 3-element lists. In each entry, the first
1010 element is a character, a unique key to select this template.
1011 The second element is the template. The third element is optional and can
1012 specify a destination file for remember items created with this template.
1013 The default file is given by `org-default-notes-file'.
1015 The template specifies the structure of the remember buffer. It should have
1016 a first line starting with a star, to act as the org-mode headline.
1017 Furthermore, the following %-escapes will be replaced with content:
1018 %t time stamp, date only
1019 %T time stamp with date and time
1020 %u inactive time stamp, date only
1021 %U inactive time stamp with date and time
1022 %n user name
1023 %a annotation, normally the link created with org-store-link
1024 %i initial content, the region when remember is called with C-u.
1025 If %i is indented, the entire inserted text will be indented as well.
1026 %? This will be removed, and the cursor placed at this position."
1027 :group 'org-remember
1028 :type '(repeat :tag "enabled"
1029 (list :value (?a "\n" nil)
1030 (character :tag "Selection Key")
1031 (string :tag "Template")
1032 (file :tag "Destination file (optional)"))))
1034 (defcustom org-reverse-note-order nil
1035 "Non-nil means, store new notes at the beginning of a file or entry.
1036 When nil, new notes will be filed to the end of a file or entry."
1037 :group 'org-remember
1038 :type '(choice
1039 (const :tag "Reverse always" t)
1040 (const :tag "Reverse never" nil)
1041 (repeat :tag "By file name regexp"
1042 (cons regexp boolean))))
1044 (defgroup org-todo nil
1045 "Options concerning TODO items in Org-mode."
1046 :tag "Org TODO"
1047 :group 'org)
1049 (defcustom org-todo-keywords '("TODO" "DONE")
1050 "List of TODO entry keywords.
1051 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1052 considered to mean that the entry is \"done\". All the other mean that
1053 action is required, and will make the entry show up in todo lists, diaries
1054 etc.
1055 The command \\[org-todo] cycles an entry through these states, and an
1056 additional state where no keyword is present. For details about this
1057 cycling, see also the variable `org-todo-interpretation'
1058 Changes become only effective after restarting Emacs."
1059 :group 'org-todo
1060 :group 'org-keywords
1061 :type '(repeat (string :tag "Keyword")))
1063 (defcustom org-todo-interpretation 'sequence
1064 "Controls how TODO keywords are interpreted.
1065 This variable is only relevant if `org-todo-keywords' contains more than two
1066 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1068 When `sequence', \\[org-todo] will always switch to the next state in the
1069 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1070 to state when executed several times in direct succession. Otherwise, it
1071 switches directly to DONE from any state.
1072 See the manual for more information."
1073 :group 'org-todo
1074 :group 'org-keywords
1075 :type '(choice (const sequence)
1076 (const type)))
1078 (defcustom org-after-todo-state-change-hook nil
1079 "Hook which is run after the state of a TODO item was changed.
1080 The new state (a string with a TODO keyword, or nil) is available in the
1081 Lisp variable `state'."
1082 :group 'org-todo
1083 :type 'hook)
1085 (defcustom org-log-done nil
1086 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1087 When the state of an entry is changed from nothing to TODO, remove a previous
1088 closing date."
1089 :group 'org-todo
1090 :type 'boolean)
1092 (defgroup org-priorities nil
1093 "Priorities in Org-mode."
1094 :tag "Org Priorities"
1095 :group 'org-todo)
1097 (defcustom org-default-priority ?B
1098 "The default priority of TODO items.
1099 This is the priority an item get if no explicit priority is given."
1100 :group 'org-priorities
1101 :type 'character)
1103 (defcustom org-lowest-priority ?C
1104 "The lowest priority of TODO items. A character like ?A, ?B etc."
1105 :group 'org-priorities
1106 :type 'character)
1108 (defgroup org-time nil
1109 "Options concerning time stamps and deadlines in Org-mode."
1110 :tag "Org Time"
1111 :group 'org)
1113 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1114 "Formats for `format-time-string' which are used for time stamps.
1115 It is not recommended to change this constant.")
1117 (defcustom org-time-stamp-rounding-minutes 0
1118 "Number of minutes to round time stamps to upon insertion.
1119 When zero, insert the time unmodified. Useful rounding numbers
1120 should be factors of 60, so for example 5, 10, 15.
1121 When this is not zero, you can still force an exact time-stamp by using
1122 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1123 :group 'org-time
1124 :type 'integer)
1126 (defcustom org-deadline-warning-days 30
1127 "No. of days before expiration during which a deadline becomes active.
1128 This variable governs the display in the org file."
1129 :group 'org-time
1130 :type 'number)
1132 (defcustom org-popup-calendar-for-date-prompt t
1133 "Non-nil means, pop up a calendar when prompting for a date.
1134 In the calendar, the date can be selected with mouse-1. However, the
1135 minibuffer will also be active, and you can simply enter the date as well.
1136 When nil, only the minibuffer will be available."
1137 :group 'org-time
1138 :type 'boolean)
1140 (defcustom org-calendar-follow-timestamp-change t
1141 "Non-nil means, make the calendar window follow timestamp changes.
1142 When a timestamp is modified and the calendar window is visible, it will be
1143 moved to the new date."
1144 :group 'org-time
1145 :type 'boolean)
1147 (defgroup org-tags nil
1148 "Options concerning tags in Org-mode."
1149 :tag "Org Tags"
1150 :group 'org)
1152 (defcustom org-tags-column 48
1153 "The column to which tags should be indented in a headline.
1154 If this number is positive, it specifies the column. If it is negative,
1155 it means that the tags should be flushright to that column. For example,
1156 -79 works well for a normal 80 character screen."
1157 :group 'org-tags
1158 :type 'integer)
1160 (defcustom org-auto-align-tags t
1161 "Non-nil means, realign tags after pro/demotion of TODO state change.
1162 These operations change the length of a headline and therefore shift
1163 the tags around. With this options turned on, after each such operation
1164 the tags are again aligned to `org-tags-column'."
1165 :group 'org-tags
1166 :type 'boolean)
1168 (defcustom org-use-tag-inheritance t
1169 "Non-nil means, tags in levels apply also for sublevels.
1170 When nil, only the tags directly given in a specific line apply there.
1171 If you turn off this option, you very likely want to turn on the
1172 companion option `org-tags-match-list-sublevels'."
1173 :group 'org-tags
1174 :type 'boolean)
1176 (defcustom org-tags-match-list-sublevels nil
1177 "Non-nil means list also sublevels of headlines matching tag search.
1178 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1179 the sublevels of a headline matching a tag search often also match
1180 the same search. Listing all of them can create very long lists.
1181 Setting this variable to nil causes subtrees of a match to be skipped.
1182 This option is off by default, because inheritance in on. If you turn
1183 inheritance off, you very likely want to turn this option on.
1185 As a special case, if the tag search is restricted to TODO items, the
1186 value of this variable is ignored and sublevels are always checked, to
1187 make sure all corresponding TODO items find their way into the list."
1188 :group 'org-tags
1189 :type 'boolean)
1191 (defvar org-tags-history nil
1192 "History of minibuffer reads for tags.")
1193 (defvar org-last-tags-completion-table nil
1194 "The last used completion table for tags.")
1196 (defgroup org-agenda nil
1197 "Options concerning agenda display Org-mode."
1198 :tag "Org Agenda"
1199 :group 'org)
1201 (defvar org-category nil
1202 "Variable used by org files to set a category for agenda display.
1203 Such files should use a file variable to set it, for example
1205 -*- mode: org; org-category: \"ELisp\"
1207 or contain a special line
1209 #+CATEGORY: ELisp
1211 If the file does not specify a category, then file's base name
1212 is used instead.")
1213 (make-variable-buffer-local 'org-category)
1215 (defcustom org-agenda-files nil
1216 "The files to be used for agenda display.
1217 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1218 \\[org-remove-file]. You can also use customize to edit the list.
1220 If the value of the variable is not a list but a single file name, then
1221 the list of agenda files is actually stored and maintained in that file, one
1222 agenda file per line."
1223 :group 'org-agenda
1224 :type '(choice
1225 (repeat :tag "List of files" file)
1226 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1228 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1229 "Custom commands for the agenda.
1230 These commands will be offered on the splash screen displayed by the
1231 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1233 key The key (a single char as a string) to be associated with the command.
1234 type The command type, any of the following symbols:
1235 todo Entries with a specific TODO keyword, in all agenda files.
1236 tags Tags match in all agenda files.
1237 todo-tree Sparse tree of specific TODO keyword in *current* file.
1238 tags-tree Sparse tree with all tags matches in *current* file.
1239 occur-tree Occur sparse tree for current file.
1240 match What to search for:
1241 - a single keyword for TODO keyword searches
1242 - a tags match expression for tags searches
1243 - a regular expression for occur searches"
1244 :group 'org-agenda
1245 :type '(repeat
1246 (list (string :tag "Key")
1247 (choice :tag "Type"
1248 (const :tag "Tags search in all agenda files" tags)
1249 (const :tag "TODO keyword search in all agenda files" todo)
1250 (const :tag "Tags sparse tree in current buffer" tags-tree)
1251 (const :tag "TODO keyword tree in current buffer" todo-tree)
1252 (const :tag "Occur tree in current buffer" occur-tree))
1253 (string :tag "Match"))))
1255 (defcustom org-agenda-include-all-todo t
1256 "Non-nil means, the agenda will always contain all TODO entries.
1257 When nil, date-less entries will only be shown if `org-agenda' is called
1258 with a prefix argument.
1259 When non-nil, the TODO entries will be listed at the top of the agenda, before
1260 the entries for specific days."
1261 :group 'org-agenda
1262 :type 'boolean)
1264 (defcustom org-agenda-include-diary nil
1265 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1266 :group 'org-agenda
1267 :type 'boolean)
1269 (defcustom org-calendar-to-agenda-key [?c]
1270 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1271 The command `org-calendar-goto-agenda' will be bound to this key. The
1272 default is the character `c' because then `c' can be used to switch back and
1273 forth between agenda and calendar."
1274 :group 'org-agenda
1275 :type 'sexp)
1277 (defgroup org-agenda-window-setup nil
1278 "Options concerning setting up the Agenda window in Org Mode."
1279 :tag "Org Agenda Window Setup"
1280 :group 'org-agenda)
1282 (defcustom org-agenda-mouse-1-follows-link nil
1283 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1284 A longer mouse click will still set point. Does not wortk on XEmacs.
1285 Needs to be set before org.el is loaded."
1286 :group 'org-agenda-setup
1287 :type 'boolean)
1289 (defcustom org-select-timeline-window t
1290 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1291 When nil, cursor will remain in the current window."
1292 :group 'org-agenda-setup
1293 :type 'boolean)
1295 (defcustom org-select-agenda-window t
1296 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1297 When nil, cursor will remain in the current window."
1298 :group 'org-agenda-setup
1299 :type 'boolean)
1301 (defcustom org-fit-agenda-window t
1302 "Non-nil means, change window size of agenda to fit content."
1303 :group 'org-agenda-setup
1304 :type 'boolean)
1306 (defgroup org-agenda-display nil
1307 "Options concerning what to display initially in Agenda."
1308 :tag "Org Agenda Display"
1309 :group 'org-agenda)
1311 (defcustom org-agenda-show-all-dates t
1312 "Non-nil means, `org-agenda' shows every day in the selected range.
1313 When nil, only the days which actually have entries are shown."
1314 :group 'org-agenda-display
1315 :type 'boolean)
1317 (defcustom org-agenda-start-on-weekday 1
1318 "Non-nil means, start the overview always on the specified weekday.
1319 0 denotes Sunday, 1 denotes Monday etc.
1320 When nil, always start on the current day."
1321 :group 'org-agenda-display
1322 :type '(choice (const :tag "Today" nil)
1323 (number :tag "Weekday No.")))
1325 (defcustom org-agenda-ndays 7
1326 "Number of days to include in overview display.
1327 Should be 1 or 7."
1328 :group 'org-agenda-display
1329 :type 'number)
1331 (defcustom org-agenda-use-time-grid t
1332 "Non-nil means, show a time grid in the agenda schedule.
1333 A time grid is a set of lines for specific times (like every two hours between
1334 8:00 and 20:00). The items scheduled for a day at specific times are
1335 sorted in between these lines.
1336 For details about when the grid will be shown, and what it will look like, see
1337 the variable `org-agenda-time-grid'."
1338 :group 'org-agenda-display
1339 :type 'boolean)
1341 (defcustom org-agenda-time-grid
1342 '((daily today require-timed)
1343 "----------------"
1344 (800 1000 1200 1400 1600 1800 2000))
1346 "The settings for time grid for agenda display.
1347 This is a list of three items. The first item is again a list. It contains
1348 symbols specifying conditions when the grid should be displayed:
1350 daily if the agenda shows a single day
1351 weekly if the agenda shows an entire week
1352 today show grid on current date, independent of daily/weekly display
1353 require-timed show grid only if at least on item has a time specification
1355 The second item is a string which will be places behing the grid time.
1357 The third item is a list of integers, indicating the times that should have
1358 a grid line."
1359 :group 'org-agenda-display
1360 :type
1361 '(list
1362 (set :greedy t :tag "Grid Display Options"
1363 (const :tag "Show grid in single day agenda display" daily)
1364 (const :tag "Show grid in weekly agenda display" weekly)
1365 (const :tag "Always show grid for today" today)
1366 (const :tag "Show grid only if any timed entries are present"
1367 require-timed)
1368 (const :tag "Skip grid times already present in an entry"
1369 remove-match))
1370 (string :tag "Grid String")
1371 (repeat :tag "Grid Times" (integer :tag "Time"))))
1373 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1374 "Sorting structure for the agenda items of a single day.
1375 This is a list of symbols which will be used in sequence to determine
1376 if an entry should be listed before another entry. The following
1377 symbols are recognized:
1379 time-up Put entries with time-of-day indications first, early first
1380 time-down Put entries with time-of-day indications first, late first
1381 category-keep Keep the default order of categories, corresponding to the
1382 sequence in `org-agenda-files'.
1383 category-up Sort alphabetically by category, A-Z.
1384 category-down Sort alphabetically by category, Z-A.
1385 priority-up Sort numerically by priority, high priority last.
1386 priority-down Sort numerically by priority, high priority first.
1388 The different possibilities will be tried in sequence, and testing stops
1389 if one comparison returns a \"not-equal\". For example, the default
1390 '(time-up category-keep priority-down)
1391 means: Pull out all entries having a specified time of day and sort them,
1392 in order to make a time schedule for the current day the first thing in the
1393 agenda listing for the day. Of the entries without a time indication, keep
1394 the grouped in categories, don't sort the categories, but keep them in
1395 the sequence given in `org-agenda-files'. Within each category sort by
1396 priority.
1398 Leaving out `category-keep' would mean that items will be sorted across
1399 categories by priority."
1400 :group 'org-agenda-display
1401 :type '(repeat
1402 (choice
1403 (const time-up)
1404 (const time-down)
1405 (const category-keep)
1406 (const category-up)
1407 (const category-down)
1408 (const priority-up)
1409 (const priority-down))))
1411 (defcustom org-sort-agenda-notime-is-late t
1412 "Non-nil means, items without time are considered late.
1413 This is only relevant for sorting. When t, items which have no explicit
1414 time like 15:30 will be considered as 24:01, i.e. later than any items which
1415 do have a time. When nil, the default time is before 0:00. You can use this
1416 option to decide if the schedule for today should come before or after timeless
1417 agenda entries."
1418 :group 'org-agenda-display
1419 :type 'boolean)
1422 (defgroup org-agenda-prefix nil
1423 "Options concerning the entry prefix in the Org-mode agenda display."
1424 :tag "Org Agenda Prefix"
1425 :group 'org-agenda)
1427 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1428 "Format specification for the prefix of items in the agenda buffer.
1429 This format works similar to a printf format, with the following meaning:
1431 %c the category of the item, \"Diary\" for entries from the diary, or
1432 as given by the CATEGORY keyword or derived from the file name.
1433 %T the first tag of the item.
1434 %t the time-of-day specification if one applies to the entry, in the
1435 format HH:MM
1436 %s Scheduling/Deadline information, a short string
1438 All specifiers work basically like the standard `%s' of printf, but may
1439 contain two additional characters: A question mark just after the `%' and
1440 a whitespace/punctuation character just before the final letter.
1442 If the first character after `%' is a question mark, the entire field
1443 will only be included if the corresponding value applies to the
1444 current entry. This is useful for fields which should have fixed
1445 width when present, but zero width when absent. For example,
1446 \"%?-12t\" will result in a 12 character time field if a time of the
1447 day is specified, but will completely disappear in entries which do
1448 not contain a time.
1450 If there is punctuation or whitespace character just before the final
1451 format letter, this character will be appended to the field value if
1452 the value is not empty. For example, the format \"%-12:c\" leads to
1453 \"Diary: \" if the category is \"Diary\". If the category were be
1454 empty, no additional colon would be interted.
1456 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1457 - Indent the line with two space characters
1458 - Give the category in a 12 chars wide field, padded with whitespace on
1459 the right (because of `-'). Append a colon if there is a category
1460 (because of `:').
1461 - If there is a time-of-day, put it into a 12 chars wide field. If no
1462 time, don't put in an empty field, just skip it (because of '?').
1463 - Finally, put the scheduling information and append a whitespace.
1465 As another example, if you don't want the time-of-day of entries in
1466 the prefix, you could use:
1468 (setq org-agenda-prefix-format \" %-11:c% s\")
1470 See also the variables `org-agenda-remove-times-when-in-prefix' and
1471 `org-agenda-remove-tags-when-in-prefix'."
1472 :type 'string
1473 :group 'org-agenda-prefix)
1475 (defcustom org-timeline-prefix-format " % s"
1476 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1477 :type 'string
1478 :group 'org-agenda-prefix)
1480 (defvar org-prefix-format-compiled nil
1481 "The compiled version of the most recently used prefix format.
1482 Depending on which command was used last, this may be the compiled version
1483 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1485 ;; FIXME: There seem to be situations where this does no work.
1486 (defcustom org-agenda-remove-times-when-in-prefix t
1487 "Non-nil means, remove duplicate time specifications in agenda items.
1488 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1489 time-of-day specification in a headline or diary entry is extracted and
1490 placed into the prefix. If this option is non-nil, the original specification
1491 \(a timestamp or -range, or just a plain time(range) specification like
1492 11:30-4pm) will be removed for agenda display. This makes the agenda less
1493 cluttered.
1494 The option can be t or nil. It may also be the symbol `beg', indicating
1495 that the time should only be removed what it is located at the beginning of
1496 the headline/diary entry."
1497 :group 'org-agenda-prefix
1498 :type '(choice
1499 (const :tag "Always" t)
1500 (const :tag "Never" nil)
1501 (const :tag "When at beginning of entry" beg)))
1503 (defcustom org-agenda-remove-tags-when-in-prefix nil
1504 "Non-nil means, remove the tags from the headline copy in the agenda.
1505 When this is the symbol `prefix', only remove tags when
1506 `org-agenda-prefix-format' contains a `%T' specifier."
1507 :group 'org-agenda-prefix
1508 :type '(choice
1509 (const :tag "Always" t)
1510 (const :tag "Never" nil)
1511 (const :tag "When prefix format contains %T" prefix)))
1513 (defgroup org-export nil
1514 "Options for exporting org-listings."
1515 :tag "Org Export"
1516 :group 'org)
1518 (defgroup org-export-general nil
1519 "General options for exporting Org-mode files."
1520 :tag "Org Export General"
1521 :group 'org-export)
1523 (defcustom org-export-language-setup
1524 '(("en" "Author" "Date" "Table of Contents")
1525 ("da" "Ophavsmand" "Dato" "Indhold")
1526 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1527 ("es" "Autor" "Fecha" "\xccndice")
1528 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1529 ("it" "Autore" "Data" "Indice")
1530 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1531 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1532 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1533 "Terms used in export text, translated to different languages.
1534 Use the variable `org-export-default-language' to set the language,
1535 or use the +OPTION lines for a per-file setting."
1536 :group 'org-export-general
1537 :type '(repeat
1538 (list
1539 (string :tag "HTML language tag")
1540 (string :tag "Author")
1541 (string :tag "Date")
1542 (string :tag "Table of Contents"))))
1544 (defcustom org-export-default-language "en"
1545 "The default language of HTML export, as a string.
1546 This should have an association in `org-export-language-setup'."
1547 :group 'org-export-general
1548 :type 'string)
1550 (defcustom org-export-headline-levels 3
1551 "The last level which is still exported as a headline.
1552 Inferior levels will produce itemize lists when exported.
1553 Note that a numeric prefix argument to an exporter function overrides
1554 this setting.
1556 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1557 :group 'org-export-general
1558 :type 'number)
1560 (defcustom org-export-with-section-numbers t
1561 "Non-nil means, add section numbers to headlines when exporting.
1563 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1564 :group 'org-export-general
1565 :type 'boolean)
1567 (defcustom org-export-with-toc t
1568 "Non-nil means, create a table of contents in exported files.
1569 The TOC contains headlines with levels up to`org-export-headline-levels'.
1571 Headlines which contain any TODO items will be marked with \"(*)\" in
1572 ASCII export, and with red color in HTML output.
1574 In HTML output, the TOC will be clickable.
1576 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1577 :group 'org-export-general
1578 :type 'boolean)
1580 (defcustom org-export-mark-todo-in-toc nil
1581 "Non-nil means, mark TOC lines that contain any open TODO items."
1582 :group 'org-export-general
1583 :type 'boolean)
1585 (defcustom org-export-preserve-breaks nil
1586 "Non-nil means, preserve all line breaks when exporting.
1587 Normally, in HTML output paragraphs will be reformatted. In ASCII
1588 export, line breaks will always be preserved, regardless of this variable.
1590 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1591 :group 'org-export-general
1592 :type 'boolean)
1594 (defgroup org-export-translation nil
1595 "Options for translating special ascii sequences for the export backends."
1596 :tag "Org Export Translation"
1597 :group 'org-export)
1599 (defcustom org-export-with-emphasize t
1600 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1601 If the export target supports emphasizing text, the word will be
1602 typeset in bold, italic, or underlined, respectively. Works only for
1603 single words, but you can say: I *really* *mean* *this*.
1604 Not all export backends support this.
1606 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1607 :group 'org-export-translation
1608 :type 'boolean)
1610 (defcustom org-export-with-sub-superscripts t
1611 "Non-nil means, interpret \"_\" and \"^\" for export.
1612 When this option is turned on, you can use TeX-like syntax for sub- and
1613 superscripts. Several characters after \"_\" or \"^\" will be
1614 considered as a single item - so grouping with {} is normally not
1615 needed. For example, the following things will be parsed as single
1616 sub- or superscripts.
1618 10^24 or 10^tau several digits will be considered 1 item.
1619 10^-12 or 10^-tau a leading sign with digits or a word
1620 x^2-y^3 will be read as x^2 - y^3, because items are
1621 terminated by almost any nonword/nondigit char.
1622 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1624 Still, ambiguity is possible - so when in doubt use {} to enclose the
1625 sub/superscript.
1626 Not all export backends support this, but HTML does.
1628 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1629 :group 'org-export-translation
1630 :type 'boolean)
1632 (defcustom org-export-with-TeX-macros t
1633 "Non-nil means, interpret simple TeX-like macros when exporting.
1634 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1635 No only real TeX macros will work here, but the standard HTML entities
1636 for math can be used as macro names as well. For a list of supported
1637 names in HTML export, see the constant `org-html-entities'.
1638 Not all export backends support this.
1640 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1641 :group 'org-export-translation
1642 :type 'boolean)
1644 (defcustom org-export-with-fixed-width t
1645 "Non-nil means, lines starting with \":\" will be in fixed width font.
1646 This can be used to have pre-formatted text, fragments of code etc. For
1647 example:
1648 : ;; Some Lisp examples
1649 : (while (defc cnt)
1650 : (ding))
1651 will be looking just like this in also HTML. See also the QUOTE keyword.
1652 Not all export backends support this.
1654 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1655 :group 'org-export-translation
1656 :type 'boolean)
1658 (defcustom org-match-sexp-depth 3
1659 "Number of stacked braces for sub/superscript matching.
1660 This has to be set before loading org.el to be effective."
1661 :group 'org-export-translation
1662 :type 'integer)
1664 (defgroup org-export-tables nil
1665 "Options for exporting tables in Org-mode."
1666 :tag "Org Export Tables"
1667 :group 'org-export)
1669 (defcustom org-export-with-tables t
1670 "If non-nil, lines starting with \"|\" define a table.
1671 For example:
1673 | Name | Address | Birthday |
1674 |-------------+----------+-----------|
1675 | Arthur Dent | England | 29.2.2100 |
1677 Not all export backends support this.
1679 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1680 :group 'org-export-tables
1681 :type 'boolean)
1683 (defcustom org-export-highlight-first-table-line t
1684 "Non-nil means, highlight the first table line.
1685 In HTML export, this means use <th> instead of <td>.
1686 In tables created with table.el, this applies to the first table line.
1687 In Org-mode tables, all lines before the first horizontal separator
1688 line will be formatted with <th> tags."
1689 :group 'org-export-tables
1690 :type 'boolean)
1692 (defcustom org-export-table-remove-special-lines t
1693 "Remove special lines and marking characters in calculating tables.
1694 This removes the special marking character column from tables that are set
1695 up for spreadsheet calculations. It also removes the entire lines
1696 marked with `!', `_', or `^'. The lines with `$' are kept, because
1697 the values of constants may be useful to have."
1698 :group 'org-export-tables
1699 :type 'boolean)
1701 (defcustom org-export-prefer-native-exporter-for-tables nil
1702 "Non-nil means, always export tables created with table.el natively.
1703 Natively means, use the HTML code generator in table.el.
1704 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1705 the table does not use row- or column-spanning). This has the
1706 advantage, that the automatic HTML conversions for math symbols and
1707 sub/superscripts can be applied. Org-mode's HTML generator is also
1708 much faster."
1709 :group 'org-export-tables
1710 :type 'boolean)
1712 (defgroup org-export-ascii nil
1713 "Options specific for ASCII export of Org-mode files."
1714 :tag "Org Export ASCII"
1715 :group 'org-export)
1717 (defcustom org-export-ascii-show-new-buffer t
1718 "Non-nil means, popup buffer containing the exported ASCII text.
1719 Otherwise the buffer will just be saved to a file and stay hidden."
1720 :group 'org-export-ascii
1721 :type 'boolean)
1723 (defgroup org-export-xml nil
1724 "Options specific for XML export of Org-mode files."
1725 :tag "Org Export XML"
1726 :group 'org-export)
1728 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1729 "The kind of XML to be produced by the XML exporter.
1730 Allowed values are:
1731 xoxo The XOXO exporter."
1732 :group 'org-export-xml
1733 :type '(choice
1734 (const :tag "XOXO" xoxo)))
1736 (defgroup org-export-html nil
1737 "Options specific for HTML export of Org-mode files."
1738 :tag "Org Export HTML"
1739 :group 'org-export)
1741 (defcustom org-export-html-style
1742 "<style type=\"text/css\">
1743 html {
1744 font-family: Times, serif;
1745 font-size: 12pt;
1747 .title { text-align: center; }
1748 .todo, .deadline { color: red; }
1749 .done { color: green; }
1750 .target { background-color: lavender; }
1751 pre {
1752 border: 1pt solid #AEBDCC;
1753 background-color: #F3F5F7;
1754 padding: 5pt;
1755 font-family: courier, monospace;
1757 table { border-collapse: collapse; }
1758 td, th {
1759 vertical-align: top;
1760 border: 1pt solid #ADB9CC;
1762 </style>"
1763 "The default style specification for exported HTML files.
1764 Since there are different ways of setting style information, this variable
1765 needs to contain the full HTML structure to provide a style, including the
1766 surrounding HTML tags. The style specifications should include definitions
1767 for new classes todo, done, title, and deadline. For example, legal values
1768 would be:
1770 <style type=\"text/css\">
1771 p { font-weight: normal; color: gray; }
1772 h1 { color: black; }
1773 .title { text-align: center; }
1774 .todo, .deadline { color: red; }
1775 .done { color: green; }
1776 </style>
1778 or, if you want to keep the style in a file,
1780 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1782 As the value of this option simply gets inserted into the HTML <head> header,
1783 you can \"misuse\" it to add arbitrary text to the header."
1784 :group 'org-export-html
1785 :type 'string)
1787 (defcustom org-export-html-link-org-files-as-html t
1788 "Non-nil means, make file links to `file.org' point to `file.html'.
1789 When org-mode is exporting an org-mode file to HTML, links to
1790 non-html files are directly put into a href tag in HTML.
1791 However, links to other Org-mode files (recognized by the
1792 extension `.org.) should become links to the corresponding html
1793 file, assuming that the linked org-mode file will also be
1794 converted to HTML.
1795 When nil, the links still point to the plain `.org' file."
1796 :group 'org-export-html
1797 :type 'boolean)
1799 (defcustom org-export-html-inline-images t
1800 "Non-nil means, inline images into exported HTML pages.
1801 The link will still be to the original location of the image file.
1802 So if you are moving the page, lets say to your public HTML site,
1803 you will have to move the image and maybe change the link."
1804 :group 'org-export-html
1805 :type 'boolean)
1807 (defcustom org-export-html-expand t
1808 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1809 When nil, these tags will be exported as plain text and therefore
1810 not be interpreted by a browser.
1812 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1813 :group 'org-export-html
1814 :type 'boolean)
1816 (defcustom org-export-html-table-tag
1817 "<table border=1 cellspacing=0 cellpadding=6>"
1818 "The HTML tag used to start a table.
1819 This must be a <table> tag, but you may change the options like
1820 borders and spacing."
1821 :group 'org-export-html
1822 :type 'string)
1824 (defcustom org-export-html-with-timestamp nil
1825 "If non-nil, write `org-export-html-html-helper-timestamp'
1826 into the exported HTML text. Otherwise, the buffer will just be saved
1827 to a file."
1828 :group 'org-export-html
1829 :type 'boolean)
1831 (defcustom org-export-html-html-helper-timestamp
1832 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1833 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1834 :group 'org-export-html
1835 :type 'string)
1837 (defcustom org-export-html-show-new-buffer nil
1838 "Non-nil means, popup buffer containing the exported html text.
1839 Otherwise, the buffer will just be saved to a file and stay hidden."
1840 :group 'org-export-html
1841 :type 'boolean)
1843 (defgroup org-export-icalendar nil
1844 "Options specific for iCalendar export of Org-mode files."
1845 :tag "Org Export iCalendar"
1846 :group 'org-export)
1848 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1849 "The file name for the iCalendar file covering all agenda files.
1850 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1851 :group 'org-export-icalendar
1852 :type 'file)
1854 (defcustom org-icalendar-include-todo nil
1855 "Non-nil means, export to iCalendar files should also cover TODO items."
1856 :group 'org-export-icalendar
1857 :type 'boolean)
1859 (defcustom org-icalendar-combined-name "OrgMode"
1860 "Calendar name for the combined iCalendar representing all agenda files."
1861 :group 'org-export-icalendar
1862 :type 'string)
1864 (defgroup org-font-lock nil
1865 "Font-lock settings for highlighting in Org-mode."
1866 :tag "Org Font Lock"
1867 :group 'org)
1869 (defcustom org-level-color-stars-only nil
1870 "Non-nil means fontify only the stars in each headline.
1871 When nil, the entire headline is fontified.
1872 Changing it requires restart of `font-lock-mode' to become effective
1873 also in regions already fontified."
1874 :group 'org-font-lock
1875 :type 'boolean)
1877 (defcustom org-hide-leading-stars nil
1878 "Non-nil means, hide the first N-1 stars in a headline.
1879 This works by using the face `org-hide' for these stars. This
1880 face is white for a light background, and black for a dark
1881 background. You may have to customize the face `org-hide' to
1882 make this work.
1883 Changing it requires restart of `font-lock-mode' to become effective
1884 also in regions already fontified.
1885 You may also set this on a per-file basis by adding one of the following
1886 lines to the buffer:
1888 #+STARTUP: hidestars
1889 #+STARTUP: showstars"
1890 :group 'org-font-lock
1891 :type 'boolean)
1893 (defcustom org-fontify-done-headline nil
1894 "Non-nil means, change the face of a headline if it is marked DONE.
1895 Normally, only the TODO/DONE keyword indicates the state of a headline.
1896 When this is non-nil, the headline after the keyword is set to the
1897 `org-headline-done' as an additional indication."
1898 :group 'org-font-lock
1899 :type 'boolean)
1901 (defcustom org-fontify-emphasized-text t
1902 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1903 Changing this variable requires a restart of Emacs to take effect."
1904 :group 'org-font-lock
1905 :type 'boolean)
1907 (defgroup org-faces nil
1908 "Faces in Org-mode."
1909 :tag "Org Faces"
1910 :group 'org-font-lock)
1912 (defun org-compatible-face (specs)
1913 "Make a compatible face specification.
1914 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
1915 For them we convert a (min-colors 8) entry to a `tty' entry and move it
1916 to the top of the list. The `min-colors' attribute will be removed from
1917 any other entries, and any resulting duplicates will be removed entirely."
1918 (if (or (featurep 'xemacs) (< emacs-major-version 22))
1919 (let (r e a)
1920 (while (setq e (pop specs))
1921 (cond
1922 ((memq (car e) '(t default)) (push e r))
1923 ((setq a (member '(min-colors 8) (car e)))
1924 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
1925 (cdr e)))))
1926 ((setq a (assq 'min-colors (car e)))
1927 (setq e (cons (delq a (car e)) (cdr e)))
1928 (or (assoc (car e) r) (push e r)))
1929 (t (or (assoc (car e) r) (push e r)))))
1930 (nreverse r))
1931 specs))
1933 (defface org-hide
1934 '((((background light)) (:foreground "white"))
1935 (((background dark)) (:foreground "black")))
1936 "Face used to hide leading stars in headlines.
1937 The forground color of this face should be equal to the background
1938 color of the frame."
1939 :group 'org-faces)
1941 (defface org-level-1 ;; font-lock-function-name-face
1942 (org-compatible-face
1943 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
1944 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
1945 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
1946 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
1947 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
1948 (t (:bold t))))
1949 "Face used for level 1 headlines."
1950 :group 'org-faces)
1952 (defface org-level-2 ;; font-lock-variable-name-face
1953 (org-compatible-face
1954 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
1955 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
1956 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
1957 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
1958 (t (:bold t))))
1959 "Face used for level 2 headlines."
1960 :group 'org-faces)
1962 (defface org-level-3 ;; font-lock-keyword-face
1963 (org-compatible-face
1964 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
1965 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
1966 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
1967 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
1968 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
1969 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
1970 (t (:bold t))))
1971 "Face used for level 3 headlines."
1972 :group 'org-faces)
1974 (defface org-level-4 ;; font-lock-comment-face
1975 (org-compatible-face
1976 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
1977 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
1978 (((class color) (min-colors 16) (background light)) (:foreground "red"))
1979 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
1980 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
1981 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
1982 (t (:bold t))))
1983 "Face used for level 4 headlines."
1984 :group 'org-faces)
1986 (defface org-level-5 ;; font-lock-type-face
1987 (org-compatible-face
1988 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
1989 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
1990 (((class color) (min-colors 8)) (:foreground "green"))))
1991 "Face used for level 5 headlines."
1992 :group 'org-faces)
1994 (defface org-level-6 ;; font-lock-constant-face
1995 (org-compatible-face
1996 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
1997 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
1998 (((class color) (min-colors 8)) (:foreground "magenta"))))
1999 "Face used for level 6 headlines."
2000 :group 'org-faces)
2002 (defface org-level-7 ;; font-lock-builtin-face
2003 (org-compatible-face
2004 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2005 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2006 (((class color) (min-colors 8)) (:foreground "blue")))) ;; FIXME: for dark bg?
2007 "Face used for level 7 headlines."
2008 :group 'org-faces)
2010 (defface org-level-8 ;; font-lock-string-face
2011 (org-compatible-face
2012 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2013 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2014 (((class color) (min-colors 8)) (:foreground "green"))))
2015 "Face used for level 8 headlines."
2016 :group 'org-faces)
2018 (defface org-special-keyword ;; font-lock-string-face
2019 (org-compatible-face
2020 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2021 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2022 (t (:italic t))))
2023 "Face used for special keywords."
2024 :group 'org-faces)
2026 (defface org-warning ;; font-lock-warning-face
2027 (org-compatible-face
2028 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2029 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2030 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2031 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2032 (t (:bold t))))
2033 "Face for deadlines and TODO keywords."
2034 :group 'org-faces)
2036 (defface org-headline-done ;; font-lock-string-face
2037 (org-compatible-face
2038 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2039 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2040 (((class color) (min-colors 8) (background light)) (:bold nil))))
2041 "Face used to indicate that a headline is DONE.
2042 This face is only used if `org-fontify-done-headline' is set."
2043 :group 'org-faces)
2045 (defface org-link
2046 '((((class color) (background light)) (:foreground "Purple" :underline t))
2047 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2048 (t (:underline t)))
2049 "Face for links."
2050 :group 'org-faces)
2052 (defface org-date
2053 '((((class color) (background light)) (:foreground "Purple" :underline t))
2054 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2055 (t (:underline t)))
2056 "Face for links."
2057 :group 'org-faces)
2059 (defface org-tag
2060 '((t (:bold t)))
2061 "Face for tags."
2062 :group 'org-faces)
2064 (defface org-todo ;; font-lock-warning-face
2065 (org-compatible-face
2066 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2067 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2068 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2069 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2070 (t (:inverse-video t :bold t))))
2071 "Face for TODO keywords."
2072 :group 'org-faces)
2074 (defface org-done ;; font-lock-type-face
2075 (org-compatible-face
2076 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2077 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2078 (((class color) (min-colors 8)) (:foreground "green"))
2079 (t (:bold t))))
2080 "Face used for DONE."
2081 :group 'org-faces)
2083 (defface org-table ;; font-lock-function-name-face
2084 (org-compatible-face
2085 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2086 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2087 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2088 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2089 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2090 (((class color) (min-colors 8) (background dark)))))
2091 "Face used for tables."
2092 :group 'org-faces)
2094 (defface org-formula
2095 (org-compatible-face
2096 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2097 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2098 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2099 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2100 (t (:bold t :italic t))))
2101 "Face for formulas."
2102 :group 'org-faces)
2104 (defface org-scheduled-today
2105 (org-compatible-face
2106 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2107 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2108 (((class color) (min-colors 8)) (:foreground "green"))
2109 (t (:bold t :italic t))))
2110 "Face for items scheduled for a certain day."
2111 :group 'org-faces)
2113 (defface org-scheduled-previously
2114 (org-compatible-face
2115 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2116 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2117 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2118 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2119 (t (:bold t))))
2120 "Face for items scheduled previously, and not yet done."
2121 :group 'org-faces)
2123 (defface org-time-grid ;; font-lock-variable-name-face
2124 (org-compatible-face
2125 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2126 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2127 (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))) ; FIXME: turn off???
2128 "Face used for time grids."
2129 :group 'org-faces)
2131 (defconst org-level-faces
2132 '(org-level-1 org-level-2 org-level-3 org-level-4
2133 org-level-5 org-level-6 org-level-7 org-level-8
2135 (defconst org-n-levels (length org-level-faces))
2137 (defconst org-bold-re
2138 (if (featurep 'xemacs)
2139 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2140 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2141 "Regular expression for bold emphasis.")
2142 (defconst org-italic-re
2143 (if (featurep 'xemacs)
2144 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2145 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2146 "Regular expression for italic emphasis.")
2147 (defconst org-underline-re
2148 (if (featurep 'xemacs)
2149 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2150 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2151 "Regular expression for underline emphasis.")
2153 ;; Variables for pre-computed regular expressions, all buffer local
2154 (defvar org-done-string nil
2155 "The last string in `org-todo-keywords', indicating an item is DONE.")
2156 (make-variable-buffer-local 'org-done-string)
2157 (defvar org-todo-regexp nil
2158 "Matches any of the TODO state keywords.")
2159 (make-variable-buffer-local 'org-todo-regexp)
2160 (defvar org-not-done-regexp nil
2161 "Matches any of the TODO state keywords except the last one.")
2162 (make-variable-buffer-local 'org-not-done-regexp)
2163 (defvar org-todo-line-regexp nil
2164 "Matches a headline and puts TODO state into group 2 if present.")
2165 (make-variable-buffer-local 'org-todo-line-regexp)
2166 (defvar org-nl-done-regexp nil
2167 "Matches newline followed by a headline with the DONE keyword.")
2168 (make-variable-buffer-local 'org-nl-done-regexp)
2169 (defvar org-looking-at-done-regexp nil
2170 "Matches the DONE keyword a point.")
2171 (make-variable-buffer-local 'org-looking-at-done-regexp)
2172 (defvar org-todo-kwd-priority-p nil
2173 "Do TODO items have priorities?")
2174 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2175 (defvar org-todo-kwd-max-priority nil
2176 "Maximum priority of TODO items.")
2177 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2178 (defvar org-ds-keyword-length 12
2179 "Maximum length of the Deadline and SCHEDULED keywords.")
2180 (make-variable-buffer-local 'org-ds-keyword-length)
2181 (defvar org-deadline-regexp nil
2182 "Matches the DEADLINE keyword.")
2183 (make-variable-buffer-local 'org-deadline-regexp)
2184 (defvar org-deadline-time-regexp nil
2185 "Matches the DEADLINE keyword together with a time stamp.")
2186 (make-variable-buffer-local 'org-deadline-time-regexp)
2187 (defvar org-deadline-line-regexp nil
2188 "Matches the DEADLINE keyword and the rest of the line.")
2189 (make-variable-buffer-local 'org-deadline-line-regexp)
2190 (defvar org-scheduled-regexp nil
2191 "Matches the SCHEDULED keyword.")
2192 (make-variable-buffer-local 'org-scheduled-regexp)
2193 (defvar org-scheduled-time-regexp nil
2194 "Matches the SCHEDULED keyword together with a time stamp.")
2195 (make-variable-buffer-local 'org-scheduled-time-regexp)
2197 (defun org-set-regexps-and-options ()
2198 "Precompute regular expressions for current buffer."
2199 (when (eq major-mode 'org-mode)
2200 (let ((re (org-make-options-regexp
2201 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2202 "STARTUP" "ARCHIVE")))
2203 (splitre "[ \t]+")
2204 kwds int key value cat arch)
2205 (save-excursion
2206 (save-restriction
2207 (widen)
2208 (goto-char (point-min))
2209 (while (re-search-forward re nil t)
2210 (setq key (match-string 1) value (match-string 2))
2211 (cond
2212 ((equal key "CATEGORY")
2213 (if (string-match "[ \t]+$" value)
2214 (setq value (replace-match "" t t value)))
2215 (setq cat (intern value)))
2216 ((equal key "SEQ_TODO")
2217 (setq int 'sequence
2218 kwds (append kwds (org-split-string value splitre))))
2219 ((equal key "PRI_TODO")
2220 (setq int 'priority
2221 kwds (append kwds (org-split-string value splitre))))
2222 ((equal key "TYP_TODO")
2223 (setq int 'type
2224 kwds (append kwds (org-split-string value splitre))))
2225 ((equal key "STARTUP")
2226 (debug)
2227 (let ((opts (org-split-string value splitre))
2228 (set '(("fold" org-startup-folded t)
2229 ("overview" org-startup-folded t)
2230 ("nofold" org-startup-folded nil)
2231 ("showall" org-startup-folded nil)
2232 ("content" org-startup-folded content)
2233 ("hidestars" org-hide-leading-stars t)
2234 ("showstars" org-hide-leading-stars nil)
2235 ("odd" org-odd-levels-only t)
2236 ("oddeven" org-odd-levels-only nil)
2237 ("align" org-startup-align-all-tables t)
2238 ("noalign" org-startup-align-all-tables nil)
2239 ("dlcheck" org-startup-with-deadline-check t)
2240 ("nodlcheck" org-startup-with-deadline-check nil)))
2241 l var val)
2242 (while (setq l (assoc (pop opts) set))
2243 (setq var (nth 1 l) val (nth 2 l))
2244 (set (make-local-variable var) val))))
2245 ((equal key "ARCHIVE")
2246 (string-match " *$" value)
2247 (setq arch (replace-match "" t t value))
2248 (remove-text-properties 0 (length arch)
2249 '(face t fontified t) arch)))
2251 (and cat (set (make-local-variable 'org-category) cat))
2252 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2253 (and arch (set (make-local-variable 'org-archive-location) arch))
2254 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2255 ;; Compute the regular expressions and other local variables
2256 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2257 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2258 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2259 (length org-scheduled-string)))
2260 org-done-string
2261 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2262 org-todo-regexp
2263 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2264 "\\|") "\\)\\>")
2265 org-not-done-regexp
2266 (concat "\\<\\("
2267 (mapconcat 'regexp-quote
2268 (nreverse (cdr (reverse org-todo-keywords)))
2269 "\\|")
2270 "\\)\\>")
2271 org-todo-line-regexp
2272 (concat "^\\(\\*+\\)[ \t]*\\("
2273 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2274 "\\)? *\\(.*\\)")
2275 org-nl-done-regexp
2276 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2277 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2278 org-deadline-regexp (concat "\\<" org-deadline-string)
2279 org-deadline-time-regexp
2280 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2281 org-deadline-line-regexp
2282 (concat "\\<\\(" org-deadline-string "\\).*")
2283 org-scheduled-regexp
2284 (concat "\\<" org-scheduled-string)
2285 org-scheduled-time-regexp
2286 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2287 (org-set-font-lock-defaults)))
2289 ;; Tell the compiler about dynamically scoped variables,
2290 ;; and variables from other packages
2291 (defvar zmacs-regions) ; XEmacs regions
2292 (defvar original-date) ; dynamically scoped in calendar
2293 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2294 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2295 (defvar org-html-entities) ; defined later in this file
2296 (defvar org-goto-start-pos) ; dynamically scoped parameter
2297 (defvar org-time-was-given) ; dynamically scoped parameter
2298 (defvar org-ts-what) ; dynamically scoped parameter
2299 (defvar mark-active) ; Emacs only, not available in XEmacs.
2300 (defvar timecnt) ; dynamically scoped parameter
2301 (defvar levels-open) ; dynamically scoped parameter
2302 (defvar title) ; dynamically scoped parameter
2303 (defvar author) ; dynamically scoped parameter
2304 (defvar email) ; dynamically scoped parameter
2305 (defvar text) ; dynamically scoped parameter
2306 (defvar entry) ; dynamically scoped parameter
2307 (defvar date) ; dynamically scoped parameter
2308 (defvar language) ; dynamically scoped parameter
2309 (defvar options) ; dynamically scoped parameter
2310 (defvar ans1) ; dynamically scoped parameter
2311 (defvar ans2) ; dynamically scoped parameter
2312 (defvar starting-day) ; local variable
2313 (defvar include-all-loc) ; local variable
2314 (defvar vm-message-pointer) ; from vm
2315 (defvar vm-folder-directory) ; from vm
2316 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2317 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2318 (defvar gnus-group-name) ; from gnus
2319 (defvar gnus-article-current) ; from gnus
2320 (defvar w3m-current-url) ; from w3m
2321 (defvar mh-progs) ; from MH-E
2322 (defvar mh-current-folder) ; from MH-E
2323 (defvar mh-show-folder-buffer) ; from MH-E
2324 (defvar mh-index-folder) ; from MH-E
2325 (defvar mh-searcher) ; from MH-E
2326 (defvar org-selected-point) ; dynamically scoped parameter
2327 (defvar calendar-mode-map) ; from calendar.el
2328 (defvar last-arg) ; local variable
2329 (defvar remember-save-after-remembering) ; from remember.el
2330 (defvar remember-data-file) ; from remember.el
2331 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2332 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2333 (defvar orgtbl-mode) ; defined later in this file
2334 ;;; Define the mode
2336 (defvar org-mode-map
2337 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2338 (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.")
2339 (copy-keymap outline-mode-map))
2340 "Keymap for Org-mode.")
2342 (defvar org-struct-menu) ; defined later in this file
2343 (defvar org-org-menu) ; defined later in this file
2344 (defvar org-tbl-menu) ; defined later in this file
2346 ;; We use a before-change function to check if a table might need
2347 ;; an update.
2348 (defvar org-table-may-need-update t
2349 "Indicates that a table might need an update.
2350 This variable is set by `org-before-change-function'.
2351 `org-table-align' sets it back to nil.")
2352 (defvar org-mode-hook nil)
2353 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2354 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2357 ;;;###autoload
2358 (define-derived-mode org-mode outline-mode "Org"
2359 "Outline-based notes management and organizer, alias
2360 \"Carsten's outline-mode for keeping track of everything.\"
2362 Org-mode develops organizational tasks around a NOTES file which
2363 contains information about projects as plain text. Org-mode is
2364 implemented on top of outline-mode, which is ideal to keep the content
2365 of large files well structured. It supports ToDo items, deadlines and
2366 time stamps, which magically appear in the diary listing of the Emacs
2367 calendar. Tables are easily created with a built-in table editor.
2368 Plain text URL-like links connect to websites, emails (VM), Usenet
2369 messages (Gnus), BBDB entries, and any files related to the project.
2370 For printing and sharing of notes, an Org-mode file (or a part of it)
2371 can be exported as a structured ASCII or HTML file.
2373 The following commands are available:
2375 \\{org-mode-map}"
2376 (easy-menu-add org-org-menu)
2377 (easy-menu-add org-tbl-menu)
2378 (org-install-agenda-files-menu)
2379 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2380 (org-add-to-invisibility-spec '(org-cwidth))
2381 (setq outline-regexp "\\*+")
2382 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2383 (setq outline-level 'org-outline-level)
2384 (when (and org-ellipsis (stringp org-ellipsis))
2385 (unless org-display-table
2386 (setq org-display-table (make-display-table)))
2387 (set-display-table-slot org-display-table
2388 4 (string-to-vector org-ellipsis))
2389 (setq buffer-display-table org-display-table))
2390 (org-set-regexps-and-options)
2391 (if org-startup-truncated (setq truncate-lines t))
2392 (set (make-local-variable 'font-lock-unfontify-region-function)
2393 'org-unfontify-region)
2394 ;; Activate before-change-function
2395 (set (make-local-variable 'org-table-may-need-update) t)
2396 (org-add-hook 'before-change-functions 'org-before-change-function nil
2397 'local)
2398 ;; Paragraphs and auto-filling
2399 (org-set-autofill-regexps)
2400 (org-update-radio-target-regexp)
2401 ;; Settings for Calc embedded mode
2402 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2403 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2404 (if (and org-insert-mode-line-in-empty-file
2405 (interactive-p)
2406 (= (point-min) (point-max)))
2407 (insert " -*- mode: org -*-\n\n"))
2409 ;; Get rid of Outline menus, they are not needed
2410 ;; Need to do this here because define-derived-mode sets up
2411 ;; the keymap so late.
2412 (if (featurep 'xemacs)
2413 (progn
2414 (delete-menu-item '("Headings"))
2415 (delete-menu-item '("Show"))
2416 (delete-menu-item '("Hide"))
2417 (set-menubar-dirty-flag))
2418 (define-key org-mode-map [menu-bar headings] 'undefined)
2419 (define-key org-mode-map [menu-bar hide] 'undefined)
2420 (define-key org-mode-map [menu-bar show] 'undefined))
2422 (unless org-inhibit-startup
2423 (if org-startup-align-all-tables
2424 (org-table-map-tables 'org-table-align))
2425 (if org-startup-with-deadline-check
2426 (call-interactively 'org-check-deadlines)
2427 (cond
2428 ((eq org-startup-folded t)
2429 (org-cycle '(4)))
2430 ((eq org-startup-folded 'content)
2431 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2432 (org-cycle '(4)) (org-cycle '(4))))))))
2434 (defsubst org-current-line (&optional pos)
2435 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2437 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2438 mouse-map t)
2439 "Properties to remove when a string without properties is wanted.")
2441 (defsubst org-match-string-no-properties (num &optional string)
2442 (if (featurep 'xemacs)
2443 (let ((s (match-string num string)))
2444 (remove-text-properties 0 (length s) org-rm-props s)
2446 (match-string-no-properties num string)))
2448 (defsubst org-no-properties (s)
2449 (remove-text-properties 0 (length s) org-rm-props s)
2452 (defun org-current-time ()
2453 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2454 (if (> org-time-stamp-rounding-minutes 0)
2455 (let ((r org-time-stamp-rounding-minutes)
2456 (time (decode-time)))
2457 (apply 'encode-time
2458 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2459 (nthcdr 2 time))))
2460 (current-time)))
2462 (defun org-add-props (string plist &rest props)
2463 "Add text properties to entire string, from beginning to end.
2464 PLIST may be a list of properties, PROPS are individual properties and values
2465 that will be added to PLIST. Returns the string that was modified."
2466 (add-text-properties
2467 0 (length string) (if props (append plist props) plist) string)
2468 string)
2469 (put 'org-add-props 'lisp-indent-function 2)
2472 ;;; Font-Lock stuff
2474 (defvar org-mouse-map (make-sparse-keymap))
2475 (define-key org-mouse-map
2476 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2477 (define-key org-mouse-map
2478 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2479 (when org-mouse-1-follows-link
2480 (define-key org-mouse-map [follow-link] 'mouse-face))
2481 (when org-tab-follows-link
2482 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2483 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2484 (when org-return-follows-link
2485 (define-key org-mouse-map [(return)] 'org-open-at-point)
2486 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2488 (require 'font-lock)
2490 (defconst org-non-link-chars "]\t\n\r<>")
2491 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2492 "wl" "mhe" "rmail" "gnus" "shell"))
2493 (defconst org-link-re-with-space
2494 (concat
2495 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2496 "\\([^" org-non-link-chars " ]"
2497 "[^" org-non-link-chars "]*"
2498 "[^" org-non-link-chars " ]\\)>?")
2499 "Matches a link with spaces, optional angular brackets around it.")
2501 (defconst org-link-re-with-space2
2502 (concat
2503 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2504 "\\([^" org-non-link-chars " ]"
2505 "[^]\t\n\r]*"
2506 "[^" org-non-link-chars " ]\\)>?")
2507 "Matches a link with spaces, optional angular brackets around it.")
2509 (defconst org-angle-link-re
2510 (concat
2511 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2512 "\\([^" org-non-link-chars " ]"
2513 "[^" org-non-link-chars "]*"
2514 "\\)>")
2515 "Matches link with angular brackets, spaces are allowed.")
2516 (defconst org-plain-link-re
2517 (concat
2518 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2519 "\\([^]\t\n\r<>,;() ]+\\)")
2520 "Matches plain link, without spaces.")
2522 (defconst org-bracket-link-regexp
2523 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2524 "Matches a link in double brackets.")
2526 (defconst org-bracket-link-analytic-regexp
2527 (concat
2528 "\\[\\["
2529 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2530 "\\([^]]+\\)"
2531 "\\]"
2532 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2533 "\\]"))
2534 ; 1: http:
2535 ; 2: http
2536 ; 3: path
2537 ; 4: [desc]
2538 ; 5: desc
2541 (defconst org-ts-lengths
2542 (cons (length (format-time-string (car org-time-stamp-formats)))
2543 (length (format-time-string (cdr org-time-stamp-formats))))
2544 "This holds the lengths of the two different time formats.")
2545 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2546 "Regular expression for fast time stamp matching.")
2547 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2548 "Regular expression for fast time stamp matching.")
2549 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2550 "Regular expression matching time strings for analysis.")
2551 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2552 "Regular expression matching time stamps, with groups.")
2553 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2554 "Regular expression matching a time stamp range.")
2555 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2556 org-ts-regexp "\\)?")
2557 "Regular expression matching a time stamp or time stamp range.")
2559 (defun org-activate-plain-links (limit)
2560 "Run through the buffer and add overlays to links."
2561 (if (re-search-forward org-plain-link-re limit t)
2562 (progn
2563 (add-text-properties (match-beginning 0) (match-end 0)
2564 (list 'mouse-face 'highlight
2565 'keymap org-mouse-map
2567 t)))
2569 (defun org-activate-angle-links (limit)
2570 "Run through the buffer and add overlays to links."
2571 (if (re-search-forward org-angle-link-re limit t)
2572 (progn
2573 (add-text-properties (match-beginning 0) (match-end 0)
2574 (list 'mouse-face 'highlight
2575 'keymap org-mouse-map
2577 t)))
2579 (defun org-activate-bracket-links (limit)
2580 "Run through the buffer and add overlays to bracketed links."
2581 (if (re-search-forward org-bracket-link-regexp limit t)
2582 (let* ((help (concat "LINK: "
2583 (org-match-string-no-properties 1)))
2584 ;; FIXME: above we should remove the escapes.
2585 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2586 'keymap org-mouse-map 'mouse-face 'highlight
2587 'help-echo help))
2588 (vp (list 'rear-nonsticky t
2589 'keymap org-mouse-map 'mouse-face 'highlight
2590 'help-echo help)))
2591 ;; We need to remove the invisible property here. Table narrowing
2592 ;; may have made some of this invisible.
2593 (remove-text-properties (match-beginning 0) (match-end 0)
2594 '(invisible nil))
2595 (if (match-end 3)
2596 (progn
2597 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2598 (add-text-properties (match-beginning 3) (match-end 3) vp)
2599 (add-text-properties (match-end 3) (match-end 0) ip))
2600 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2601 (add-text-properties (match-beginning 1) (match-end 1) vp)
2602 (add-text-properties (match-end 1) (match-end 0) ip))
2603 t)))
2605 (defun org-activate-dates (limit)
2606 "Run through the buffer and add overlays to dates."
2607 (if (re-search-forward org-tsr-regexp limit t)
2608 (progn
2609 (add-text-properties (match-beginning 0) (match-end 0)
2610 (list 'mouse-face 'highlight
2611 'keymap org-mouse-map))
2612 t)))
2614 (defvar org-target-link-regexp nil
2615 "Regular expression matching radio targets in plain text.")
2616 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2617 "Regular expression matching a link target.")
2618 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2619 "Regular expression matching a link target.")
2621 (defun org-activate-target-links (limit)
2622 "Run through the buffer and add overlays to target matches."
2623 (when org-target-link-regexp
2624 (let ((case-fold-search t))
2625 (if (re-search-forward org-target-link-regexp limit t)
2626 (progn
2627 (add-text-properties (match-beginning 0) (match-end 0)
2628 (list 'mouse-face 'highlight
2629 'keymap org-mouse-map
2630 'help-echo "Radio target link"
2631 'org-linked-text t))
2632 t)))))
2634 (defun org-update-radio-target-regexp ()
2635 "Find all radio targets in this file and update the regular expression."
2636 (interactive)
2637 (when (memq 'radio org-activate-links)
2638 (setq org-target-link-regexp
2639 (org-make-target-link-regexp (org-all-targets 'radio)))
2640 (org-restart-font-lock)))
2642 (defun org-hide-wide-columns (limit)
2643 (let (s e)
2644 (setq s (text-property-any (point) (or limit (point-max))
2645 'org-cwidth t))
2646 (when s
2647 (setq e (next-single-property-change s 'org-cwidth))
2648 (add-text-properties s e '(invisible org-cwidth intangible t))
2649 (goto-char e)
2650 t)))
2652 (defun org-restart-font-lock ()
2653 "Restart font-lock-mode, to force refontification."
2654 (when (and (boundp 'font-lock-mode) font-lock-mode)
2655 (font-lock-mode -1)
2656 (font-lock-mode 1)))
2658 (defun org-all-targets (&optional radio)
2659 "Return a list of all targets in this file.
2660 With optional argument RADIO, only find radio targets."
2661 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2662 rtn)
2663 (save-excursion
2664 (goto-char (point-min))
2665 (while (re-search-forward re nil t)
2666 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2667 rtn)))
2669 (defun org-make-target-link-regexp (targets)
2670 "Make regular expression matching all strings in TARGETS.
2671 The regular expression finds the targets also if there is a line break
2672 between words."
2673 (and targets
2674 (concat
2675 "\\<\\("
2676 (mapconcat
2677 (lambda (x)
2678 (while (string-match " +" x)
2679 (setq x (replace-match "\\s-+" t t x)))
2681 targets
2682 "\\|")
2683 "\\)\\>")))
2685 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2686 "Matches CamelCase words, possibly with a star before it.")
2688 (defun org-activate-camels (limit)
2689 "Run through the buffer and add overlays to dates."
2690 (if (re-search-forward org-camel-regexp limit t)
2691 (progn
2692 (add-text-properties (match-beginning 0) (match-end 0)
2693 (list 'mouse-face 'highlight
2694 'keymap org-mouse-map))
2695 t)))
2697 (defun org-activate-tags (limit)
2698 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2699 (progn
2700 (add-text-properties (match-beginning 1) (match-end 1)
2701 (list 'mouse-face 'highlight
2702 'keymap org-mouse-map))
2703 t)))
2705 (defun org-font-lock-level ()
2706 (save-excursion
2707 (org-back-to-heading t)
2708 (- (match-end 0) (match-beginning 0))))
2710 (defun org-outline-level ()
2711 (save-excursion
2712 (looking-at outline-regexp)
2713 (if (match-beginning 1)
2714 (+ (org-get-string-indentation (match-string 1)) 1000)
2715 (- (match-end 0) (match-beginning 0)))))
2717 (defvar org-font-lock-keywords nil)
2719 (defun org-set-font-lock-defaults ()
2720 (let* ((em org-fontify-emphasized-text)
2721 (lk org-activate-links)
2722 (org-font-lock-extra-keywords
2723 (list
2724 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2725 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2726 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2727 (1 'org-table))
2728 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2729 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2730 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2731 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2732 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
2733 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2734 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2735 (if org-table-limit-column-width
2736 '(org-hide-wide-columns (0 nil append)))
2737 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2738 '(1 'org-todo t))
2739 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2740 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2741 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2742 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2743 ; (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2744 ; (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2745 ; (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2746 (if em (list org-bold-re 2 ''bold 'prepend))
2747 (if em (list org-italic-re 2 ''italic 'prepend))
2748 (if em (list org-underline-re 2 ''underline 'prepend))
2749 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2750 "\\|" org-quote-string "\\)\\>")
2751 '(1 'org-special-keyword t))
2752 '("^#.*" (0 'font-lock-comment-face t))
2753 (if org-fontify-done-headline
2754 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2755 '(1 'org-done t) '(2 'org-headline-done t))
2756 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2757 '(1 'org-done t)))
2758 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2759 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2760 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2761 (if org-format-transports-properties-p
2762 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
2764 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2765 ;; Now set the full font-lock-keywords
2766 (set (make-local-variable 'org-font-lock-keywords)
2767 org-font-lock-extra-keywords)
2768 (set (make-local-variable 'font-lock-defaults)
2769 '(org-font-lock-keywords t nil nil backward-paragraph))
2770 (kill-local-variable 'font-lock-keywords) nil))
2772 (defvar org-m nil)
2773 (defvar org-l nil)
2774 (defvar org-f nil)
2775 (defun org-get-level-face (n)
2776 "Get the right face for match N in font-lock matching of healdines."
2777 (setq org-l (- (match-end 2) (match-beginning 1)))
2778 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2779 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2780 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2781 (cond
2782 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2783 ((eq n 2) org-f)
2784 (t (if org-level-color-stars-only nil org-f))))
2786 (defun org-unfontify-region (beg end &optional maybe_loudly)
2787 "Remove fontification and activation overlays from links."
2788 (font-lock-default-unfontify-region beg end)
2789 (let* ((buffer-undo-list t)
2790 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2791 (inhibit-modification-hooks t)
2792 deactivate-mark buffer-file-name buffer-file-truename)
2793 (remove-text-properties beg end
2794 '(mouse-face nil keymap nil org-linked-text nil
2795 invisible nil intangible nil))))
2796 ;;; Visibility cycling
2798 (defvar org-cycle-global-status nil)
2799 (defvar org-cycle-subtree-status nil)
2800 (defun org-cycle (&optional arg)
2801 "Visibility cycling for Org-mode.
2803 - When this function is called with a prefix argument, rotate the entire
2804 buffer through 3 states (global cycling)
2805 1. OVERVIEW: Show only top-level headlines.
2806 2. CONTENTS: Show all headlines of all levels, but no body text.
2807 3. SHOW ALL: Show everything.
2809 - When point is at the beginning of a headline, rotate the subtree started
2810 by this line through 3 different states (local cycling)
2811 1. FOLDED: Only the main headline is shown.
2812 2. CHILDREN: The main headline and the direct children are shown.
2813 From this state, you can move to one of the children
2814 and zoom in further.
2815 3. SUBTREE: Show the entire subtree, including body text.
2817 - When there is a numeric prefix, go up to a heading with level ARG, do
2818 a `show-subtree' and return to the previous cursor position. If ARG
2819 is negative, go up that many levels.
2821 - When point is not at the beginning of a headline, execute
2822 `indent-relative', like TAB normally does. See the option
2823 `org-cycle-emulate-tab' for details.
2825 - Special case: if point is the the beginning of the buffer and there is
2826 no headline in line 1, this function will act as if called with prefix arg."
2827 (interactive "P")
2829 (if (or (and (bobp) (not (looking-at outline-regexp)))
2830 (equal arg '(4)))
2831 ;; special case: use global cycling
2832 (setq arg t))
2834 (let ((outline-regexp
2835 (if org-cycle-include-plain-lists
2836 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2837 outline-regexp)))
2839 (cond
2841 ((org-at-table-p 'any)
2842 ;; Enter the table or move to the next field in the table
2843 (or (org-table-recognize-table.el)
2844 (progn
2845 (if arg (org-table-edit-field t)
2846 (org-table-justify-field-maybe)
2847 (org-table-next-field)))))
2849 ((eq arg t) ;; Global cycling
2851 (cond
2852 ((and (eq last-command this-command)
2853 (eq org-cycle-global-status 'overview))
2854 ;; We just created the overview - now do table of contents
2855 ;; This can be slow in very large buffers, so indicate action
2856 (message "CONTENTS...")
2857 (save-excursion
2858 ;; Visit all headings and show their offspring
2859 (goto-char (point-max))
2860 (catch 'exit
2861 (while (and (progn (condition-case nil
2862 (outline-previous-visible-heading 1)
2863 (error (goto-char (point-min))))
2865 (looking-at outline-regexp))
2866 (show-branches)
2867 (if (bobp) (throw 'exit nil))))
2868 (message "CONTENTS...done"))
2869 (setq org-cycle-global-status 'contents)
2870 (run-hook-with-args 'org-cycle-hook 'contents))
2872 ((and (eq last-command this-command)
2873 (eq org-cycle-global-status 'contents))
2874 ;; We just showed the table of contents - now show everything
2875 (show-all)
2876 (message "SHOW ALL")
2877 (setq org-cycle-global-status 'all)
2878 (run-hook-with-args 'org-cycle-hook 'all))
2881 ;; Default action: go to overview
2882 (hide-sublevels 1)
2883 (message "OVERVIEW")
2884 (setq org-cycle-global-status 'overview)
2885 (run-hook-with-args 'org-cycle-hook 'overview))))
2887 ((integerp arg)
2888 ;; Show-subtree, ARG levels up from here.
2889 (save-excursion
2890 (org-back-to-heading)
2891 (outline-up-heading (if (< arg 0) (- arg)
2892 (- (funcall outline-level) arg)))
2893 (org-show-subtree)))
2895 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2896 ;; At a heading: rotate between three different views
2897 (org-back-to-heading)
2898 (let ((goal-column 0) eoh eol eos)
2899 ;; First, some boundaries
2900 (save-excursion
2901 (org-back-to-heading)
2902 (save-excursion
2903 (beginning-of-line 2)
2904 (while (and (not (eobp)) ;; this is like `next-line'
2905 (get-char-property (1- (point)) 'invisible))
2906 (beginning-of-line 2)) (setq eol (point)))
2907 (outline-end-of-heading) (setq eoh (point))
2908 (org-end-of-subtree t) (setq eos (point))
2909 (outline-next-heading))
2910 ;; Find out what to do next and set `this-command'
2911 (cond
2912 ((= eos eoh)
2913 ;; Nothing is hidden behind this heading
2914 (message "EMPTY ENTRY")
2915 (setq org-cycle-subtree-status nil))
2916 ((>= eol eos)
2917 ;; Entire subtree is hidden in one line: open it
2918 (org-show-entry)
2919 (show-children)
2920 (message "CHILDREN")
2921 (setq org-cycle-subtree-status 'children)
2922 (run-hook-with-args 'org-cycle-hook 'children))
2923 ((and (eq last-command this-command)
2924 (eq org-cycle-subtree-status 'children))
2925 ;; We just showed the children, now show everything.
2926 (org-show-subtree)
2927 (message "SUBTREE")
2928 (setq org-cycle-subtree-status 'subtree)
2929 (run-hook-with-args 'org-cycle-hook 'subtree))
2931 ;; Default action: hide the subtree.
2932 (hide-subtree)
2933 (message "FOLDED")
2934 (setq org-cycle-subtree-status 'folded)
2935 (run-hook-with-args 'org-cycle-hook 'folded)))))
2937 ;; TAB emulation
2938 (buffer-read-only (org-back-to-heading))
2939 ((if (and (eq org-cycle-emulate-tab 'white)
2940 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2942 (eq org-cycle-emulate-tab t))
2943 (if (and (looking-at "[ \n\r\t]")
2944 (string-match "^[ \t]*$" (buffer-substring
2945 (point-at-bol) (point))))
2946 (progn
2947 (beginning-of-line 1)
2948 (and (looking-at "[ \t]+") (replace-match ""))))
2949 (indent-relative))
2951 (t (save-excursion
2952 (org-back-to-heading)
2953 (org-cycle))))))
2955 (defun org-optimize-window-after-visibility-change (state)
2956 "Adjust the window after a change in outline visibility.
2957 This function is the default value of the hook `org-cycle-hook'."
2958 (when (get-buffer-window (current-buffer))
2959 (cond
2960 ((eq state 'overview) (org-first-headline-recenter 1))
2961 ((eq state 'content) nil)
2962 ((eq state 'all) nil)
2963 ((eq state 'folded) nil)
2964 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2965 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
2967 (defun org-subtree-end-visible-p ()
2968 "Is the end of the current subtree visible?"
2969 (pos-visible-in-window-p
2970 (save-excursion (org-end-of-subtree t) (point))))
2972 (defun org-first-headline-recenter (&optional N)
2973 "Move cursor to the first headline and recenter the headline.
2974 Optional argument N means, put the headline into the Nth line of the window."
2975 (goto-char (point-min))
2976 (when (re-search-forward (concat "^" outline-regexp) nil t)
2977 (beginning-of-line)
2978 (recenter (prefix-numeric-value N))))
2980 (defvar org-goto-window-configuration nil)
2981 (defvar org-goto-marker nil)
2982 (defvar org-goto-map (make-sparse-keymap))
2983 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2984 (while (setq cmd (pop cmds))
2985 (substitute-key-definition cmd cmd org-goto-map global-map)))
2986 (define-key org-goto-map "\C-m" 'org-goto-ret)
2987 (define-key org-goto-map [(left)] 'org-goto-left)
2988 (define-key org-goto-map [(right)] 'org-goto-right)
2989 (define-key org-goto-map [(?q)] 'org-goto-quit)
2990 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2991 (define-key org-goto-map "\C-i" 'org-cycle)
2992 (define-key org-goto-map [(tab)] 'org-cycle)
2993 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2994 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2995 (define-key org-goto-map "n" 'outline-next-visible-heading)
2996 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2997 (define-key org-goto-map "f" 'outline-forward-same-level)
2998 (define-key org-goto-map "b" 'outline-backward-same-level)
2999 (define-key org-goto-map "u" 'outline-up-heading)
3000 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3001 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3002 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3003 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3004 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3005 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3006 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3008 (defconst org-goto-help
3009 "Select a location to jump to, press RET
3010 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3012 (defun org-goto ()
3013 "Go to a different location of the document, keeping current visibility.
3015 When you want to go to a different location in a document, the fastest way
3016 is often to fold the entire buffer and then dive into the tree. This
3017 method has the disadvantage, that the previous location will be folded,
3018 which may not be what you want.
3020 This command works around this by showing a copy of the current buffer in
3021 overview mode. You can dive into the tree in that copy, to find the
3022 location you want to reach. When pressing RET, the command returns to the
3023 original buffer in which the visibility is still unchanged. It then jumps
3024 to the new location, making it and the headline hierarchy above it visible."
3025 (interactive)
3026 (let* ((org-goto-start-pos (point))
3027 (selected-point
3028 (org-get-location (current-buffer) org-goto-help)))
3029 (if selected-point
3030 (progn
3031 (org-mark-ring-push org-goto-start-pos)
3032 (goto-char selected-point)
3033 (if (or (org-invisible-p) (org-invisible-p2))
3034 (org-show-hierarchy-above)))
3035 (error "Quit"))))
3037 (defun org-get-location (buf help)
3038 "Let the user select a location in the Org-mode buffer BUF.
3039 This function uses a recursive edit. It returns the selected position
3040 or nil."
3041 (let (org-selected-point)
3042 (save-excursion
3043 (save-window-excursion
3044 (delete-other-windows)
3045 (switch-to-buffer (get-buffer-create "*org-goto*"))
3046 (with-output-to-temp-buffer "*Help*"
3047 (princ help))
3048 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3049 (setq buffer-read-only nil)
3050 (erase-buffer)
3051 (insert-buffer-substring buf)
3052 (let ((org-startup-truncated t)
3053 (org-startup-folded t)
3054 (org-startup-align-all-tables nil)
3055 (org-startup-with-deadline-check nil))
3056 (org-mode))
3057 (setq buffer-read-only t)
3058 (if (boundp 'org-goto-start-pos)
3059 (goto-char org-goto-start-pos)
3060 (goto-char (point-min)))
3061 (org-beginning-of-line)
3062 (message "Select location and press RET")
3063 ;; now we make sure that during selection, ony very few keys work
3064 ;; and that it is impossible to switch to another window.
3065 (let ((gm (current-global-map))
3066 (overriding-local-map org-goto-map))
3067 (unwind-protect
3068 (progn
3069 (use-global-map org-goto-map)
3070 (recursive-edit))
3071 (use-global-map gm)))))
3072 (kill-buffer "*org-goto*")
3073 org-selected-point))
3075 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3076 (defun org-goto-ret (&optional arg)
3077 "Finish `org-goto' by going to the new location."
3078 (interactive "P")
3079 (setq org-selected-point (point)
3080 current-prefix-arg arg)
3081 (throw 'exit nil))
3083 (defun org-goto-left ()
3084 "Finish `org-goto' by going to the new location."
3085 (interactive)
3086 (if (org-on-heading-p)
3087 (progn
3088 (beginning-of-line 1)
3089 (setq org-selected-point (point)
3090 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3091 (throw 'exit nil))
3092 (error "Not on a heading")))
3094 (defun org-goto-right ()
3095 "Finish `org-goto' by going to the new location."
3096 (interactive)
3097 (if (org-on-heading-p)
3098 (progn
3099 (outline-end-of-subtree)
3100 (or (eobp) (forward-char 1))
3101 (setq org-selected-point (point)
3102 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3103 (throw 'exit nil))
3104 (error "Not on a heading")))
3106 (defun org-goto-quit ()
3107 "Finish `org-goto' without cursor motion."
3108 (interactive)
3109 (setq org-selected-point nil)
3110 (throw 'exit nil))
3112 ;;; Promotion, Demotion, Inserting new headlines
3114 (defvar org-ignore-region nil
3115 "To temporarily disable the active region.")
3117 (defun org-insert-heading (&optional force-heading)
3118 "Insert a new heading or item with same depth at point."
3119 (interactive "P")
3120 (when (or force-heading (not (org-insert-item)))
3121 (let* ((head (save-excursion
3122 (condition-case nil
3123 (org-back-to-heading)
3124 (error (outline-next-heading)))
3125 (prog1 (match-string 0)
3126 (funcall outline-level)))))
3127 (cond
3128 ((and (org-on-heading-p) (bolp)
3129 (save-excursion (backward-char 1) (not (org-invisible-p))))
3130 (open-line 1))
3131 ((bolp) nil)
3132 (t (newline)))
3133 (insert head)
3134 (just-one-space)
3135 (run-hooks 'org-insert-heading-hook))))
3137 (defun org-insert-item ()
3138 "Insert a new item at the current level.
3139 Return t when things worked, nil when we are not in an item."
3140 (when (save-excursion
3141 (condition-case nil
3142 (progn
3143 (org-beginning-of-item)
3144 (org-at-item-p)
3146 (error nil)))
3147 (let* ((bul (match-string 0))
3148 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3149 (match-end 0)))
3150 (eowcol (save-excursion (goto-char eow) (current-column))))
3151 (cond
3152 ((and (org-at-item-p) (<= (point) eow))
3153 ;; before the bullet
3154 (beginning-of-line 1)
3155 (open-line 1))
3156 ((<= (point) eow)
3157 (beginning-of-line 1))
3158 (t (newline)))
3159 (insert bul)
3160 (just-one-space))
3161 (org-maybe-renumber-ordered-list)
3164 (defun org-insert-todo-heading (arg)
3165 "Insert a new heading with the same level and TODO state as current heading.
3166 If the heading has no TODO state, or if the state is DONE, use the first
3167 state (TODO by default). Also with prefix arg, force first state."
3168 (interactive "P")
3169 (org-insert-heading)
3170 (save-excursion
3171 (org-back-to-heading)
3172 (outline-previous-heading)
3173 (looking-at org-todo-line-regexp))
3174 (if (or arg
3175 (not (match-beginning 2))
3176 (equal (match-string 2) org-done-string))
3177 (insert (car org-todo-keywords) " ")
3178 (insert (match-string 2) " ")))
3180 (defun org-promote-subtree ()
3181 "Promote the entire subtree.
3182 See also `org-promote'."
3183 (interactive)
3184 (save-excursion
3185 (org-map-tree 'org-promote)))
3187 (defun org-demote-subtree ()
3188 "Demote the entire subtree. See `org-demote'.
3189 See also `org-promote'."
3190 (interactive)
3191 (save-excursion
3192 (org-map-tree 'org-demote)))
3194 (defun org-do-promote ()
3195 "Promote the current heading higher up the tree.
3196 If the region is active in `transient-mark-mode', promote all headings
3197 in the region."
3198 (interactive)
3199 (save-excursion
3200 (if (org-region-active-p)
3201 (org-map-region 'org-promote (region-beginning) (region-end))
3202 (org-promote)))
3203 (org-fix-position-after-promote))
3205 (defun org-do-demote ()
3206 "Demote the current heading lower down the tree.
3207 If the region is active in `transient-mark-mode', demote all headings
3208 in the region."
3209 (interactive)
3210 (save-excursion
3211 (if (org-region-active-p)
3212 (org-map-region 'org-demote (region-beginning) (region-end))
3213 (org-demote)))
3214 (org-fix-position-after-promote))
3216 (defun org-fix-position-after-promote ()
3217 "Make sure that after pro/demotion cursor position is right."
3218 (and (equal (char-after) ?\ )
3219 (equal (char-before) ?*)
3220 (forward-char 1)))
3222 (defun org-get-legal-level (level change)
3223 "Rectify a level change under the influence of `org-odd-levels-only'
3224 LEVEL is a current level, CHANGE is by how much the level should be
3225 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3226 even level numbers will become the next higher odd number."
3227 (if org-odd-levels-only
3228 (cond ((not change) (1+ (* 2 (/ level 2))))
3229 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3230 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3231 (max 1 (+ level change))))
3233 (defun org-promote ()
3234 "Promote the current heading higher up the tree.
3235 If the region is active in `transient-mark-mode', promote all headings
3236 in the region."
3237 (org-back-to-heading t)
3238 (let* ((level (save-match-data (funcall outline-level)))
3239 (up-head (make-string (org-get-legal-level level -1) ?*))
3240 (diff (abs (- level (length up-head)))))
3241 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3242 (replace-match up-head nil t)
3243 ;; Fixup tag positioning
3244 (and org-auto-align-tags (org-set-tags nil t))
3245 (if org-adapt-indentation
3246 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3247 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3249 (defun org-demote ()
3250 "Demote the current heading lower down the tree.
3251 If the region is active in `transient-mark-mode', demote all headings
3252 in the region."
3253 (org-back-to-heading t)
3254 (let* ((level (save-match-data (funcall outline-level)))
3255 (down-head (make-string (org-get-legal-level level 1) ?*))
3256 (diff (abs (- level (length down-head)))))
3257 (replace-match down-head nil t)
3258 ;; Fixup tag positioning
3259 (and org-auto-align-tags (org-set-tags nil t))
3260 (if org-adapt-indentation
3261 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3263 (defun org-map-tree (fun)
3264 "Call FUN for every heading underneath the current one."
3265 (org-back-to-heading)
3266 (let ((level (funcall outline-level)))
3267 (save-excursion
3268 (funcall fun)
3269 (while (and (progn
3270 (outline-next-heading)
3271 (> (funcall outline-level) level))
3272 (not (eobp)))
3273 (funcall fun)))))
3275 (defun org-map-region (fun beg end)
3276 "Call FUN for every heading between BEG and END."
3277 (let ((org-ignore-region t))
3278 (save-excursion
3279 (setq end (copy-marker end))
3280 (goto-char beg)
3281 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3282 (< (point) end))
3283 (funcall fun))
3284 (while (and (progn
3285 (outline-next-heading)
3286 (< (point) end))
3287 (not (eobp)))
3288 (funcall fun)))))
3290 (defun org-fixup-indentation (from to prohibit)
3291 "Change the indentation in the current entry by re-replacing FROM with TO.
3292 However, if the regexp PROHIBIT matches at all, don't do anything.
3293 This is being used to change indentation along with the length of the
3294 heading marker. But if there are any lines which are not indented, nothing
3295 is changed at all."
3296 (save-excursion
3297 (let ((end (save-excursion (outline-next-heading)
3298 (point-marker))))
3299 (unless (save-excursion (re-search-forward prohibit end t))
3300 (while (re-search-forward from end t)
3301 (replace-match to)
3302 (beginning-of-line 2)))
3303 (move-marker end nil))))
3305 ;;; Vertical tree motion, cutting and pasting of subtrees
3307 (defun org-move-subtree-up (&optional arg)
3308 "Move the current subtree up past ARG headlines of the same level."
3309 (interactive "p")
3310 (org-move-subtree-down (- (prefix-numeric-value arg))))
3312 (defun org-move-subtree-down (&optional arg)
3313 "Move the current subtree down past ARG headlines of the same level."
3314 (interactive "p")
3315 (setq arg (prefix-numeric-value arg))
3316 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3317 'outline-get-last-sibling))
3318 (ins-point (make-marker))
3319 (cnt (abs arg))
3320 beg end txt folded)
3321 ;; Select the tree
3322 (org-back-to-heading)
3323 (setq beg (point))
3324 (save-match-data
3325 (save-excursion (outline-end-of-heading)
3326 (setq folded (org-invisible-p)))
3327 (outline-end-of-subtree))
3328 (outline-next-heading)
3329 (setq end (point))
3330 ;; Find insertion point, with error handling
3331 (goto-char beg)
3332 (while (> cnt 0)
3333 (or (and (funcall movfunc) (looking-at outline-regexp))
3334 (progn (goto-char beg)
3335 (error "Cannot move past superior level or buffer limit")))
3336 (setq cnt (1- cnt)))
3337 (if (> arg 0)
3338 ;; Moving forward - still need to move over subtree
3339 (progn (outline-end-of-subtree)
3340 (outline-next-heading)
3341 (if (not (or (looking-at (concat "^" outline-regexp))
3342 (bolp)))
3343 (newline))))
3344 (move-marker ins-point (point))
3345 (setq txt (buffer-substring beg end))
3346 (delete-region beg end)
3347 (insert txt)
3348 (goto-char ins-point)
3349 (if folded (hide-subtree))
3350 (move-marker ins-point nil)))
3352 (defvar org-subtree-clip ""
3353 "Clipboard for cut and paste of subtrees.
3354 This is actually only a copy of the kill, because we use the normal kill
3355 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3357 (defvar org-subtree-clip-folded nil
3358 "Was the last copied subtree folded?
3359 This is used to fold the tree back after pasting.")
3361 (defun org-cut-subtree ()
3362 "Cut the current subtree into the clipboard.
3363 This is a short-hand for marking the subtree and then cutting it."
3364 (interactive)
3365 (org-copy-subtree 'cut))
3367 (defun org-copy-subtree (&optional cut)
3368 "Cut the current subtree into the clipboard.
3369 This is a short-hand for marking the subtree and then copying it.
3370 If CUT is non nil, actually cut the subtree."
3371 (interactive)
3372 (let (beg end folded)
3373 (org-back-to-heading)
3374 (setq beg (point))
3375 (save-match-data
3376 (save-excursion (outline-end-of-heading)
3377 (setq folded (org-invisible-p)))
3378 (outline-end-of-subtree))
3379 (if (equal (char-after) ?\n) (forward-char 1))
3380 (setq end (point))
3381 (goto-char beg)
3382 (when (> end beg)
3383 (setq org-subtree-clip-folded folded)
3384 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3385 (setq org-subtree-clip (current-kill 0))
3386 (message "%s: Subtree with %d characters"
3387 (if cut "Cut" "Copied")
3388 (length org-subtree-clip)))))
3390 (defun org-paste-subtree (&optional level tree)
3391 "Paste the clipboard as a subtree, with modification of headline level.
3392 The entire subtree is promoted or demoted in order to match a new headline
3393 level. By default, the new level is derived from the visible headings
3394 before and after the insertion point, and taken to be the inferior headline
3395 level of the two. So if the previous visible heading is level 3 and the
3396 next is level 4 (or vice versa), level 4 will be used for insertion.
3397 This makes sure that the subtree remains an independent subtree and does
3398 not swallow low level entries.
3400 You can also force a different level, either by using a numeric prefix
3401 argument, or by inserting the heading marker by hand. For example, if the
3402 cursor is after \"*****\", then the tree will be shifted to level 5.
3404 If you want to insert the tree as is, just use \\[yank].
3406 If optional TREE is given, use this text instead of the kill ring."
3407 (interactive "P")
3408 (unless (org-kill-is-subtree-p tree)
3409 (error
3410 (substitute-command-keys
3411 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3412 (let* ((txt (or tree (current-kill 0)))
3413 (^re (concat "^\\(" outline-regexp "\\)"))
3414 (re (concat "\\(" outline-regexp "\\)"))
3415 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3417 (old-level (if (string-match ^re txt)
3418 (- (match-end 0) (match-beginning 0))
3419 -1))
3420 (force-level (cond (level (prefix-numeric-value level))
3421 ((string-match
3422 ^re_ (buffer-substring (point-at-bol) (point)))
3423 (- (match-end 0) (match-beginning 0)))
3424 (t nil)))
3425 (previous-level (save-excursion
3426 (condition-case nil
3427 (progn
3428 (outline-previous-visible-heading 1)
3429 (if (looking-at re)
3430 (- (match-end 0) (match-beginning 0))
3432 (error 1))))
3433 (next-level (save-excursion
3434 (condition-case nil
3435 (progn
3436 (outline-next-visible-heading 1)
3437 (if (looking-at re)
3438 (- (match-end 0) (match-beginning 0))
3440 (error 1))))
3441 (new-level (or force-level (max previous-level next-level)))
3442 (shift (if (or (= old-level -1)
3443 (= new-level -1)
3444 (= old-level new-level))
3446 (- new-level old-level)))
3447 (shift1 shift)
3448 (delta (if (> shift 0) -1 1))
3449 (func (if (> shift 0) 'org-demote 'org-promote))
3450 (org-odd-levels-only nil)
3451 beg end)
3452 ;; Remove the forces level indicator
3453 (if force-level
3454 (delete-region (point-at-bol) (point)))
3455 ;; Make sure we start at the beginning of an empty line
3456 (if (not (bolp)) (insert "\n"))
3457 (if (not (looking-at "[ \t]*$"))
3458 (progn (insert "\n") (backward-char 1)))
3459 ;; Paste
3460 (setq beg (point))
3461 (insert txt)
3462 (setq end (point))
3463 (goto-char beg)
3464 ;; Shift if necessary
3465 (if (= shift 0)
3466 (message "Pasted at level %d, without shift" new-level)
3467 (save-restriction
3468 (narrow-to-region beg end)
3469 (while (not (= shift 0))
3470 (org-map-region func (point-min) (point-max))
3471 (setq shift (+ delta shift)))
3472 (goto-char (point-min))
3473 (message "Pasted at level %d, with shift by %d levels"
3474 new-level shift1)))
3475 (if (and (eq org-subtree-clip (current-kill 0))
3476 org-subtree-clip-folded)
3477 ;; The tree was folded before it was killed/copied
3478 (hide-subtree))))
3480 (defun org-kill-is-subtree-p (&optional txt)
3481 "Check if the current kill is an outline subtree, or a set of trees.
3482 Returns nil if kill does not start with a headline, or if the first
3483 headline level is not the largest headline level in the tree.
3484 So this will actually accept several entries of equal levels as well,
3485 which is OK for `org-paste-subtree'.
3486 If optional TXT is given, check this string instead of the current kill."
3487 (let* ((kill (or txt (current-kill 0) ""))
3488 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3489 (- (match-end 0) (match-beginning 0))))
3490 (re (concat "^" outline-regexp))
3491 (start 1))
3492 (if (not start-level)
3493 nil ;; does not even start with a heading
3494 (catch 'exit
3495 (while (setq start (string-match re kill (1+ start)))
3496 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3497 (throw 'exit nil)))
3498 t))))
3500 ;;; Plain list items
3502 (defun org-at-item-p ()
3503 "Is point in a line starting a hand-formatted item?"
3504 (let ((llt org-plain-list-ordered-item-terminator))
3505 (save-excursion
3506 (goto-char (point-at-bol))
3507 (looking-at
3508 (cond
3509 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3510 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3511 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3512 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3514 (defun org-get-indentation ()
3515 "Get the indentation of the current line, interpreting tabs."
3516 (save-excursion
3517 (beginning-of-line 1)
3518 (skip-chars-forward " \t")
3519 (current-column)))
3521 (defun org-beginning-of-item ()
3522 "Go to the beginning of the current hand-formatted item.
3523 If the cursor is not in an item, throw an error."
3524 (let ((pos (point))
3525 (limit (save-excursion (org-back-to-heading)
3526 (beginning-of-line 2) (point)))
3527 ind ind1)
3528 (if (org-at-item-p)
3529 (beginning-of-line 1)
3530 (beginning-of-line 1)
3531 (skip-chars-forward " \t")
3532 (setq ind (current-column))
3533 (if (catch 'exit
3534 (while t
3535 (beginning-of-line 0)
3536 (if (< (point) limit) (throw 'exit nil))
3537 (unless (looking-at " \t]*$")
3538 (skip-chars-forward " \t")
3539 (setq ind1 (current-column))
3540 (if (< ind1 ind)
3541 (throw 'exit (org-at-item-p))))))
3543 (goto-char pos)
3544 (error "Not in an item")))))
3546 (defun org-end-of-item ()
3547 "Go to the end of the current hand-formatted item.
3548 If the cursor is not in an item, throw an error."
3549 (let ((pos (point))
3550 (limit (save-excursion (outline-next-heading) (point)))
3551 (ind (save-excursion
3552 (org-beginning-of-item)
3553 (skip-chars-forward " \t")
3554 (current-column)))
3555 ind1)
3556 (if (catch 'exit
3557 (while t
3558 (beginning-of-line 2)
3559 (if (>= (point) limit) (throw 'exit t))
3560 (unless (looking-at "[ \t]*$")
3561 (skip-chars-forward " \t")
3562 (setq ind1 (current-column))
3563 (if (<= ind1 ind) (throw 'exit t)))))
3564 (beginning-of-line 1)
3565 (goto-char pos)
3566 (error "Not in an item"))))
3568 (defun org-move-item-down (arg)
3569 "Move the plain list item at point down, i.e. swap with following item.
3570 Subitems (items with larger indentation) are considered part of the item,
3571 so this really moves item trees."
3572 (interactive "p")
3573 (let (beg end ind ind1 (pos (point)) txt)
3574 (org-beginning-of-item)
3575 (setq beg (point))
3576 (setq ind (org-get-indentation))
3577 (org-end-of-item)
3578 (setq end (point))
3579 (setq ind1 (org-get-indentation))
3580 (if (and (org-at-item-p) (= ind ind1))
3581 (progn
3582 (org-end-of-item)
3583 (setq txt (buffer-substring beg end))
3584 (save-excursion
3585 (delete-region beg end))
3586 (setq pos (point))
3587 (insert txt)
3588 (goto-char pos)
3589 (org-maybe-renumber-ordered-list))
3590 (goto-char pos)
3591 (error "Cannot move this item further down"))))
3593 (defun org-move-item-up (arg)
3594 "Move the plain list item at point up, i.e. swap with previous item.
3595 Subitems (items with larger indentation) are considered part of the item,
3596 so this really moves item trees."
3597 (interactive "p")
3598 (let (beg end ind ind1 (pos (point)) txt)
3599 (org-beginning-of-item)
3600 (setq beg (point))
3601 (setq ind (org-get-indentation))
3602 (org-end-of-item)
3603 (setq end (point))
3604 (goto-char beg)
3605 (catch 'exit
3606 (while t
3607 (beginning-of-line 0)
3608 (if (looking-at "[ \t]*$")
3610 (if (<= (setq ind1 (org-get-indentation)) ind)
3611 (throw 'exit t)))))
3612 (condition-case nil
3613 (org-beginning-of-item)
3614 (error (goto-char beg)
3615 (error "Cannot move this item further up")))
3616 (setq ind1 (org-get-indentation))
3617 (if (and (org-at-item-p) (= ind ind1))
3618 (progn
3619 (setq txt (buffer-substring beg end))
3620 (save-excursion
3621 (delete-region beg end))
3622 (setq pos (point))
3623 (insert txt)
3624 (goto-char pos)
3625 (org-maybe-renumber-ordered-list))
3626 (goto-char pos)
3627 (error "Cannot move this item further up"))))
3629 (defun org-maybe-renumber-ordered-list ()
3630 "Renumber the ordered list at point if setup allows it.
3631 This tests the user option `org-auto-renumber-ordered-lists' before
3632 doing the renumbering."
3633 (and org-auto-renumber-ordered-lists
3634 (org-at-item-p)
3635 (match-beginning 3)
3636 (org-renumber-ordered-list 1)))
3638 (defun org-get-string-indentation (s)
3639 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3640 (let ((n -1) (i 0) (w tab-width) c)
3641 (catch 'exit
3642 (while (< (setq n (1+ n)) (length s))
3643 (setq c (aref s n))
3644 (cond ((= c ?\ ) (setq i (1+ i)))
3645 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3646 (t (throw 'exit t)))))
3649 (defun org-renumber-ordered-list (arg)
3650 "Renumber an ordered plain list.
3651 Cursor next to be in the first line of an item, the line that starts
3652 with something like \"1.\" or \"2)\"."
3653 (interactive "p")
3654 (unless (and (org-at-item-p)
3655 (match-beginning 3))
3656 (error "This is not an ordered list"))
3657 (let ((line (org-current-line))
3658 (col (current-column))
3659 (ind (org-get-string-indentation
3660 (buffer-substring (point-at-bol) (match-beginning 3))))
3661 ;; (term (substring (match-string 3) -1))
3662 ind1 (n (1- arg)))
3663 ;; find where this list begins
3664 (catch 'exit
3665 (while t
3666 (catch 'next
3667 (beginning-of-line 0)
3668 (if (looking-at "[ \t]*$") (throw 'next t))
3669 (skip-chars-forward " \t") (setq ind1 (current-column))
3670 (if (or (< ind1 ind)
3671 (and (= ind1 ind)
3672 (not (org-at-item-p))))
3673 (throw 'exit t)))))
3674 ;; Walk forward and replace these numbers
3675 (catch 'exit
3676 (while t
3677 (catch 'next
3678 (beginning-of-line 2)
3679 (if (eobp) (throw 'exit nil))
3680 (if (looking-at "[ \t]*$") (throw 'next nil))
3681 (skip-chars-forward " \t") (setq ind1 (current-column))
3682 (if (> ind1 ind) (throw 'next t))
3683 (if (< ind1 ind) (throw 'exit t))
3684 (if (not (org-at-item-p)) (throw 'exit nil))
3685 (if (not (match-beginning 3))
3686 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3687 (delete-region (match-beginning 3) (1- (match-end 3)))
3688 (goto-char (match-beginning 3))
3689 (insert (format "%d" (setq n (1+ n)))))))
3690 (goto-line line)
3691 (move-to-column col)))
3693 (defvar org-last-indent-begin-marker (make-marker))
3694 (defvar org-last-indent-end-marker (make-marker))
3696 (defun org-outdent-item (arg)
3697 "Outdent a local list item."
3698 (interactive "p")
3699 (org-indent-item (- arg)))
3701 (defun org-indent-item (arg)
3702 "Indent a local list item."
3703 (interactive "p")
3704 (unless (org-at-item-p)
3705 (error "Not on an item"))
3706 (let (beg end ind ind1)
3707 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3708 (setq beg org-last-indent-begin-marker
3709 end org-last-indent-end-marker)
3710 (org-beginning-of-item)
3711 (setq beg (move-marker org-last-indent-begin-marker (point)))
3712 (org-end-of-item)
3713 (setq end (move-marker org-last-indent-end-marker (point))))
3714 (goto-char beg)
3715 (skip-chars-forward " \t") (setq ind (current-column))
3716 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3717 (while (< (point) end)
3718 (beginning-of-line 1)
3719 (skip-chars-forward " \t") (setq ind1 (current-column))
3720 (delete-region (point-at-bol) (point))
3721 (indent-to-column (+ ind1 arg))
3722 (beginning-of-line 2))
3723 (goto-char beg)))
3725 ;;; Archiving
3727 (defun org-archive-subtree ()
3728 "Move the current subtree to the archive.
3729 The archive can be a certain top-level heading in the current file, or in
3730 a different file. The tree will be moved to that location, the subtree
3731 heading be marked DONE, and the current time will be added."
3732 (interactive)
3733 ;; Save all relevant TODO keyword-relatex variables
3734 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3735 (tr-org-todo-keywords org-todo-keywords)
3736 (tr-org-todo-interpretation org-todo-interpretation)
3737 (tr-org-done-string org-done-string)
3738 (tr-org-todo-regexp org-todo-regexp)
3739 (tr-org-todo-line-regexp org-todo-line-regexp)
3740 (this-buffer (current-buffer))
3741 file heading buffer level newfile-p)
3742 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3743 (progn
3744 (setq file (format (match-string 1 org-archive-location)
3745 (file-name-nondirectory buffer-file-name))
3746 heading (match-string 2 org-archive-location)))
3747 (error "Invalid `org-archive-location'"))
3748 (if (> (length file) 0)
3749 (setq newfile-p (not (file-exists-p file))
3750 buffer (find-file-noselect file))
3751 (setq buffer (current-buffer)))
3752 (unless buffer
3753 (error "Cannot access file \"%s\"" file))
3754 (if (and (> (length heading) 0)
3755 (string-match "^\\*+" heading))
3756 (setq level (match-end 0))
3757 (setq heading nil level 0))
3758 (save-excursion
3759 ;; We first only copy, in case something goes wrong
3760 ;; we need to protect this-command, to avoid kill-region sets it,
3761 ;; which would lead to duplication of subtrees
3762 (let (this-command) (org-copy-subtree))
3763 (set-buffer buffer)
3764 ;; Enforce org-mode for the archive buffer
3765 (if (not (eq major-mode 'org-mode))
3766 ;; Force the mode for future visits.
3767 (let ((org-insert-mode-line-in-empty-file t))
3768 (call-interactively 'org-mode)))
3769 (when newfile-p
3770 (goto-char (point-max))
3771 (insert (format "\nArchived entries from file %s\n\n"
3772 (buffer-file-name this-buffer))))
3773 ;; Force the TODO keywords of the original buffer
3774 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3775 (org-todo-keywords tr-org-todo-keywords)
3776 (org-todo-interpretation tr-org-todo-interpretation)
3777 (org-done-string tr-org-done-string)
3778 (org-todo-regexp tr-org-todo-regexp)
3779 (org-todo-line-regexp tr-org-todo-line-regexp))
3780 (goto-char (point-min))
3781 (if heading
3782 (progn
3783 (if (re-search-forward
3784 (concat "\\(^\\|\r\\)"
3785 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3786 nil t)
3787 (goto-char (match-end 0))
3788 ;; Heading not found, just insert it at the end
3789 (goto-char (point-max))
3790 (or (bolp) (insert "\n"))
3791 (insert "\n" heading "\n")
3792 (end-of-line 0))
3793 ;; Make the heading visible, and the following as well
3794 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3795 (if (re-search-forward
3796 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3797 nil t)
3798 (progn (goto-char (match-beginning 0)) (insert "\n")
3799 (beginning-of-line 0))
3800 (goto-char (point-max)) (insert "\n")))
3801 (goto-char (point-max)) (insert "\n"))
3802 ;; Paste
3803 (org-paste-subtree (1+ level))
3804 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3805 (if org-archive-mark-done
3806 (org-todo (length org-todo-keywords)))
3807 ;; Move cursor to right after the TODO keyword
3808 (when org-archive-stamp-time
3809 (beginning-of-line 1)
3810 (looking-at org-todo-line-regexp)
3811 (goto-char (or (match-end 2) (match-beginning 3)))
3812 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3813 (org-current-time))
3814 ")"))
3815 ;; Save the buffer, if it is not the same buffer.
3816 (if (not (eq this-buffer buffer)) (save-buffer))))
3817 ;; Here we are back in the original buffer. Everything seems to have
3818 ;; worked. So now cut the tree and finish up.
3819 (let (this-command) (org-cut-subtree))
3820 (if (looking-at "[ \t]*$") (kill-line))
3821 (message "Subtree archived %s"
3822 (if (eq this-buffer buffer)
3823 (concat "under heading: " heading)
3824 (concat "in file: " (abbreviate-file-name file))))))
3826 ;;; Completion
3828 (defun org-complete (&optional arg)
3829 "Perform completion on word at point.
3830 At the beginning of a headline, this completes TODO keywords as given in
3831 `org-todo-keywords'.
3832 If the current word is preceded by a backslash, completes the TeX symbols
3833 that are supported for HTML support.
3834 If the current word is preceded by \"#+\", completes special words for
3835 setting file options.
3836 At all other locations, this simply calls `ispell-complete-word'."
3837 (interactive "P")
3838 (catch 'exit
3839 (let* ((end (point))
3840 (beg1 (save-excursion
3841 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3842 (skip-chars-backward "a-zA-Z_@0-9")
3843 (point)))
3844 (beg (save-excursion
3845 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3846 (skip-chars-backward "a-zA-Z0-9_:$")
3847 (point)))
3848 (camel (equal (char-before beg) ?*))
3849 (tag (equal (char-before beg1) ?:))
3850 (texp (equal (char-before beg) ?\\))
3851 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3852 beg)
3853 "#+"))
3854 (completion-ignore-case opt)
3855 (type nil)
3856 (tbl nil)
3857 (table (cond
3858 (opt
3859 (setq type :opt)
3860 (mapcar (lambda (x)
3861 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3862 (cons (match-string 2 x) (match-string 1 x)))
3863 (org-split-string (org-get-current-options) "\n")))
3864 (texp
3865 (setq type :tex)
3866 org-html-entities)
3867 ((string-match "\\`\\*+[ \t]*\\'"
3868 (buffer-substring (point-at-bol) beg))
3869 (setq type :todo)
3870 (mapcar 'list org-todo-keywords))
3871 (camel
3872 (setq type :camel)
3873 (save-excursion
3874 (goto-char (point-min))
3875 (while (re-search-forward org-todo-line-regexp nil t)
3876 (push (list
3877 (if org-file-link-context-use-camel-case
3878 (org-make-org-heading-camel (match-string 3) t)
3879 (org-make-org-heading-search-string
3880 (match-string 3) t)))
3881 tbl)))
3882 tbl)
3883 (tag (setq type :tag beg beg1)
3884 (org-get-buffer-tags))
3885 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3886 (pattern (buffer-substring-no-properties beg end))
3887 (completion (try-completion pattern table)))
3888 (cond ((eq completion t)
3889 (if (equal type :opt)
3890 (insert (substring (cdr (assoc (upcase pattern) table))
3891 (length pattern)))))
3892 ((null completion)
3893 (message "Can't find completion for \"%s\"" pattern)
3894 (ding))
3895 ((not (string= pattern completion))
3896 (delete-region beg end)
3897 (if (string-match " +$" completion)
3898 (setq completion (replace-match "" t t completion)))
3899 (insert completion)
3900 (if (get-buffer-window "*Completions*")
3901 (delete-window (get-buffer-window "*Completions*")))
3902 (if (assoc completion table)
3903 (if (eq type :todo) (insert " ")
3904 (if (eq type :tag) (insert ":"))))
3905 (if (and (equal type :opt) (assoc completion table))
3906 (message "%s" (substitute-command-keys
3907 "Press \\[org-complete] again to insert example settings"))))
3909 (message "Making completion list...")
3910 (let ((list (sort (all-completions pattern table) 'string<)))
3911 (with-output-to-temp-buffer "*Completions*"
3912 (condition-case nil
3913 ;; Protection needed for XEmacs and emacs 21
3914 (display-completion-list list pattern)
3915 (error (display-completion-list list)))))
3916 (message "Making completion list...%s" "done"))))))
3918 ;;; Comments, TODO and DEADLINE
3920 (defun org-toggle-comment ()
3921 "Change the COMMENT state of an entry."
3922 (interactive)
3923 (save-excursion
3924 (org-back-to-heading)
3925 (if (looking-at (concat outline-regexp
3926 "\\( +\\<" org-comment-string "\\>\\)"))
3927 (replace-match "" t t nil 1)
3928 (if (looking-at outline-regexp)
3929 (progn
3930 (goto-char (match-end 0))
3931 (insert " " org-comment-string))))))
3933 (defvar org-last-todo-state-is-todo nil
3934 "This is non-nil when the last TODO state change led to a TODO state.
3935 If the last change removed the TODO tag or switched to DONE, then
3936 this is nil.")
3938 (defun org-todo (&optional arg)
3939 "Change the TODO state of an item.
3940 The state of an item is given by a keyword at the start of the heading,
3941 like
3942 *** TODO Write paper
3943 *** DONE Call mom
3945 The different keywords are specified in the variable `org-todo-keywords'.
3946 By default the available states are \"TODO\" and \"DONE\".
3947 So for this example: when the item starts with TODO, it is changed to DONE.
3948 When it starts with DONE, the DONE is removed. And when neither TODO nor
3949 DONE are present, add TODO at the beginning of the heading.
3951 With prefix arg, use completion to determine the new state. With numeric
3952 prefix arg, switch to that state."
3953 (interactive "P")
3954 (save-excursion
3955 (org-back-to-heading)
3956 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3957 (or (looking-at (concat " +" org-todo-regexp " *"))
3958 (looking-at " *"))
3959 (let* ((this (match-string 1))
3960 (completion-ignore-case t)
3961 (member (member this org-todo-keywords))
3962 (tail (cdr member))
3963 (state (cond
3964 ((equal arg '(4))
3965 ;; Read a state with completion
3966 (completing-read "State: " (mapcar (lambda(x) (list x))
3967 org-todo-keywords)
3968 nil t))
3969 ((eq arg 'right)
3970 (if this
3971 (if tail (car tail) nil)
3972 (car org-todo-keywords)))
3973 ((eq arg 'left)
3974 (if (equal member org-todo-keywords)
3976 (if this
3977 (nth (- (length org-todo-keywords) (length tail) 2)
3978 org-todo-keywords)
3979 org-done-string)))
3980 (arg
3981 ;; user requests a specific state
3982 (nth (1- (prefix-numeric-value arg))
3983 org-todo-keywords))
3984 ((null member) (car org-todo-keywords))
3985 ((null tail) nil) ;; -> first entry
3986 ((eq org-todo-interpretation 'sequence)
3987 (car tail))
3988 ((memq org-todo-interpretation '(type priority))
3989 (if (eq this-command last-command)
3990 (car tail)
3991 (if (> (length tail) 0) org-done-string nil)))
3992 (t nil)))
3993 (next (if state (concat " " state " ") " ")))
3994 (replace-match next t t)
3995 (setq org-last-todo-state-is-todo
3996 (not (equal state org-done-string)))
3997 (when org-log-done
3998 (if (equal state org-done-string)
3999 (org-log-done)
4000 (if (not this)
4001 (org-log-done t))))
4002 ;; Fixup tag positioning
4003 (and org-auto-align-tags (org-set-tags nil t))
4004 (run-hooks 'org-after-todo-state-change-hook)))
4005 ;; Fixup cursor location if close to the keyword
4006 (if (and (outline-on-heading-p)
4007 (not (bolp))
4008 (save-excursion (beginning-of-line 1)
4009 (looking-at org-todo-line-regexp))
4010 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4011 (progn
4012 (goto-char (or (match-end 2) (match-end 1)))
4013 (just-one-space))))
4015 (defun org-log-done (&optional undone)
4016 "Add a time stamp logging that a TODO entry has been closed.
4017 When UNDONE is non-nil, remove such a time stamp again."
4018 (interactive)
4019 (let (beg end col)
4020 (save-excursion
4021 (org-back-to-heading t)
4022 (setq beg (point))
4023 (looking-at (concat outline-regexp " *"))
4024 (goto-char (match-end 0))
4025 (setq col (current-column))
4026 (outline-next-heading)
4027 (setq end (point))
4028 (goto-char beg)
4029 (when (re-search-forward (concat
4030 "[\r\n]\\([ \t]*"
4031 (regexp-quote org-closed-string)
4032 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4033 (delete-region (match-beginning 1) (match-end 1)))
4034 (unless undone
4035 (org-back-to-heading t)
4036 (skip-chars-forward "^\n\r")
4037 (goto-char (min (1+ (point)) (point-max)))
4038 (when (not (member (char-before) '(?\r ?\n)))
4039 (insert "\n"))
4040 (indent-to col)
4041 (insert org-closed-string " "
4042 (format-time-string
4043 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4044 (org-current-time))
4045 "\n")))))
4047 (defun org-show-todo-tree (arg)
4048 "Make a compact tree which shows all headlines marked with TODO.
4049 The tree will show the lines where the regexp matches, and all higher
4050 headlines above the match.
4051 With \\[universal-argument] prefix, also show the DONE entries.
4052 With a numeric prefix N, construct a sparse tree for the Nth element
4053 of `org-todo-keywords'."
4054 (interactive "P")
4055 (let ((case-fold-search nil)
4056 (kwd-re
4057 (cond ((null arg) org-not-done-regexp)
4058 ((equal arg '(4)) org-todo-regexp)
4059 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4060 (regexp-quote (nth (1- (prefix-numeric-value arg))
4061 org-todo-keywords)))
4062 (t (error "Invalid prefix argument: %s" arg)))))
4063 (message "%d TODO entries found"
4064 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4066 (defun org-deadline ()
4067 "Insert the DEADLINE: string to make a deadline.
4068 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4069 to modify it to the correct date."
4070 (interactive)
4071 (insert
4072 org-deadline-string " "
4073 (format-time-string (car org-time-stamp-formats)
4074 (org-read-date nil 'to-time)))
4075 (message "%s" (substitute-command-keys
4076 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4078 (defun org-schedule ()
4079 "Insert the SCHEDULED: string to schedule a TODO item.
4080 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4081 to modify it to the correct date."
4082 (interactive)
4083 (insert
4084 org-scheduled-string " "
4085 (format-time-string (car org-time-stamp-formats)
4086 (org-read-date nil 'to-time)))
4087 (message "%s" (substitute-command-keys
4088 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4091 (defun org-occur (regexp &optional callback)
4092 "Make a compact tree which shows all matches of REGEXP.
4093 The tree will show the lines where the regexp matches, and all higher
4094 headlines above the match. It will also show the heading after the match,
4095 to make sure editing the matching entry is easy.
4096 If CALLBACK is non-nil, it is a function which is called to confirm
4097 that the match should indeed be shown."
4098 (interactive "sRegexp: ")
4099 (org-remove-occur-highlights nil nil t)
4100 (setq regexp (org-check-occur-regexp regexp))
4101 (let ((cnt 0))
4102 (save-excursion
4103 (goto-char (point-min))
4104 (hide-sublevels 1)
4105 (while (re-search-forward regexp nil t)
4106 (when (or (not callback)
4107 (save-match-data (funcall callback)))
4108 (setq cnt (1+ cnt))
4109 (org-highlight-new-match (match-beginning 0) (match-end 0))
4110 (org-show-hierarchy-above))))
4111 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4112 nil 'local)
4113 (run-hooks 'org-occur-hook)
4114 (if (interactive-p)
4115 (message "%d match(es) for regexp %s" cnt regexp))
4116 cnt))
4118 (defun org-show-hierarchy-above ()
4119 "Make sure point and the headings hierarchy above is visible."
4120 (catch 'exit
4121 (if (org-on-heading-p t)
4122 (org-flag-heading nil) ; only show the heading
4123 (and (or (org-invisible-p) (org-invisible-p2))
4124 (org-show-hidden-entry))) ; show entire entry
4125 (save-excursion
4126 (and org-show-following-heading
4127 (outline-next-heading)
4128 (org-flag-heading nil))) ; show the next heading
4129 (when org-show-hierarchy-above
4130 (save-excursion ; show all higher headings
4131 (while (and (condition-case nil
4132 (progn (org-up-heading-all 1) t)
4133 (error nil))
4134 (not (bobp)))
4135 (org-flag-heading nil))))))
4137 ;; Overlay compatibility functions
4138 (defun org-make-overlay (beg end &optional buffer)
4139 (if (featurep 'xemacs)
4140 (make-extent beg end buffer)
4141 (make-overlay beg end buffer)))
4142 (defun org-delete-overlay (ovl)
4143 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4144 (defun org-detatch-overlay (ovl)
4145 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4146 (defun org-move-overlay (ovl beg end &optional buffer)
4147 (if (featurep 'xemacs)
4148 (set-extent-endpoints ovl beg end buffer)
4149 (move-overlay ovl beg end buffer)))
4150 (defun org-overlay-put (ovl prop value)
4151 (if (featurep 'xemacs)
4152 (set-extent-property ovl prop value)
4153 (overlay-put ovl prop value)))
4155 (defvar org-occur-highlights nil)
4156 (defun org-highlight-new-match (beg end)
4157 "Highlight from BEG to END and mark the highlight is an occur headline."
4158 (let ((ov (org-make-overlay beg end)))
4159 (org-overlay-put ov 'face 'secondary-selection)
4160 (push ov org-occur-highlights)))
4162 (defun org-remove-occur-highlights (&optional beg end noremove)
4163 "Remove the occur highlights from the buffer.
4164 BEG and END are ignored. If NOREMOVE is nil, remove this function
4165 from the `before-change-functions' in the current buffer."
4166 (interactive)
4167 (mapc 'org-delete-overlay org-occur-highlights)
4168 (setq org-occur-highlights nil)
4169 (unless noremove
4170 (remove-hook 'before-change-functions
4171 'org-remove-occur-highlights 'local)))
4173 ;;; Priorities
4175 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4176 "Regular expression matching the priority indicator.")
4178 (defvar org-remove-priority-next-time nil)
4180 (defun org-priority-up ()
4181 "Increase the priority of the current item."
4182 (interactive)
4183 (org-priority 'up))
4185 (defun org-priority-down ()
4186 "Decrease the priority of the current item."
4187 (interactive)
4188 (org-priority 'down))
4190 (defun org-priority (&optional action)
4191 "Change the priority of an item by ARG.
4192 ACTION can be set, up, or down."
4193 (interactive)
4194 (setq action (or action 'set))
4195 (let (current new news have remove)
4196 (save-excursion
4197 (org-back-to-heading)
4198 (if (looking-at org-priority-regexp)
4199 (setq current (string-to-char (match-string 2))
4200 have t)
4201 (setq current org-default-priority))
4202 (cond
4203 ((eq action 'set)
4204 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4205 (setq new (read-char-exclusive))
4206 (cond ((equal new ?\ ) (setq remove t))
4207 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4208 (error "Priority must be between `%c' and `%c'"
4209 ?A org-lowest-priority))))
4210 ((eq action 'up)
4211 (setq new (1- current)))
4212 ((eq action 'down)
4213 (setq new (1+ current)))
4214 (t (error "Invalid action")))
4215 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4216 (setq news (format "%c" new))
4217 (if have
4218 (if remove
4219 (replace-match "" t t nil 1)
4220 (replace-match news t t nil 2))
4221 (if remove
4222 (error "No priority cookie found in line")
4223 (looking-at org-todo-line-regexp)
4224 (if (match-end 2)
4225 (progn
4226 (goto-char (match-end 2))
4227 (insert " [#" news "]"))
4228 (goto-char (match-beginning 3))
4229 (insert "[#" news "] ")))))
4230 (if remove
4231 (message "Priority removed")
4232 (message "Priority of current item set to %s" news))))
4235 (defun org-get-priority (s)
4236 "Find priority cookie and return priority."
4237 (save-match-data
4238 (if (not (string-match org-priority-regexp s))
4239 (* 1000 (- org-lowest-priority org-default-priority))
4240 (* 1000 (- org-lowest-priority
4241 (string-to-char (match-string 2 s)))))))
4243 ;;; Timestamps
4245 (defvar org-last-changed-timestamp nil)
4247 (defun org-time-stamp (arg)
4248 "Prompt for a date/time and insert a time stamp.
4249 If the user specifies a time like HH:MM, or if this command is called
4250 with a prefix argument, the time stamp will contain date and time.
4251 Otherwise, only the date will be included. All parts of a date not
4252 specified by the user will be filled in from the current date/time.
4253 So if you press just return without typing anything, the time stamp
4254 will represent the current date/time. If there is already a timestamp
4255 at the cursor, it will be modified."
4256 (interactive "P")
4257 (let ((fmt (if arg (cdr org-time-stamp-formats)
4258 (car org-time-stamp-formats)))
4259 (org-time-was-given nil)
4260 time)
4261 (cond
4262 ((and (org-at-timestamp-p)
4263 (eq last-command 'org-time-stamp)
4264 (eq this-command 'org-time-stamp))
4265 (insert "--")
4266 (setq time (let ((this-command this-command))
4267 (org-read-date arg 'totime)))
4268 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4269 (insert (format-time-string fmt time)))
4270 ((org-at-timestamp-p)
4271 (setq time (let ((this-command this-command))
4272 (org-read-date arg 'totime)))
4273 (and (org-at-timestamp-p) (replace-match
4274 (setq org-last-changed-timestamp
4275 (format-time-string fmt time))
4276 t t))
4277 (message "Timestamp updated"))
4279 (setq time (let ((this-command this-command))
4280 (org-read-date arg 'totime)))
4281 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4282 (insert (format-time-string fmt time))))))
4284 (defun org-time-stamp-inactive (&optional arg)
4285 "Insert an inactive time stamp.
4286 An inactive time stamp is enclosed in square brackets instead of angle
4287 brackets. It is inactive in the sense that it does not trigger agenda entries,
4288 does not link to the calendar and cannot be changed with the S-cursor keys.
4289 So these are more for recording a certain time/date."
4290 (interactive "P")
4291 (let ((fmt (if arg (cdr org-time-stamp-formats)
4292 (car org-time-stamp-formats)))
4293 (org-time-was-given nil)
4294 time)
4295 (setq time (org-read-date arg 'totime))
4296 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4297 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4298 (insert (format-time-string fmt time))))
4300 (defvar org-date-ovl (org-make-overlay 1 1))
4301 (org-overlay-put org-date-ovl 'face 'org-warning)
4302 (org-detatch-overlay org-date-ovl)
4304 (defun org-read-date (&optional with-time to-time)
4305 "Read a date and make things smooth for the user.
4306 The prompt will suggest to enter an ISO date, but you can also enter anything
4307 which will at least partially be understood by `parse-time-string'.
4308 Unrecognized parts of the date will default to the current day, month, year,
4309 hour and minute. For example,
4310 3-2-5 --> 2003-02-05
4311 feb 15 --> currentyear-02-15
4312 sep 12 9 --> 2009-09-12
4313 12:45 --> today 12:45
4314 22 sept 0:34 --> currentyear-09-22 0:34
4315 12 --> currentyear-currentmonth-12
4316 Fri --> nearest Friday (today or later)
4317 etc.
4318 The function understands only English month and weekday abbreviations,
4319 but this can be configured with the variables `parse-time-months' and
4320 `parse-time-weekdays'.
4322 While prompting, a calendar is popped up - you can also select the
4323 date with the mouse (button 1). The calendar shows a period of three
4324 months. To scroll it to other months, use the keys `>' and `<'.
4325 If you don't like the calendar, turn it off with
4326 \(setq org-popup-calendar-for-date-prompt nil)
4328 With optional argument TO-TIME, the date will immediately be converted
4329 to an internal time.
4330 With an optional argument WITH-TIME, the prompt will suggest to also
4331 insert a time. Note that when WITH-TIME is not set, you can still
4332 enter a time, and this function will inform the calling routine about
4333 this change. The calling routine may then choose to change the format
4334 used to insert the time stamp into the buffer to include the time."
4335 (require 'parse-time)
4336 (let* ((org-time-stamp-rounding-minutes
4337 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4338 (ct (org-current-time))
4339 (default-time
4340 ;; Default time is either today, or, when entering a range,
4341 ;; the range start.
4342 (if (save-excursion
4343 (re-search-backward
4344 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4345 (- (point) 20) t))
4346 (apply
4347 'encode-time
4348 (mapcar (lambda(x) (or x 0))
4349 (parse-time-string (match-string 1))))
4350 ct))
4351 (calendar-move-hook nil)
4352 (view-diary-entries-initially nil)
4353 (timestr (format-time-string
4354 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4355 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4356 ans ans1 ans2
4357 second minute hour day month year tl wday wday1)
4359 (if org-popup-calendar-for-date-prompt
4360 (save-excursion
4361 (save-window-excursion
4362 (calendar)
4363 (calendar-forward-day (- (time-to-days default-time)
4364 (calendar-absolute-from-gregorian
4365 (calendar-current-date))))
4366 (org-eval-in-calendar nil)
4367 (let* ((old-map (current-local-map))
4368 (map (copy-keymap calendar-mode-map))
4369 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4370 (define-key map (kbd "RET") 'org-calendar-select)
4371 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4372 'org-calendar-select-mouse)
4373 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4374 'org-calendar-select-mouse)
4375 (define-key minibuffer-local-map [(meta shift left)]
4376 (lambda () (interactive)
4377 (org-eval-in-calendar '(calendar-backward-month 1))))
4378 (define-key minibuffer-local-map [(meta shift right)]
4379 (lambda () (interactive)
4380 (org-eval-in-calendar '(calendar-forward-month 1))))
4381 (define-key minibuffer-local-map [(shift up)]
4382 (lambda () (interactive)
4383 (org-eval-in-calendar '(calendar-backward-week 1))))
4384 (define-key minibuffer-local-map [(shift down)]
4385 (lambda () (interactive)
4386 (org-eval-in-calendar '(calendar-forward-week 1))))
4387 (define-key minibuffer-local-map [(shift left)]
4388 (lambda () (interactive)
4389 (org-eval-in-calendar '(calendar-backward-day 1))))
4390 (define-key minibuffer-local-map [(shift right)]
4391 (lambda () (interactive)
4392 (org-eval-in-calendar '(calendar-forward-day 1))))
4393 (define-key minibuffer-local-map ">"
4394 (lambda () (interactive)
4395 (org-eval-in-calendar '(scroll-calendar-left 1))))
4396 (define-key minibuffer-local-map "<"
4397 (lambda () (interactive)
4398 (org-eval-in-calendar '(scroll-calendar-right 1))))
4399 (unwind-protect
4400 (progn
4401 (use-local-map map)
4402 (setq ans (read-string prompt "" nil nil))
4403 (if (not (string-match "\\S-" ans)) (setq ans nil))
4404 (setq ans (or ans1 ans ans2)))
4405 (use-local-map old-map)))))
4406 ;; Naked prompt only
4407 (setq ans (read-string prompt "" nil timestr)))
4408 (org-detatch-overlay org-date-ovl)
4410 (if (string-match
4411 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4412 (progn
4413 (setq year (if (match-end 2)
4414 (string-to-number (match-string 2 ans))
4415 (string-to-number (format-time-string "%Y")))
4416 month (string-to-number (match-string 3 ans))
4417 day (string-to-number (match-string 4 ans)))
4418 (if (< year 100) (setq year (+ 2000 year)))
4419 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4420 t nil ans))))
4421 (setq tl (parse-time-string ans)
4422 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4423 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4424 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4425 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4426 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4427 second (or (nth 0 tl) 0)
4428 wday (nth 6 tl))
4429 (when (and wday (not (nth 3 tl)))
4430 ;; Weekday was given, but no day, so pick that day in the week
4431 ;; on or after the derived date.
4432 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4433 (unless (equal wday wday1)
4434 (setq day (+ day (% (- wday wday1 -7) 7)))))
4435 (if (and (boundp 'org-time-was-given)
4436 (nth 2 tl))
4437 (setq org-time-was-given t))
4438 (if (< year 100) (setq year (+ 2000 year)))
4439 (if to-time
4440 (encode-time second minute hour day month year)
4441 (if (or (nth 1 tl) (nth 2 tl))
4442 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4443 (format "%04d-%02d-%02d" year month day)))))
4445 (defun org-eval-in-calendar (form)
4446 "Eval FORM in the calendar window and return to current window.
4447 Also, store the cursor date in variable ans2."
4448 (let ((sw (selected-window)))
4449 (select-window (get-buffer-window "*Calendar*"))
4450 (eval form)
4451 (when (calendar-cursor-to-date)
4452 (let* ((date (calendar-cursor-to-date))
4453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4454 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4455 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4456 (select-window sw)))
4458 (defun org-calendar-select ()
4459 "Return to `org-read-date' with the date currently selected.
4460 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4461 (interactive)
4462 (when (calendar-cursor-to-date)
4463 (let* ((date (calendar-cursor-to-date))
4464 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4465 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4466 (if (active-minibuffer-window) (exit-minibuffer))))
4468 (defun org-calendar-select-mouse (ev)
4469 "Return to `org-read-date' with the date currently selected.
4470 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4471 (interactive "e")
4472 (mouse-set-point ev)
4473 (when (calendar-cursor-to-date)
4474 (let* ((date (calendar-cursor-to-date))
4475 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4476 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4477 (if (active-minibuffer-window) (exit-minibuffer))))
4479 (defun org-check-deadlines (ndays)
4480 "Check if there are any deadlines due or past due.
4481 A deadline is considered due if it happens within `org-deadline-warning-days'
4482 days from today's date. If the deadline appears in an entry marked DONE,
4483 it is not shown. The prefix arg NDAYS can be used to test that many
4484 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4485 (interactive "P")
4486 (let* ((org-warn-days
4487 (cond
4488 ((equal ndays '(4)) 100000)
4489 (ndays (prefix-numeric-value ndays))
4490 (t org-deadline-warning-days)))
4491 (case-fold-search nil)
4492 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4493 (callback
4494 (lambda ()
4495 (and (let ((d1 (time-to-days (current-time)))
4496 (d2 (time-to-days
4497 (org-time-string-to-time (match-string 1)))))
4498 (< (- d2 d1) org-warn-days))
4499 (not (org-entry-is-done-p))))))
4500 (message "%d deadlines past-due or due within %d days"
4501 (org-occur regexp callback)
4502 org-warn-days)))
4504 (defun org-evaluate-time-range (&optional to-buffer)
4505 "Evaluate a time range by computing the difference between start and end.
4506 Normally the result is just printed in the echo area, but with prefix arg
4507 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4508 If the time range is actually in a table, the result is inserted into the
4509 next column.
4510 For time difference computation, a year is assumed to be exactly 365
4511 days in order to avoid rounding problems."
4512 (interactive "P")
4513 (save-excursion
4514 (unless (org-at-date-range-p)
4515 (goto-char (point-at-bol))
4516 (re-search-forward org-tr-regexp (point-at-eol) t))
4517 (if (not (org-at-date-range-p))
4518 (error "Not at a time-stamp range, and none found in current line")))
4519 (let* ((ts1 (match-string 1))
4520 (ts2 (match-string 2))
4521 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4522 (match-end (match-end 0))
4523 (time1 (org-time-string-to-time ts1))
4524 (time2 (org-time-string-to-time ts2))
4525 (t1 (time-to-seconds time1))
4526 (t2 (time-to-seconds time2))
4527 (diff (abs (- t2 t1)))
4528 (negative (< (- t2 t1) 0))
4529 ;; (ys (floor (* 365 24 60 60)))
4530 (ds (* 24 60 60))
4531 (hs (* 60 60))
4532 (fy "%dy %dd %02d:%02d")
4533 (fy1 "%dy %dd")
4534 (fd "%dd %02d:%02d")
4535 (fd1 "%dd")
4536 (fh "%02d:%02d")
4537 y d h m align)
4538 (if havetime
4539 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4541 d (floor (/ diff ds)) diff (mod diff ds)
4542 h (floor (/ diff hs)) diff (mod diff hs)
4543 m (floor (/ diff 60)))
4544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4546 d (floor (+ (/ diff ds) 0.5))
4547 h 0 m 0))
4548 (if (not to-buffer)
4549 (message (org-make-tdiff-string y d h m))
4550 (when (org-at-table-p)
4551 (goto-char match-end)
4552 (setq align t)
4553 (and (looking-at " *|") (goto-char (match-end 0))))
4554 (if (looking-at
4555 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4556 (replace-match ""))
4557 (if negative (insert " -"))
4558 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4559 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4560 (insert " " (format fh h m))))
4561 (if align (org-table-align))
4562 (message "Time difference inserted"))))
4564 (defun org-make-tdiff-string (y d h m)
4565 (let ((fmt "")
4566 (l nil))
4567 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4568 l (push y l)))
4569 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4570 l (push d l)))
4571 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4572 l (push h l)))
4573 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4574 l (push m l)))
4575 (apply 'format fmt (nreverse l))))
4577 (defun org-time-string-to-time (s)
4578 (apply 'encode-time (org-parse-time-string s)))
4580 (defun org-parse-time-string (s &optional nodefault)
4581 "Parse the standard Org-mode time string.
4582 This should be a lot faster than the normal `parse-time-string'.
4583 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4584 hour and minute fields will be nil if not given."
4585 (if (string-match org-ts-regexp1 s)
4586 (list 0
4587 (if (or (match-beginning 8) (not nodefault))
4588 (string-to-number (or (match-string 8 s) "0")))
4589 (if (or (match-beginning 7) (not nodefault))
4590 (string-to-number (or (match-string 7 s) "0")))
4591 (string-to-number (match-string 4 s))
4592 (string-to-number (match-string 3 s))
4593 (string-to-number (match-string 2 s))
4594 nil nil nil)
4595 (make-list 9 0)))
4597 (defun org-timestamp-up (&optional arg)
4598 "Increase the date item at the cursor by one.
4599 If the cursor is on the year, change the year. If it is on the month or
4600 the day, change that.
4601 With prefix ARG, change by that many units."
4602 (interactive "p")
4603 (org-timestamp-change (prefix-numeric-value arg)))
4605 (defun org-timestamp-down (&optional arg)
4606 "Decrease the date item at the cursor by one.
4607 If the cursor is on the year, change the year. If it is on the month or
4608 the day, change that.
4609 With prefix ARG, change by that many units."
4610 (interactive "p")
4611 (org-timestamp-change (- (prefix-numeric-value arg))))
4613 (defun org-timestamp-up-day (&optional arg)
4614 "Increase the date in the time stamp by one day.
4615 With prefix ARG, change that many days."
4616 (interactive "p")
4617 (if (and (not (org-at-timestamp-p))
4618 (org-on-heading-p))
4619 (org-todo 'up)
4620 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4622 (defun org-timestamp-down-day (&optional arg)
4623 "Decrease the date in the time stamp by one day.
4624 With prefix ARG, change that many days."
4625 (interactive "p")
4626 (if (and (not (org-at-timestamp-p))
4627 (org-on-heading-p))
4628 (org-todo 'down)
4629 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4631 (defsubst org-pos-in-match-range (pos n)
4632 (and (match-beginning n)
4633 (<= (match-beginning n) pos)
4634 (>= (match-end n) pos)))
4636 (defun org-at-timestamp-p ()
4637 "Determine if the cursor is in or at a timestamp."
4638 (interactive)
4639 (let* ((tsr org-ts-regexp2)
4640 (pos (point))
4641 (ans (or (looking-at tsr)
4642 (save-excursion
4643 (skip-chars-backward "^<\n\r\t")
4644 (if (> (point) 1) (backward-char 1))
4645 (and (looking-at tsr)
4646 (> (- (match-end 0) pos) -1))))))
4647 (and (boundp 'org-ts-what)
4648 (setq org-ts-what
4649 (cond
4650 ((org-pos-in-match-range pos 2) 'year)
4651 ((org-pos-in-match-range pos 3) 'month)
4652 ((org-pos-in-match-range pos 7) 'hour)
4653 ((org-pos-in-match-range pos 8) 'minute)
4654 ((or (org-pos-in-match-range pos 4)
4655 (org-pos-in-match-range pos 5)) 'day)
4656 (t 'day))))
4657 ans))
4659 (defun org-timestamp-change (n &optional what)
4660 "Change the date in the time stamp at point.
4661 The date will be changed by N times WHAT. WHAT can be `day', `month',
4662 `year', `minute', `second'. If WHAT is not given, the cursor position
4663 in the timestamp determines what will be changed."
4664 (let ((fmt (car org-time-stamp-formats))
4665 org-ts-what
4666 (pos (point))
4667 ts time time0)
4668 (if (not (org-at-timestamp-p))
4669 (error "Not at a timestamp"))
4670 (setq org-ts-what (or what org-ts-what))
4671 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4672 (- (match-end 0) (match-beginning 0))))
4674 (cdr org-time-stamp-formats)
4675 (car org-time-stamp-formats)))
4676 (setq ts (match-string 0))
4677 (replace-match "")
4678 (setq time0 (org-parse-time-string ts))
4679 (setq time
4680 (apply 'encode-time
4681 (append
4682 (list (or (car time0) 0))
4683 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4684 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4685 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4686 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4687 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4688 (nthcdr 6 time0))))
4689 (if (eq what 'calendar)
4690 (let ((cal-date
4691 (save-excursion
4692 (save-match-data
4693 (set-buffer "*Calendar*")
4694 (calendar-cursor-to-date)))))
4695 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4696 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4697 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4698 (setcar time0 (or (car time0) 0))
4699 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4700 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4701 (setq time (apply 'encode-time time0))))
4702 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4703 (goto-char pos)
4704 ;; Try to recenter the calendar window, if any
4705 (if (and org-calendar-follow-timestamp-change
4706 (get-buffer-window "*Calendar*" t)
4707 (memq org-ts-what '(day month year)))
4708 (org-recenter-calendar (time-to-days time)))))
4710 (defun org-recenter-calendar (date)
4711 "If the calendar is visible, recenter it to DATE."
4712 (let* ((win (selected-window))
4713 (cwin (get-buffer-window "*Calendar*" t))
4714 (calendar-move-hook nil))
4715 (when cwin
4716 (select-window cwin)
4717 (calendar-goto-date (if (listp date) date
4718 (calendar-gregorian-from-absolute date)))
4719 (select-window win))))
4721 (defun org-goto-calendar (&optional arg)
4722 "Go to the Emacs calendar at the current date.
4723 If there is a time stamp in the current line, go to that date.
4724 A prefix ARG can be used to force the current date."
4725 (interactive "P")
4726 (let ((tsr org-ts-regexp) diff
4727 (calendar-move-hook nil)
4728 (view-diary-entries-initially nil))
4729 (if (or (org-at-timestamp-p)
4730 (save-excursion
4731 (beginning-of-line 1)
4732 (looking-at (concat ".*" tsr))))
4733 (let ((d1 (time-to-days (current-time)))
4734 (d2 (time-to-days
4735 (org-time-string-to-time (match-string 1)))))
4736 (setq diff (- d2 d1))))
4737 (calendar)
4738 (calendar-goto-today)
4739 (if (and diff (not arg)) (calendar-forward-day diff))))
4741 (defun org-date-from-calendar ()
4742 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4743 If there is already a time stamp at the cursor position, update it."
4744 (interactive)
4745 (org-timestamp-change 0 'calendar))
4747 ;;; Agenda, and Diary Integration
4749 ;;; Define the mode
4751 (defvar org-agenda-mode-map (make-sparse-keymap)
4752 "Keymap for `org-agenda-mode'.")
4754 (defvar org-agenda-menu) ; defined later in this file.
4755 (defvar org-agenda-follow-mode nil)
4756 (defvar org-agenda-show-log nil)
4757 (defvar org-agenda-buffer-name "*Org Agenda*")
4758 (defvar org-agenda-redo-command nil)
4759 (defvar org-agenda-mode-hook nil)
4760 (defvar org-agenda-type nil)
4761 (defvar org-agenda-force-single-file nil)
4763 ;;;###autoload
4764 (defun org-agenda-mode ()
4765 "Mode for time-sorted view on action items in Org-mode files.
4767 The following commands are available:
4769 \\{org-agenda-mode-map}"
4770 (interactive)
4771 (kill-all-local-variables)
4772 (setq major-mode 'org-agenda-mode)
4773 (setq mode-name "Org-Agenda")
4774 (use-local-map org-agenda-mode-map)
4775 (easy-menu-add org-agenda-menu)
4776 (if org-startup-truncated (setq truncate-lines t))
4777 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4778 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4779 (unless org-agenda-keep-modes
4780 (setq org-agenda-follow-mode nil
4781 org-agenda-show-log nil))
4782 (easy-menu-change
4783 '("Agenda") "Agenda Files"
4784 (append
4785 (list
4786 (vector
4787 (if (get 'org-agenda-files 'org-restrict)
4788 "Restricted to single file"
4789 "Edit File List")
4790 '(org-edit-agenda-file-list)
4791 (not (get 'org-agenda-files 'org-restrict)))
4792 "--")
4793 (mapcar 'org-file-menu-entry (org-agenda-files))))
4794 (org-agenda-set-mode-name)
4795 (apply
4796 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4797 (list 'org-agenda-mode-hook)))
4799 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4800 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4801 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4802 (define-key org-agenda-mode-map " " 'org-agenda-show)
4803 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4804 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4805 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4806 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4807 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4808 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4809 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4810 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4811 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4812 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4813 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4814 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4816 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4817 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4818 (while l (define-key org-agenda-mode-map
4819 (int-to-string (pop l)) 'digit-argument)))
4821 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4822 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4823 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4824 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4825 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4826 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4827 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4828 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4829 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4830 (define-key org-agenda-mode-map "n" 'next-line)
4831 (define-key org-agenda-mode-map "p" 'previous-line)
4832 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4833 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4834 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4835 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4836 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4837 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4838 (eval-after-load "calendar"
4839 '(define-key calendar-mode-map org-calendar-to-agenda-key
4840 'org-calendar-goto-agenda))
4841 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4842 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4843 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4844 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4845 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4846 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4847 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4848 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4849 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4850 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4851 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4852 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4853 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4854 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4855 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4856 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4857 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4858 "Local keymap for agenda entries from Org-mode.")
4860 (define-key org-agenda-keymap
4861 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4862 (define-key org-agenda-keymap
4863 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4864 (when org-agenda-mouse-1-follows-link
4865 (define-key org-agenda-keymap [follow-link] 'mouse-face))
4866 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4867 '("Agenda"
4868 ("Agenda Files")
4869 "--"
4870 ["Show" org-agenda-show t]
4871 ["Go To (other window)" org-agenda-goto t]
4872 ["Go To (one window)" org-agenda-switch-to t]
4873 ["Follow Mode" org-agenda-follow-mode
4874 :style toggle :selected org-agenda-follow-mode :active t]
4875 "--"
4876 ["Cycle TODO" org-agenda-todo t]
4877 ("Tags"
4878 ["Show all Tags" org-agenda-show-tags t]
4879 ["Set Tags" org-agenda-set-tags t])
4880 ("Reschedule"
4881 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4882 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4883 "--"
4884 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4885 ("Priority"
4886 ["Set Priority" org-agenda-priority t]
4887 ["Increase Priority" org-agenda-priority-up t]
4888 ["Decrease Priority" org-agenda-priority-down t]
4889 ["Show Priority" org-agenda-show-priority t])
4890 "--"
4891 ;; ["New agenda command" org-agenda t]
4892 ["Rebuild buffer" org-agenda-redo t]
4893 "--"
4894 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4895 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4896 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4897 "--"
4898 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4899 :style radio :selected (equal org-agenda-ndays 1)]
4900 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4901 :style radio :selected (equal org-agenda-ndays 7)]
4902 "--"
4903 ["Show Logbook entries" org-agenda-log-mode
4904 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4905 ["Include Diary" org-agenda-toggle-diary
4906 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4907 ["Use Time Grid" org-agenda-toggle-time-grid
4908 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4909 "--"
4910 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4911 ("Calendar Commands"
4912 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4913 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4914 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4915 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4916 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4917 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4918 "--"
4919 ["Quit" org-agenda-quit t]
4920 ["Exit and Release Buffers" org-agenda-exit t]
4923 ;;;###autoload
4924 (defun org-agenda (arg)
4925 "Dispatch agenda commands to collect entries to the agenda buffer.
4926 Prompts for a character to select a command. Any prefix arg will be passed
4927 on to the selected command. The default selections are:
4929 a Call `org-agenda' to display the agenda for the current day or week.
4930 t Call `org-todo-list' to display the global todo list.
4931 T Call `org-todo-list' to display the global todo list, select only
4932 entries with a specific TODO keyword (the user gets a prompt).
4933 m Call `org-tags-view' to display headlines with tags matching
4934 a condition (the user is prompted for the condition).
4935 M Like `m', but select only TODO entries, no ordinary headlines.
4937 More commands can be added by configuring the variable
4938 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4939 searches can be pre-defined in this way.
4941 If the current buffer is in Org-mode and visiting a file, you can also
4942 first press `1' to indicate that the agenda should be temporarily (until the
4943 next use of \\[org-agenda]) restricted to the current file."
4944 (interactive "P")
4945 (catch 'exit
4946 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4947 (custom org-agenda-custom-commands)
4948 c entry key type string)
4949 (put 'org-agenda-files 'org-restrict nil)
4950 (save-window-excursion
4951 (delete-other-windows)
4952 (switch-to-buffer-other-window " *Agenda Commands*")
4953 (erase-buffer)
4954 (insert
4955 "Press key for an agenda command:
4956 --------------------------------
4957 a Agenda for current week or day
4958 t List of all TODO entries T Entries with special TODO kwd
4959 m Match a TAGS query M Like m, but only TODO entries
4960 C Configure your own agenda commands")
4961 (while (setq entry (pop custom))
4962 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4963 (insert (format "\n%-4s%-14s: %s"
4965 (cond
4966 ((eq type 'tags) "Tags query")
4967 ((eq type 'todo) "TODO keyword")
4968 ((eq type 'tags-tree) "Tags tree")
4969 ((eq type 'todo-tree) "TODO kwd tree")
4970 ((eq type 'occur-tree) "Occur tree")
4971 (t "???"))
4972 (org-add-props string nil 'face 'org-warning))))
4973 (goto-char (point-min))
4974 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4975 (message "Press key for agenda command%s"
4976 (if restrict-ok ", or [1] to restrict to current file" ""))
4977 (setq c (read-char-exclusive))
4978 (message "")
4979 (when (equal c ?1)
4980 (if restrict-ok
4981 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4982 (error "Cannot restrict agenda to current buffer"))
4983 (message "Press key for agenda command%s"
4984 (if restrict-ok " (restricted to current file)" ""))
4985 (setq c (read-char-exclusive))
4986 (message "")))
4987 (require 'calendar) ; FIXME: can we avoid this for some commands?
4988 ;; For example the todo list should not need it (but does...)
4989 (cond
4990 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4991 ((equal c ?a) (call-interactively 'org-agenda-list))
4992 ((equal c ?t) (call-interactively 'org-todo-list))
4993 ((equal c ?T)
4994 (setq current-prefix-arg (or arg '(4)))
4995 (call-interactively 'org-todo-list))
4996 ((equal c ?m) (call-interactively 'org-tags-view))
4997 ((equal c ?M)
4998 (setq current-prefix-arg (or arg '(4)))
4999 (call-interactively 'org-tags-view))
5000 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5001 (setq type (nth 1 entry) string (nth 2 entry))
5002 (cond
5003 ((eq type 'tags)
5004 (org-tags-view current-prefix-arg string))
5005 ((eq type 'todo)
5006 (org-todo-list string))
5007 ((eq type 'tags-tree)
5008 (org-check-for-org-mode)
5009 (org-tags-sparse-tree current-prefix-arg string))
5010 ((eq type 'todo-tree)
5011 (org-check-for-org-mode)
5012 (org-occur (concat "^" outline-regexp "[ \t]*"
5013 (regexp-quote string) "\\>")))
5014 ((eq type 'occur-tree)
5015 (org-check-for-org-mode)
5016 (org-occur string))
5017 (t (error "Invalid custom agenda command type %s" type))))
5018 (t (error "Invalid key"))))))
5020 (defun org-check-for-org-mode ()
5021 "Make sure current buffer is in org-mode. Error if not."
5022 (or (eq major-mode 'org-mode)
5023 (error "Cannot execute org-mode agenda command on buffer in %s."
5024 major-mode)))
5026 (defun org-fit-agenda-window ()
5027 "Fit the window to the buffer size."
5028 (and org-fit-agenda-window
5029 (fboundp 'fit-window-to-buffer)
5030 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5031 (/ (frame-height) 2))))
5033 (defun org-agenda-files (&optional unrestricted)
5034 "Get the list of agenda files.
5035 Optional UNRESTRICTED means return the full list even if a restriction
5036 is currently in place."
5037 (cond
5038 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5039 ((stringp org-agenda-files) (org-read-agenda-file-list))
5040 ((listp org-agenda-files) org-agenda-files)
5041 (t (error "Invalid value of `org-agenda-files'"))))
5043 (defvar org-window-configuration)
5045 (defun org-edit-agenda-file-list ()
5046 "Edit the list of agenda files.
5047 Depending on setup, this either uses customize to edit the variable
5048 `org-agenda-files', or it visits the file that is holding the list. In the
5049 latter case, the buffer is set up in a way that saving it automatically kills
5050 the buffer and restores the previous window configuration."
5051 (interactive)
5052 (if (stringp org-agenda-files)
5053 (let ((cw (current-window-configuration)))
5054 (find-file org-agenda-files)
5055 (set (make-local-variable 'org-window-configuration) cw)
5056 (org-add-hook 'after-save-hook
5057 (lambda ()
5058 (set-window-configuration
5059 (prog1 org-window-configuration
5060 (kill-buffer (current-buffer))))
5061 (org-install-agenda-files-menu)
5062 (message "New agenda file list installed"))
5063 nil 'local)
5064 (message (substitute-command-keys
5065 "Edit list and finish with \\[save-buffer]")))
5066 (customize-variable 'org-agenda-files)))
5068 (defun org-store-new-agenda-file-list (list)
5069 "Set new value for the agenda file list and save it correcly."
5070 (if (stringp org-agenda-files)
5071 (let ((f org-agenda-files) b)
5072 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5073 (with-temp-file f
5074 (insert (mapconcat 'identity list "\n") "\n")))
5075 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5076 (setq org-agenda-files list)
5077 (customize-save-variable 'org-agenda-files org-agenda-files))))
5079 (defun org-read-agenda-file-list ()
5080 "Read the list of agenda files from a file."
5081 (when (stringp org-agenda-files)
5082 (with-temp-buffer
5083 (insert-file-contents org-agenda-files)
5084 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5086 (defvar org-agenda-markers nil
5087 "List of all currently active markers created by `org-agenda'.")
5088 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5089 "Creation time of the last agenda marker.")
5091 (defun org-agenda-new-marker (&optional pos)
5092 "Return a new agenda marker.
5093 Org-mode keeps a list of these markers and resets them when they are
5094 no longer in use."
5095 (let ((m (copy-marker (or pos (point)))))
5096 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5097 (push m org-agenda-markers)
5100 (defun org-agenda-maybe-reset-markers (&optional force)
5101 "Reset markers created by `org-agenda'. But only if they are old enough."
5102 (if (or force
5103 (> (- (time-to-seconds (current-time))
5104 org-agenda-last-marker-time)
5106 (while org-agenda-markers
5107 (move-marker (pop org-agenda-markers) nil))))
5109 (defvar org-agenda-new-buffers nil
5110 "Buffers created to visit agenda files.")
5112 (defun org-get-agenda-file-buffer (file)
5113 "Get a buffer visiting FILE. If the buffer needs to be created, add
5114 it to the list of buffers which might be released later."
5115 (let ((buf (find-buffer-visiting file)))
5116 (if buf
5117 buf ; just return it
5118 ;; Make a new buffer and remember it
5119 (setq buf (find-file-noselect file))
5120 (if buf (push buf org-agenda-new-buffers))
5121 buf)))
5123 (defun org-release-buffers (blist)
5124 "Release all buffers in list, asking the user for confirmation when needed.
5125 When a buffer is unmodified, it is just killed. When modified, it is saved
5126 \(if the user agrees) and then killed."
5127 (let (buf file)
5128 (while (setq buf (pop blist))
5129 (setq file (buffer-file-name buf))
5130 (when (and (buffer-modified-p buf)
5131 file
5132 (y-or-n-p (format "Save file %s? " file)))
5133 (with-current-buffer buf (save-buffer)))
5134 (kill-buffer buf))))
5136 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5138 (defun org-timeline (&optional include-all keep-modes)
5139 "Show a time-sorted view of the entries in the current org file.
5140 Only entries with a time stamp of today or later will be listed. With
5141 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5142 under the current date.
5143 If the buffer contains an active region, only check the region for
5144 dates."
5145 (interactive "P")
5146 (require 'calendar)
5147 (org-agenda-maybe-reset-markers 'force)
5148 (org-compile-prefix-format org-timeline-prefix-format)
5149 (let* ((dopast t)
5150 (dotodo include-all)
5151 (doclosed org-agenda-show-log)
5152 (org-agenda-keep-modes keep-modes)
5153 (entry buffer-file-name)
5154 (org-agenda-files (list buffer-file-name))
5155 (date (calendar-current-date))
5156 (win (selected-window))
5157 (pos1 (point))
5158 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5159 (end (if (org-region-active-p) (region-end) (point-max)))
5160 (day-numbers (org-get-all-dates beg end 'no-ranges
5161 t doclosed)) ; always include today
5162 (today (time-to-days (current-time)))
5163 (org-respect-restriction t)
5164 (past t)
5165 args
5166 s e rtn d)
5167 (setq org-agenda-redo-command
5168 (list 'progn
5169 (list 'switch-to-buffer-other-window (current-buffer))
5170 (list 'org-timeline (list 'quote include-all) t)))
5171 (if (not dopast)
5172 ;; Remove past dates from the list of dates.
5173 (setq day-numbers (delq nil (mapcar (lambda(x)
5174 (if (>= x today) x nil))
5175 day-numbers))))
5176 (switch-to-buffer-other-window
5177 (get-buffer-create org-agenda-buffer-name))
5178 (setq buffer-read-only nil)
5179 (erase-buffer)
5180 (org-agenda-mode) (setq buffer-read-only nil)
5181 (set (make-local-variable 'org-agenda-type) 'timeline)
5182 (if doclosed (push :closed args))
5183 (push :timestamp args)
5184 (if dotodo (push :todo args))
5185 (while (setq d (pop day-numbers))
5186 (if (and (>= d today)
5187 dopast
5188 past)
5189 (progn
5190 (setq past nil)
5191 (insert (make-string 79 ?-) "\n")))
5192 (setq date (calendar-gregorian-from-absolute d))
5193 (setq s (point))
5194 (setq rtn (apply 'org-agenda-get-day-entries
5195 entry date args))
5196 (if (or rtn (equal d today))
5197 (progn
5198 (insert (calendar-day-name date) " "
5199 (number-to-string (extract-calendar-day date)) " "
5200 (calendar-month-name (extract-calendar-month date)) " "
5201 (number-to-string (extract-calendar-year date)) "\n")
5202 (put-text-property s (1- (point)) 'face
5203 'org-level-3)
5204 (if (equal d today)
5205 (put-text-property s (1- (point)) 'org-today t))
5206 (insert (org-finalize-agenda-entries rtn) "\n")
5207 (put-text-property s (1- (point)) 'day d))))
5208 (goto-char (point-min))
5209 (setq buffer-read-only t)
5210 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5211 (point-min)))
5212 (when (not org-select-timeline-window)
5213 (select-window win)
5214 (goto-char pos1))))
5216 ;;;###autoload
5217 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5218 "Produce a weekly view from all files in variable `org-agenda-files'.
5219 The view will be for the current week, but from the overview buffer you
5220 will be able to go to other weeks.
5221 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5222 also be shown, under the current date.
5223 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5224 on the days are also shown. See the variable `org-log-done' for how
5225 to turn on logging.
5226 START-DAY defaults to TODAY, or to the most recent match for the weekday
5227 given in `org-agenda-start-on-weekday'.
5228 NDAYS defaults to `org-agenda-ndays'."
5229 (interactive "P")
5230 (org-agenda-maybe-reset-markers 'force)
5231 (org-compile-prefix-format org-agenda-prefix-format)
5232 (require 'calendar)
5233 (let* ((org-agenda-start-on-weekday
5234 (if (or (equal ndays 1)
5235 (and (null ndays) (equal 1 org-agenda-ndays)))
5236 nil org-agenda-start-on-weekday))
5237 (org-agenda-keep-modes keep-modes)
5238 (thefiles (org-agenda-files))
5239 (files thefiles)
5240 (win (selected-window))
5241 (today (time-to-days (current-time)))
5242 (sd (or start-day today))
5243 (start (if (or (null org-agenda-start-on-weekday)
5244 (< org-agenda-ndays 7))
5246 (let* ((nt (calendar-day-of-week
5247 (calendar-gregorian-from-absolute sd)))
5248 (n1 org-agenda-start-on-weekday)
5249 (d (- nt n1)))
5250 (- sd (+ (if (< d 0) 7 0) d)))))
5251 (day-numbers (list start))
5252 (inhibit-redisplay t)
5253 s e rtn rtnall file date d start-pos end-pos todayp nd)
5254 (setq org-agenda-redo-command
5255 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5256 ;; Make the list of days
5257 (setq ndays (or ndays org-agenda-ndays)
5258 nd ndays)
5259 (while (> ndays 1)
5260 (push (1+ (car day-numbers)) day-numbers)
5261 (setq ndays (1- ndays)))
5262 (setq day-numbers (nreverse day-numbers))
5263 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5264 (progn
5265 (delete-other-windows)
5266 (switch-to-buffer-other-window
5267 (get-buffer-create org-agenda-buffer-name))))
5268 (setq buffer-read-only nil)
5269 (erase-buffer)
5270 (org-agenda-mode) (setq buffer-read-only nil)
5271 (set (make-local-variable 'org-agenda-type) 'agenda)
5272 (set (make-local-variable 'starting-day) (car day-numbers))
5273 (set (make-local-variable 'include-all-loc) include-all)
5274 (when (and (or include-all org-agenda-include-all-todo)
5275 (member today day-numbers))
5276 (setq files thefiles
5277 rtnall nil)
5278 (while (setq file (pop files))
5279 (catch 'nextfile
5280 (org-check-agenda-file file)
5281 (setq date (calendar-gregorian-from-absolute today)
5282 rtn (org-agenda-get-day-entries
5283 file date :todo))
5284 (setq rtnall (append rtnall rtn))))
5285 (when rtnall
5286 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5287 (add-text-properties (point-min) (1- (point))
5288 (list 'face 'org-level-3))
5289 (insert (org-finalize-agenda-entries rtnall) "\n")))
5290 (while (setq d (pop day-numbers))
5291 (setq date (calendar-gregorian-from-absolute d)
5292 s (point))
5293 (if (or (setq todayp (= d today))
5294 (and (not start-pos) (= d sd)))
5295 (setq start-pos (point))
5296 (if (and start-pos (not end-pos))
5297 (setq end-pos (point))))
5298 (setq files thefiles
5299 rtnall nil)
5300 (while (setq file (pop files))
5301 (catch 'nextfile
5302 (org-check-agenda-file file)
5303 (if org-agenda-show-log
5304 (setq rtn (org-agenda-get-day-entries
5305 file date
5306 :deadline :scheduled :timestamp :closed))
5307 (setq rtn (org-agenda-get-day-entries
5308 file date
5309 :deadline :scheduled :timestamp)))
5310 (setq rtnall (append rtnall rtn))))
5311 (if org-agenda-include-diary
5312 (progn
5313 (require 'diary-lib)
5314 (setq rtn (org-get-entries-from-diary date))
5315 (setq rtnall (append rtnall rtn))))
5316 (if (or rtnall org-agenda-show-all-dates)
5317 (progn
5318 (insert (format "%-9s %2d %s %4d\n"
5319 (calendar-day-name date)
5320 (extract-calendar-day date)
5321 (calendar-month-name (extract-calendar-month date))
5322 (extract-calendar-year date)))
5323 (put-text-property s (1- (point)) 'face
5324 'org-level-3)
5325 (if rtnall (insert
5326 (org-finalize-agenda-entries
5327 (org-agenda-add-time-grid-maybe
5328 rtnall nd todayp))
5329 "\n"))
5330 (put-text-property s (1- (point)) 'day d))))
5331 (goto-char (point-min))
5332 (setq buffer-read-only t)
5333 (org-fit-agenda-window)
5334 (unless (and (pos-visible-in-window-p (point-min))
5335 (pos-visible-in-window-p (point-max)))
5336 (goto-char (1- (point-max)))
5337 (recenter -1)
5338 (if (not (pos-visible-in-window-p (or start-pos 1)))
5339 (progn
5340 (goto-char (or start-pos 1))
5341 (recenter 1))))
5342 (goto-char (or start-pos 1))
5343 (if (not org-select-agenda-window) (select-window win))
5344 (message "")))
5346 (defvar org-select-this-todo-keyword nil)
5348 ;;;###autoload
5349 (defun org-todo-list (arg &optional keep-modes)
5350 "Show all TODO entries from all agenda file in a single list.
5351 The prefix arg can be used to select a specific TODO keyword and limit
5352 the list to these. When using \\[universal-argument], you will be prompted
5353 for a keyword. A numeric prefix directly selects the Nth keyword in
5354 `org-todo-keywords'."
5355 (interactive "P")
5356 (org-agenda-maybe-reset-markers 'force)
5357 (org-compile-prefix-format org-agenda-prefix-format)
5358 (let* ((org-agenda-keep-modes keep-modes)
5359 (today (time-to-days (current-time)))
5360 (date (calendar-gregorian-from-absolute today))
5361 (win (selected-window))
5362 (kwds org-todo-keywords)
5363 (completion-ignore-case t)
5364 (org-select-this-todo-keyword
5365 (if (stringp arg) arg
5366 (and arg (integerp arg) (> arg 0)
5367 (nth (1- arg) org-todo-keywords))))
5368 rtn rtnall files file pos)
5369 (when (equal arg '(4))
5370 (setq org-select-this-todo-keyword
5371 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5372 nil t)))
5373 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5374 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5375 (progn
5376 (delete-other-windows)
5377 (switch-to-buffer-other-window
5378 (get-buffer-create org-agenda-buffer-name))))
5379 (setq buffer-read-only nil)
5380 (erase-buffer)
5381 (org-agenda-mode) (setq buffer-read-only nil)
5382 (set (make-local-variable 'org-agenda-type) 'todo)
5383 (set (make-local-variable 'last-arg) arg)
5384 (set (make-local-variable 'org-todo-keywords) kwds)
5385 (set (make-local-variable 'org-agenda-redo-command)
5386 '(org-todo-list (or current-prefix-arg last-arg) t))
5387 (setq files (org-agenda-files)
5388 rtnall nil)
5389 (while (setq file (pop files))
5390 (catch 'nextfile
5391 (org-check-agenda-file file)
5392 (setq rtn (org-agenda-get-day-entries file date :todo))
5393 (setq rtnall (append rtnall rtn))))
5394 (insert "Global list of TODO items of type: ")
5395 (add-text-properties (point-min) (1- (point))
5396 (list 'face 'org-level-3))
5397 (setq pos (point))
5398 (insert (or org-select-this-todo-keyword "ALL") "\n")
5399 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5400 (setq pos (point))
5401 (insert
5402 "Available with `N r': (0)ALL "
5403 (let ((n 0))
5404 (mapconcat (lambda (x)
5405 (format "(%d)%s" (setq n (1+ n)) x))
5406 org-todo-keywords " "))
5407 "\n")
5408 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5409 (when rtnall
5410 (insert (org-finalize-agenda-entries rtnall) "\n"))
5411 (goto-char (point-min))
5412 (setq buffer-read-only t)
5413 (org-fit-agenda-window)
5414 (if (not org-select-agenda-window) (select-window win))))
5416 (defun org-check-agenda-file (file)
5417 "Make sure FILE exists. If not, ask user what to do."
5418 (when (not (file-exists-p file))
5419 (message "non-existent file %s. [R]emove from list or [A]bort?"
5420 (abbreviate-file-name file))
5421 (let ((r (downcase (read-char-exclusive))))
5422 (cond
5423 ((equal r ?r)
5424 (org-remove-file file)
5425 (throw 'nextfile t))
5426 (t (error "Abort"))))))
5428 (defun org-agenda-check-type (error &rest types)
5429 "Check if agenda buffer is of allowed type.
5430 If ERROR is non-nil, throw an error, otherwise just return nil."
5431 (if (memq org-agenda-type types)
5433 (if error
5434 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5435 nil)))
5437 (defun org-agenda-quit ()
5438 "Exit agenda by removing the window or the buffer."
5439 (interactive)
5440 (let ((buf (current-buffer)))
5441 (if (not (one-window-p)) (delete-window))
5442 (kill-buffer buf)
5443 (org-agenda-maybe-reset-markers 'force)))
5445 (defun org-agenda-exit ()
5446 "Exit agenda by removing the window or the buffer.
5447 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5448 Org-mode buffers visited directly by the user will not be touched."
5449 (interactive)
5450 (org-release-buffers org-agenda-new-buffers)
5451 (setq org-agenda-new-buffers nil)
5452 (org-agenda-quit))
5454 (defun org-agenda-redo ()
5455 "Rebuild Agenda.
5456 When this is the global TODO list, a prefix argument will be interpreted."
5457 (interactive)
5458 (message "Rebuilding agenda buffer...")
5459 (eval org-agenda-redo-command)
5460 (message "Rebuilding agenda buffer...done"))
5462 (defun org-agenda-goto-today ()
5463 "Go to today."
5464 (interactive)
5465 (org-agenda-check-type t 'timeline 'agenda)
5466 (if (boundp 'starting-day)
5467 (let ((cmd (car org-agenda-redo-command))
5468 (iall (nth 1 org-agenda-redo-command))
5469 (nday (nth 3 org-agenda-redo-command))
5470 (keep (nth 4 org-agenda-redo-command)))
5471 (eval (list cmd iall nil nday keep)))
5472 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5473 (point-min)))))
5475 (defun org-agenda-later (arg)
5476 "Go forward in time by `org-agenda-ndays' days.
5477 With prefix ARG, go forward that many times `org-agenda-ndays'."
5478 (interactive "p")
5479 (org-agenda-check-type t 'agenda)
5480 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5481 (+ starting-day (* arg org-agenda-ndays)) nil t))
5483 (defun org-agenda-earlier (arg)
5484 "Go back in time by `org-agenda-ndays' days.
5485 With prefix ARG, go back that many times `org-agenda-ndays'."
5486 (interactive "p")
5487 (org-agenda-check-type t 'agenda)
5488 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5489 (- starting-day (* arg org-agenda-ndays)) nil t))
5491 (defun org-agenda-week-view ()
5492 "Switch to weekly view for agenda."
5493 (interactive)
5494 (org-agenda-check-type t 'agenda)
5495 (setq org-agenda-ndays 7)
5496 (org-agenda-list include-all-loc
5497 (or (get-text-property (point) 'day)
5498 starting-day)
5499 nil t)
5500 (org-agenda-set-mode-name)
5501 (message "Switched to week view"))
5503 (defun org-agenda-day-view ()
5504 "Switch to daily view for agenda."
5505 (interactive)
5506 (org-agenda-check-type t 'agenda)
5507 (setq org-agenda-ndays 1)
5508 (org-agenda-list include-all-loc
5509 (or (get-text-property (point) 'day)
5510 starting-day)
5511 nil t)
5512 (org-agenda-set-mode-name)
5513 (message "Switched to day view"))
5515 (defun org-agenda-next-date-line (&optional arg)
5516 "Jump to the next line indicating a date in agenda buffer."
5517 (interactive "p")
5518 (org-agenda-check-type t 'agenda 'timeline)
5519 (beginning-of-line 1)
5520 (if (looking-at "^\\S-") (forward-char 1))
5521 (if (not (re-search-forward "^\\S-" nil t arg))
5522 (progn
5523 (backward-char 1)
5524 (error "No next date after this line in this buffer")))
5525 (goto-char (match-beginning 0)))
5527 (defun org-agenda-previous-date-line (&optional arg)
5528 "Jump to the previous line indicating a date in agenda buffer."
5529 (interactive "p")
5530 (org-agenda-check-type t 'agenda 'timeline)
5531 (beginning-of-line 1)
5532 (if (not (re-search-backward "^\\S-" nil t arg))
5533 (error "No previous date before this line in this buffer")))
5535 ;; Initialize the highlight
5536 (defvar org-hl (org-make-overlay 1 1))
5537 (org-overlay-put org-hl 'face 'highlight)
5539 (defun org-highlight (begin end &optional buffer)
5540 "Highlight a region with overlay."
5541 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5542 org-hl begin end (or buffer (current-buffer))))
5544 (defun org-unhighlight ()
5545 "Detach overlay INDEX."
5546 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5549 (defun org-agenda-follow-mode ()
5550 "Toggle follow mode in an agenda buffer."
5551 (interactive)
5552 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5553 (org-agenda-set-mode-name)
5554 (message "Follow mode is %s"
5555 (if org-agenda-follow-mode "on" "off")))
5557 (defun org-agenda-log-mode ()
5558 "Toggle log mode in an agenda buffer."
5559 (interactive)
5560 (org-agenda-check-type t 'agenda 'timeline)
5561 (setq org-agenda-show-log (not org-agenda-show-log))
5562 (org-agenda-set-mode-name)
5563 (org-agenda-redo)
5564 (message "Log mode is %s"
5565 (if org-agenda-show-log "on" "off")))
5567 (defun org-agenda-toggle-diary ()
5568 "Toggle diary inclusion in an agenda buffer."
5569 (interactive)
5570 (org-agenda-check-type t 'agenda)
5571 (setq org-agenda-include-diary (not org-agenda-include-diary))
5572 (org-agenda-redo)
5573 (org-agenda-set-mode-name)
5574 (message "Diary inclusion turned %s"
5575 (if org-agenda-include-diary "on" "off")))
5577 (defun org-agenda-toggle-time-grid ()
5578 "Toggle time grid in an agenda buffer."
5579 (interactive)
5580 (org-agenda-check-type t 'agenda)
5581 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5582 (org-agenda-redo)
5583 (org-agenda-set-mode-name)
5584 (message "Time-grid turned %s"
5585 (if org-agenda-use-time-grid "on" "off")))
5587 (defun org-agenda-set-mode-name ()
5588 "Set the mode name to indicate all the small mode settings."
5589 (setq mode-name
5590 (concat "Org-Agenda"
5591 (if (equal org-agenda-ndays 1) " Day" "")
5592 (if (equal org-agenda-ndays 7) " Week" "")
5593 (if org-agenda-follow-mode " Follow" "")
5594 (if org-agenda-include-diary " Diary" "")
5595 (if org-agenda-use-time-grid " Grid" "")
5596 (if org-agenda-show-log " Log" "")))
5597 (force-mode-line-update))
5599 (defun org-agenda-post-command-hook ()
5600 (and (eolp) (not (bolp)) (backward-char 1))
5601 (if (and org-agenda-follow-mode
5602 (get-text-property (point) 'org-marker))
5603 (org-agenda-show)))
5605 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5607 (defun org-get-entries-from-diary (date)
5608 "Get the (Emacs Calendar) diary entries for DATE."
5609 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5610 (diary-display-hook '(fancy-diary-display))
5611 (list-diary-entries-hook
5612 (cons 'org-diary-default-entry list-diary-entries-hook))
5613 (diary-file-name-prefix-function nil) ; turn this feature off
5614 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5615 entries
5616 (org-disable-agenda-to-diary t))
5617 (save-excursion
5618 (save-window-excursion
5619 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5620 (if (not (get-buffer fancy-diary-buffer))
5621 (setq entries nil)
5622 (with-current-buffer fancy-diary-buffer
5623 (setq buffer-read-only nil)
5624 (if (= (point-max) 1)
5625 ;; No entries
5626 (setq entries nil)
5627 ;; Omit the date and other unnecessary stuff
5628 (org-agenda-cleanup-fancy-diary)
5629 ;; Add prefix to each line and extend the text properties
5630 (if (= (point-max) 1)
5631 (setq entries nil)
5632 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5633 (set-buffer-modified-p nil)
5634 (kill-buffer fancy-diary-buffer)))
5635 (when entries
5636 (setq entries (org-split-string entries "\n"))
5637 (setq entries
5638 (mapcar
5639 (lambda (x)
5640 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5641 ;; Extend the text properties to the beginning of the line
5642 (org-add-props x (text-properties-at (1- (length x)) x)))
5643 entries)))))
5645 (defun org-agenda-cleanup-fancy-diary ()
5646 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5647 This gets rid of the date, the underline under the date, and
5648 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5649 date. It also removes lines that contain only whitespace."
5650 (goto-char (point-min))
5651 (if (looking-at ".*?:[ \t]*")
5652 (progn
5653 (replace-match "")
5654 (re-search-forward "\n=+$" nil t)
5655 (replace-match "")
5656 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5657 (re-search-forward "\n=+$" nil t)
5658 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5659 (goto-char (point-min))
5660 (while (re-search-forward "^ +\n" nil t)
5661 (replace-match ""))
5662 (goto-char (point-min))
5663 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5664 (replace-match "")))
5666 ;; Make sure entries from the diary have the right text properties.
5667 (eval-after-load "diary-lib"
5668 '(if (boundp 'diary-modify-entry-list-string-function)
5669 ;; We can rely on the hook, nothing to do
5671 ;; Hook not avaiable, must use advice to make this work
5672 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5673 "Make the position visible."
5674 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5675 (stringp string)
5676 buffer-file-name)
5677 (setq string (org-modify-diary-entry-string string))))))
5679 (defun org-modify-diary-entry-string (string)
5680 "Add text properties to string, allowing org-mode to act on it."
5681 (org-add-props string nil
5682 'mouse-face 'highlight
5683 'keymap org-agenda-keymap
5684 'help-echo (format "mouse-2 or RET jump to diary file %s"
5685 (abbreviate-file-name buffer-file-name))
5686 'org-agenda-diary-link t
5687 'org-marker (org-agenda-new-marker (point-at-bol))))
5689 (defun org-diary-default-entry ()
5690 "Add a dummy entry to the diary.
5691 Needed to avoid empty dates which mess up holiday display."
5692 ;; Catch the error if dealing with the new add-to-diary-alist
5693 (when org-disable-agenda-to-diary
5694 (condition-case nil
5695 (add-to-diary-list original-date "Org-mode dummy" "")
5696 (error
5697 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5699 (defun org-cycle-agenda-files ()
5700 "Cycle through the files in `org-agenda-files'.
5701 If the current buffer visits an agenda file, find the next one in the list.
5702 If the current buffer does not, find the first agenda file."
5703 (interactive)
5704 (let* ((fs (org-agenda-files t))
5705 (files (append fs (list (car fs))))
5706 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5707 file)
5708 (unless files (error "No agenda files"))
5709 (catch 'exit
5710 (while (setq file (pop files))
5711 (if (equal (file-truename file) tcf)
5712 (when (car files)
5713 (find-file (car files))
5714 (throw 'exit t))))
5715 (find-file (car fs)))))
5717 (defun org-agenda-file-to-end ()
5718 "Move/add the current file to the end of the agenda file list.
5719 If the file is not present in the list, it is appended to the list. If it is
5720 present, it is moved there."
5721 (interactive)
5722 (org-agenda-file-to-front 'to-end))
5724 (defun org-agenda-file-to-front (&optional to-end)
5725 "Move/add the current file to the top of the agenda file list.
5726 If the file is not present in the list, it is added to the front. If it is
5727 present, it is moved there. With optional argument TO-END, add/move to the
5728 end of the list."
5729 (interactive "P")
5730 (let ((file-alist (mapcar (lambda (x)
5731 (cons (file-truename x) x))
5732 (org-agenda-files t)))
5733 (ctf (file-truename buffer-file-name))
5734 x had)
5735 (setq x (assoc ctf file-alist) had x)
5737 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5738 (if to-end
5739 (setq file-alist (append (delq x file-alist) (list x)))
5740 (setq file-alist (cons x (delq x file-alist))))
5741 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5742 (org-install-agenda-files-menu)
5743 (message "File %s to %s of agenda file list"
5744 (if had "moved" "added") (if to-end "end" "front"))))
5746 (defun org-remove-file (&optional file)
5747 "Remove current file from the list of files in variable `org-agenda-files'.
5748 These are the files which are being checked for agenda entries.
5749 Optional argument FILE means, use this file instead of the current."
5750 (interactive)
5751 (let* ((file (or file buffer-file-name))
5752 (true-file (file-truename file))
5753 (afile (abbreviate-file-name file))
5754 (files (delq nil (mapcar
5755 (lambda (x)
5756 (if (equal true-file
5757 (file-truename x))
5758 nil x))
5759 (org-agenda-files t)))))
5760 (if (not (= (length files) (length (org-agenda-files t))))
5761 (progn
5762 (org-store-new-agenda-file-list files)
5763 (org-install-agenda-files-menu)
5764 (message "Removed file: %s" afile))
5765 (message "File was not in list: %s" afile))))
5767 (defun org-file-menu-entry (file)
5768 (vector file (list 'find-file file) t))
5770 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5771 "Return a list of all relevant day numbers from BEG to END buffer positions.
5772 If NO-RANGES is non-nil, include only the start and end dates of a range,
5773 not every single day in the range. If FORCE-TODAY is non-nil, make
5774 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5775 inactive time stamps (those in square brackets) are included."
5776 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5777 dates date day day1 day2 ts1 ts2)
5778 (if force-today
5779 (setq dates (list (time-to-days (current-time)))))
5780 (save-excursion
5781 (goto-char beg)
5782 (while (re-search-forward re end t)
5783 (setq day (time-to-days (org-time-string-to-time
5784 (substring (match-string 1) 0 10))))
5785 (or (memq day dates) (push day dates)))
5786 (unless no-ranges
5787 (goto-char beg)
5788 (while (re-search-forward org-tr-regexp end t)
5789 (setq ts1 (substring (match-string 1) 0 10)
5790 ts2 (substring (match-string 2) 0 10)
5791 day1 (time-to-days (org-time-string-to-time ts1))
5792 day2 (time-to-days (org-time-string-to-time ts2)))
5793 (while (< (setq day1 (1+ day1)) day2)
5794 (or (memq day1 dates) (push day1 dates)))))
5795 (sort dates '<))))
5797 ;;;###autoload
5798 (defun org-diary (&rest args)
5799 "Return diary information from org-files.
5800 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5801 It accesses org files and extracts information from those files to be
5802 listed in the diary. The function accepts arguments specifying what
5803 items should be listed. The following arguments are allowed:
5805 :timestamp List the headlines of items containing a date stamp or
5806 date range matching the selected date. Deadlines will
5807 also be listed, on the expiration day.
5809 :deadline List any deadlines past due, or due within
5810 `org-deadline-warning-days'. The listing occurs only
5811 in the diary for *today*, not at any other date. If
5812 an entry is marked DONE, it is no longer listed.
5814 :scheduled List all items which are scheduled for the given date.
5815 The diary for *today* also contains items which were
5816 scheduled earlier and are not yet marked DONE.
5818 :todo List all TODO items from the org-file. This may be a
5819 long list - so this is not turned on by default.
5820 Like deadlines, these entries only show up in the
5821 diary for *today*, not at any other date.
5823 The call in the diary file should look like this:
5825 &%%(org-diary) ~/path/to/some/orgfile.org
5827 Use a separate line for each org file to check. Or, if you omit the file name,
5828 all files listed in `org-agenda-files' will be checked automatically:
5830 &%%(org-diary)
5832 If you don't give any arguments (as in the example above), the default
5833 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5834 also be written as
5836 &%%(org-diary :deadline :timestamp :scheduled)
5838 The function expects the lisp variables `entry' and `date' to be provided
5839 by the caller, because this is how the calendar works. Don't use this
5840 function from a program - use `org-agenda-get-day-entries' instead."
5841 (org-agenda-maybe-reset-markers)
5842 (org-compile-prefix-format org-agenda-prefix-format)
5843 (setq args (or args '(:deadline :scheduled :timestamp)))
5844 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5845 (list entry)
5846 (org-agenda-files t)))
5847 file rtn results)
5848 ;; If this is called during org-agenda, don't return any entries to
5849 ;; the calendar. Org Agenda will list these entries itself.
5850 (if org-disable-agenda-to-diary (setq files nil))
5851 (while (setq file (pop files))
5852 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5853 (setq results (append results rtn)))
5854 (if results
5855 (concat (org-finalize-agenda-entries results) "\n"))))
5856 (defvar org-category-table nil)
5857 (defun org-get-category-table ()
5858 "Get the table of categories and positions in current buffer."
5859 (let (tbl)
5860 (save-excursion
5861 (goto-char (point-min))
5862 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5863 (push (cons (point) (org-trim (match-string 2))) tbl)))
5864 tbl))
5865 (defun org-get-category (&optional pos)
5866 "Get the category applying to position POS."
5867 (if (not org-category-table)
5868 (cond
5869 ((null org-category)
5870 (setq org-category
5871 (if buffer-file-name
5872 (file-name-sans-extension
5873 (file-name-nondirectory buffer-file-name))
5874 "???")))
5875 ((symbolp org-category) (symbol-name org-category))
5876 (t org-category))
5877 (let ((tbl org-category-table)
5878 (pos (or pos (point))))
5879 (while (and tbl (> (caar tbl) pos))
5880 (pop tbl))
5881 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5882 org-category-table))))))
5884 (defun org-agenda-get-day-entries (file date &rest args)
5885 "Does the work for `org-diary' and `org-agenda'.
5886 FILE is the path to a file to be checked for entries. DATE is date like
5887 the one returned by `calendar-current-date'. ARGS are symbols indicating
5888 which kind of entries should be extracted. For details about these, see
5889 the documentation of `org-diary'."
5890 (setq args (or args '(:deadline :scheduled :timestamp)))
5891 (let* ((org-startup-with-deadline-check nil)
5892 (org-startup-folded nil)
5893 (org-startup-align-all-tables nil)
5894 (buffer (if (file-exists-p file)
5895 (org-get-agenda-file-buffer file)
5896 (error "No such file %s" file)))
5897 arg results rtn)
5898 (if (not buffer)
5899 ;; If file does not exist, make sure an error message ends up in diary
5900 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5901 (with-current-buffer buffer
5902 (unless (eq major-mode 'org-mode)
5903 (error "Agenda file %s is not in `org-mode'" file))
5904 (setq org-category-table (org-get-category-table))
5905 (let ((case-fold-search nil))
5906 (save-excursion
5907 (save-restriction
5908 (if org-respect-restriction
5909 (if (org-region-active-p)
5910 ;; Respect a region to restrict search
5911 (narrow-to-region (region-beginning) (region-end)))
5912 ;; If we work for the calendar or many files,
5913 ;; get rid of any restriction
5914 (widen))
5915 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5916 (while (setq arg (pop args))
5917 (cond
5918 ((and (eq arg :todo)
5919 (equal date (calendar-current-date)))
5920 (setq rtn (org-agenda-get-todos))
5921 (setq results (append results rtn)))
5922 ((eq arg :timestamp)
5923 (setq rtn (org-agenda-get-blocks))
5924 (setq results (append results rtn))
5925 (setq rtn (org-agenda-get-timestamps))
5926 (setq results (append results rtn)))
5927 ((eq arg :scheduled)
5928 (setq rtn (org-agenda-get-scheduled))
5929 (setq results (append results rtn)))
5930 ((eq arg :closed)
5931 (setq rtn (org-agenda-get-closed))
5932 (setq results (append results rtn)))
5933 ((and (eq arg :deadline)
5934 (equal date (calendar-current-date)))
5935 (setq rtn (org-agenda-get-deadlines))
5936 (setq results (append results rtn))))))))
5937 results))))
5939 (defun org-entry-is-done-p ()
5940 "Is the current entry marked DONE?"
5941 (save-excursion
5942 (and (re-search-backward "[\r\n]\\*" nil t)
5943 (looking-at org-nl-done-regexp))))
5945 (defun org-at-date-range-p ()
5946 "Is the cursor inside a date range?"
5947 (interactive)
5948 (save-excursion
5949 (catch 'exit
5950 (let ((pos (point)))
5951 (skip-chars-backward "^<\r\n")
5952 (skip-chars-backward "<")
5953 (and (looking-at org-tr-regexp)
5954 (>= (match-end 0) pos)
5955 (throw 'exit t))
5956 (skip-chars-backward "^<\r\n")
5957 (skip-chars-backward "<")
5958 (and (looking-at org-tr-regexp)
5959 (>= (match-end 0) pos)
5960 (throw 'exit t)))
5961 nil)))
5963 (defun org-agenda-get-todos ()
5964 "Return the TODO information for agenda display."
5965 (let* ((props (list 'face nil
5966 'done-face 'org-done
5967 'org-not-done-regexp org-not-done-regexp
5968 'mouse-face 'highlight
5969 'keymap org-agenda-keymap
5970 'help-echo
5971 (format "mouse-2 or RET jump to org file %s"
5972 (abbreviate-file-name buffer-file-name))))
5973 (regexp (concat "[\n\r]\\*+ *\\("
5974 (if org-select-this-todo-keyword
5975 (concat "\\<\\(" org-select-this-todo-keyword
5976 "\\)\\>")
5977 org-not-done-regexp)
5978 "[^\n\r]*\\)"))
5979 marker priority category tags
5980 ee txt)
5981 (goto-char (point-min))
5982 (while (re-search-forward regexp nil t)
5983 (goto-char (match-beginning 1))
5984 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5985 category (org-get-category)
5986 tags (org-get-tags-at (point))
5987 txt (org-format-agenda-item "" (match-string 1) category tags)
5988 priority
5989 (+ (org-get-priority txt)
5990 (if org-todo-kwd-priority-p
5991 (- org-todo-kwd-max-priority -2
5992 (length
5993 (member (match-string 2) org-todo-keywords)))
5994 1)))
5995 (org-add-props txt props
5996 'org-marker marker 'org-hd-marker marker
5997 'priority priority 'category category)
5998 (push txt ee)
5999 (goto-char (match-end 1)))
6000 (nreverse ee)))
6002 (defconst org-agenda-no-heading-message
6003 "No heading for this item in buffer or region.")
6005 (defun org-agenda-get-timestamps ()
6006 "Return the date stamp information for agenda display."
6007 (let* ((props (list 'face nil
6008 'org-not-done-regexp org-not-done-regexp
6009 'mouse-face 'highlight
6010 'keymap org-agenda-keymap
6011 'help-echo
6012 (format "mouse-2 or RET jump to org file %s"
6013 (abbreviate-file-name buffer-file-name))))
6014 (regexp (regexp-quote
6015 (substring
6016 (format-time-string
6017 (car org-time-stamp-formats)
6018 (apply 'encode-time ; DATE bound by calendar
6019 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6020 0 11)))
6021 marker hdmarker deadlinep scheduledp donep tmp priority category
6022 ee txt timestr tags)
6023 (goto-char (point-min))
6024 (while (re-search-forward regexp nil t)
6025 (if (not (save-match-data (org-at-date-range-p)))
6026 (progn
6027 (setq marker (org-agenda-new-marker (match-beginning 0))
6028 category (org-get-category (match-beginning 0))
6029 tmp (buffer-substring (max (point-min)
6030 (- (match-beginning 0)
6031 org-ds-keyword-length))
6032 (match-beginning 0))
6033 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6034 deadlinep (string-match org-deadline-regexp tmp)
6035 scheduledp (string-match org-scheduled-regexp tmp)
6036 donep (org-entry-is-done-p))
6037 (if (string-match ">" timestr)
6038 ;; substring should only run to end of time stamp
6039 (setq timestr (substring timestr 0 (match-end 0))))
6040 (save-excursion
6041 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6042 (progn
6043 (goto-char (match-end 1))
6044 (setq hdmarker (org-agenda-new-marker)
6045 tags (org-get-tags-at))
6046 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6047 (setq txt (org-format-agenda-item
6048 (format "%s%s"
6049 (if deadlinep "Deadline: " "")
6050 (if scheduledp "Scheduled: " ""))
6051 (match-string 1) category tags timestr)))
6052 (setq txt org-agenda-no-heading-message))
6053 (setq priority (org-get-priority txt))
6054 (org-add-props txt props
6055 'org-marker marker 'org-hd-marker hdmarker)
6056 (if deadlinep
6057 (org-add-props txt nil
6058 'face (if donep 'org-done 'org-warning)
6059 'undone-face 'org-warning 'done-face 'org-done
6060 'category category 'priority (+ 100 priority))
6061 (if scheduledp
6062 (org-add-props txt nil
6063 'face 'org-scheduled-today
6064 'undone-face 'org-scheduled-today 'done-face 'org-done
6065 'category category 'priority (+ 99 priority))
6066 (org-add-props txt nil 'priority priority 'category category)))
6067 (push txt ee))
6068 (outline-next-heading))))
6069 (nreverse ee)))
6071 (defun org-agenda-get-closed ()
6072 "Return the logged TODO entries for agenda display."
6073 (let* ((props (list 'mouse-face 'highlight
6074 'org-not-done-regexp org-not-done-regexp
6075 'keymap org-agenda-keymap
6076 'help-echo
6077 (format "mouse-2 or RET jump to org file %s"
6078 (abbreviate-file-name buffer-file-name))))
6079 (regexp (concat
6080 "\\<" org-closed-string " *\\["
6081 (regexp-quote
6082 (substring
6083 (format-time-string
6084 (car org-time-stamp-formats)
6085 (apply 'encode-time ; DATE bound by calendar
6086 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6087 1 11))))
6088 marker hdmarker priority category tags
6089 ee txt timestr)
6090 (goto-char (point-min))
6091 (while (re-search-forward regexp nil t)
6092 (if (not (save-match-data (org-at-date-range-p)))
6093 (progn
6094 (setq marker (org-agenda-new-marker (match-beginning 0))
6095 category (org-get-category (match-beginning 0))
6096 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6097 ;; donep (org-entry-is-done-p)
6099 (if (string-match "\\]" timestr)
6100 ;; substring should only run to end of time stamp
6101 (setq timestr (substring timestr 0 (match-end 0))))
6102 (save-excursion
6103 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6104 (progn
6105 (goto-char (match-end 1))
6106 (setq hdmarker (org-agenda-new-marker)
6107 tags (org-get-tags-at))
6108 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6109 (setq txt (org-format-agenda-item
6110 "Closed: "
6111 (match-string 1) category tags timestr)))
6112 (setq txt org-agenda-no-heading-message))
6113 (setq priority 100000)
6114 (org-add-props txt props
6115 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6116 'priority priority 'category category
6117 'undone-face 'org-warning 'done-face 'org-done)
6118 (push txt ee))
6119 (outline-next-heading))))
6120 (nreverse ee)))
6122 (defun org-agenda-get-deadlines ()
6123 "Return the deadline information for agenda display."
6124 (let* ((wdays org-deadline-warning-days)
6125 (props (list 'mouse-face 'highlight
6126 'org-not-done-regexp org-not-done-regexp
6127 'keymap org-agenda-keymap
6128 'help-echo
6129 (format "mouse-2 or RET jump to org file %s"
6130 (abbreviate-file-name buffer-file-name))))
6131 (regexp org-deadline-time-regexp)
6132 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6133 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6134 d2 diff pos pos1 category tags
6135 ee txt head)
6136 (goto-char (point-min))
6137 (while (re-search-forward regexp nil t)
6138 (setq pos (1- (match-beginning 1))
6139 d2 (time-to-days
6140 (org-time-string-to-time (match-string 1)))
6141 diff (- d2 d1))
6142 ;; When to show a deadline in the calendar:
6143 ;; If the expiration is within wdays warning time.
6144 ;; Past-due deadlines are only shown on the current date
6145 (if (and (< diff wdays) todayp (not (= diff 0)))
6146 (save-excursion
6147 (setq category (org-get-category))
6148 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6149 (progn
6150 (goto-char (match-end 0))
6151 (setq pos1 (match-end 1))
6152 (setq tags (org-get-tags-at pos1))
6153 (setq head (buffer-substring-no-properties
6154 (point)
6155 (progn (skip-chars-forward "^\r\n")
6156 (point))))
6157 (if (string-match org-looking-at-done-regexp head)
6158 (setq txt nil)
6159 (setq txt (org-format-agenda-item
6160 (format "In %3d d.: " diff) head category tags))))
6161 (setq txt org-agenda-no-heading-message))
6162 (when txt
6163 (org-add-props txt props
6164 'org-marker (org-agenda-new-marker pos)
6165 'org-hd-marker (org-agenda-new-marker pos1)
6166 'priority (+ (- 10 diff) (org-get-priority txt))
6167 'category category
6168 'face (cond ((<= diff 0) 'org-warning)
6169 ((<= diff 5) 'org-scheduled-previously)
6170 (t nil))
6171 'undone-face (cond
6172 ((<= diff 0) 'org-warning)
6173 ((<= diff 5) 'org-scheduled-previously)
6174 (t nil))
6175 'done-face 'org-done)
6176 (push txt ee)))))
6177 ee))
6179 (defun org-agenda-get-scheduled ()
6180 "Return the scheduled information for agenda display."
6181 (let* ((props (list 'face 'org-scheduled-previously
6182 'org-not-done-regexp org-not-done-regexp
6183 'undone-face 'org-scheduled-previously
6184 'done-face 'org-done
6185 'mouse-face 'highlight
6186 'keymap org-agenda-keymap
6187 'help-echo
6188 (format "mouse-2 or RET jump to org file %s"
6189 (abbreviate-file-name buffer-file-name))))
6190 (regexp org-scheduled-time-regexp)
6191 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6192 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6193 d2 diff pos pos1 category tags
6194 ee txt head)
6195 (goto-char (point-min))
6196 (while (re-search-forward regexp nil t)
6197 (setq pos (1- (match-beginning 1))
6198 d2 (time-to-days
6199 (org-time-string-to-time (match-string 1)))
6200 diff (- d2 d1))
6201 ;; When to show a scheduled item in the calendar:
6202 ;; If it is on or past the date.
6203 (if (and (< diff 0) todayp)
6204 (save-excursion
6205 (setq category (org-get-category))
6206 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6207 (progn
6208 (goto-char (match-end 0))
6209 (setq pos1 (match-end 1))
6210 (setq tags (org-get-tags-at))
6211 (setq head (buffer-substring-no-properties
6212 (point)
6213 (progn (skip-chars-forward "^\r\n") (point))))
6214 (if (string-match org-looking-at-done-regexp head)
6215 (setq txt nil)
6216 (setq txt (org-format-agenda-item
6217 (format "Sched.%2dx: " (- 1 diff)) head
6218 category tags))))
6219 (setq txt org-agenda-no-heading-message))
6220 (when txt
6221 (org-add-props txt props
6222 'org-marker (org-agenda-new-marker pos)
6223 'org-hd-marker (org-agenda-new-marker pos1)
6224 'priority (+ (- 5 diff) (org-get-priority txt))
6225 'category category)
6226 (push txt ee)))))
6227 ee))
6229 (defun org-agenda-get-blocks ()
6230 "Return the date-range information for agenda display."
6231 (let* ((props (list 'face nil
6232 'org-not-done-regexp org-not-done-regexp
6233 'mouse-face 'highlight
6234 'keymap org-agenda-keymap
6235 'help-echo
6236 (format "mouse-2 or RET jump to org file %s"
6237 (abbreviate-file-name buffer-file-name))))
6238 (regexp org-tr-regexp)
6239 (d0 (calendar-absolute-from-gregorian date))
6240 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6241 (goto-char (point-min))
6242 (while (re-search-forward regexp nil t)
6243 (setq timestr (match-string 0)
6244 s1 (match-string 1)
6245 s2 (match-string 2)
6246 d1 (time-to-days (org-time-string-to-time s1))
6247 d2 (time-to-days (org-time-string-to-time s2)))
6248 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6249 ;; Only allow days between the limits, because the normal
6250 ;; date stamps will catch the limits.
6251 (save-excursion
6252 (setq marker (org-agenda-new-marker (point)))
6253 (setq category (org-get-category))
6254 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6255 (progn
6256 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6257 (goto-char (match-end 1))
6258 (setq tags (org-get-tags-at))
6259 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6260 (setq txt (org-format-agenda-item
6261 (format (if (= d1 d2) "" "(%d/%d): ")
6262 (1+ (- d0 d1)) (1+ (- d2 d1)))
6263 (match-string 1) category tags
6264 (if (= d0 d1) timestr))))
6265 (setq txt org-agenda-no-heading-message))
6266 (org-add-props txt props
6267 'org-marker marker 'org-hd-marker hdmarker
6268 'priority (org-get-priority txt) 'category category)
6269 (push txt ee)))
6270 (outline-next-heading))
6271 ;; Sort the entries by expiration date.
6272 (nreverse ee)))
6274 (defconst org-plain-time-of-day-regexp
6275 (concat
6276 "\\(\\<[012]?[0-9]"
6277 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6278 "\\(--?"
6279 "\\(\\<[012]?[0-9]"
6280 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6281 "\\)?")
6282 "Regular expression to match a plain time or time range.
6283 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6284 groups carry important information:
6285 0 the full match
6286 1 the first time, range or not
6287 8 the second time, if it is a range.")
6289 (defconst org-stamp-time-of-day-regexp
6290 (concat
6291 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6292 "\\([012][0-9]:[0-5][0-9]\\)>"
6293 "\\(--?"
6294 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6295 "Regular expression to match a timestamp time or time range.
6296 After a match, the following groups carry important information:
6297 0 the full match
6298 1 date plus weekday, for backreferencing to make sure both times on same day
6299 2 the first time, range or not
6300 4 the second time, if it is a range.")
6302 (defvar org-prefix-has-time nil
6303 "A flag, set by `org-compile-prefix-format'.
6304 The flag is set if the currently compiled format contains a `%t'.")
6305 (defvar org-prefix-has-tag nil
6306 "A flag, set by `org-compile-prefix-format'.
6307 The flag is set if the currently compiled format contains a `%T'.")
6309 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6310 "Format TXT to be inserted into the agenda buffer.
6311 In particular, it adds the prefix and corresponding text properties. EXTRA
6312 must be a string and replaces the `%s' specifier in the prefix format.
6313 CATEGORY (string, symbol or nil) may be used to overrule the default
6314 category taken from local variable or file name. It will replace the `%c'
6315 specifier in the format. DOTIME, when non-nil, indicates that a
6316 time-of-day should be extracted from TXT for sorting of this entry, and for
6317 the `%t' specifier in the format. When DOTIME is a string, this string is
6318 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6319 only the correctly processes TXT should be returned - this is used by
6320 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6321 (save-match-data
6322 ;; Diary entries sometimes have extra whitespace at the beginning
6323 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6324 (let* ((category (or category
6325 org-category
6326 (if buffer-file-name
6327 (file-name-sans-extension
6328 (file-name-nondirectory buffer-file-name))
6329 "")))
6330 (tag (if tags (nth (1- (length tags)) tags) ""))
6331 time ;; needed for the eval of the prefix format
6332 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6333 (time-of-day (and dotime (org-get-time-of-day ts)))
6334 stamp plain s0 s1 s2 rtn)
6335 (when (and dotime time-of-day org-prefix-has-time)
6336 ;; Extract starting and ending time and move them to prefix
6337 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6338 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6339 (setq s0 (match-string 0 ts)
6340 s1 (match-string (if plain 1 2) ts)
6341 s2 (match-string (if plain 8 4) ts))
6343 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6344 ;; them, we might want to remove them there to avoid duplication.
6345 ;; The user can turn this off with a variable.
6346 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6347 (string-match (concat (regexp-quote s0) " *") txt)
6348 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6349 (= (match-beginning 0) 0)
6351 (setq txt (replace-match "" nil nil txt))))
6352 ;; Normalize the time(s) to 24 hour
6353 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6354 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6356 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6357 (and org-agenda-remove-tags-when-in-prefix
6358 org-prefix-has-tag))
6359 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6360 (setq txt (replace-match "" t t txt)))
6362 ;; Create the final string
6363 (if noprefix
6364 (setq rtn txt)
6365 ;; Prepare the variables needed in the eval of the compiled format
6366 (setq time (cond (s2 (concat s1 "-" s2))
6367 (s1 (concat s1 "......"))
6368 (t ""))
6369 extra (or extra "")
6370 category (if (symbolp category) (symbol-name category) category))
6371 ;; Evaluate the compiled format
6372 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6374 ;; And finally add the text properties
6375 (org-add-props rtn nil
6376 'category (downcase category) 'tags tags
6377 'prefix-length (- (length rtn) (length txt))
6378 'time-of-day time-of-day
6379 'dotime dotime))))
6381 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6382 (catch 'exit
6383 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6384 ((and todayp (member 'today (car org-agenda-time-grid))))
6385 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6386 ((member 'weekly (car org-agenda-time-grid)))
6387 (t (throw 'exit list)))
6388 (let* ((have (delq nil (mapcar
6389 (lambda (x) (get-text-property 1 'time-of-day x))
6390 list)))
6391 (string (nth 1 org-agenda-time-grid))
6392 (gridtimes (nth 2 org-agenda-time-grid))
6393 (req (car org-agenda-time-grid))
6394 (remove (member 'remove-match req))
6395 new time)
6396 (if (and (member 'require-timed req) (not have))
6397 ;; don't show empty grid
6398 (throw 'exit list))
6399 (while (setq time (pop gridtimes))
6400 (unless (and remove (member time have))
6401 (setq time (int-to-string time))
6402 (push (org-format-agenda-item
6403 nil string "" nil
6404 (concat (substring time 0 -2) ":" (substring time -2)))
6405 new)
6406 (put-text-property
6407 1 (length (car new)) 'face 'org-time-grid (car new))))
6408 (if (member 'time-up org-agenda-sorting-strategy)
6409 (append new list)
6410 (append list new)))))
6412 (defun org-compile-prefix-format (format)
6413 "Compile the prefix format into a Lisp form that can be evaluated.
6414 The resulting form is returned and stored in the variable
6415 `org-prefix-format-compiled'."
6416 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6417 (let ((start 0) varform vars var (s format)e c f opt)
6418 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6419 s start)
6420 (setq var (cdr (assoc (match-string 4 s)
6421 '(("c" . category) ("t" . time) ("s" . extra)
6422 ("T" . tag))))
6423 c (or (match-string 3 s) "")
6424 opt (match-beginning 1)
6425 start (1+ (match-beginning 0)))
6426 (if (equal var 'time) (setq org-prefix-has-time t))
6427 (if (equal var 'tag) (setq org-prefix-has-tag t))
6428 (setq f (concat "%" (match-string 2 s) "s"))
6429 (if opt
6430 (setq varform
6431 `(if (equal "" ,var)
6433 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6434 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6435 (setq s (replace-match "%s" t nil s))
6436 (push varform vars))
6437 (setq vars (nreverse vars))
6438 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6440 (defun org-get-time-of-day (s &optional string)
6441 "Check string S for a time of day.
6442 If found, return it as a military time number between 0 and 2400.
6443 If not found, return nil.
6444 The optional STRING argument forces conversion into a 5 character wide string
6445 HH:MM."
6446 (save-match-data
6447 (when
6449 (string-match
6450 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6451 (string-match
6452 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6453 (let* ((t0 (+ (* 100
6454 (+ (string-to-number (match-string 1 s))
6455 (if (and (match-beginning 4)
6456 (equal (downcase (match-string 4 s)) "pm"))
6457 12 0)))
6458 (if (match-beginning 3)
6459 (string-to-number (match-string 3 s))
6460 0)))
6461 (t1 (concat " "
6462 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6463 (int-to-string t0))))
6464 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6466 (defun org-finalize-agenda-entries (list)
6467 "Sort and concatenate the agenda items."
6468 (setq list (mapcar 'org-agenda-highlight-todo list))
6469 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6471 (defun org-agenda-highlight-todo (x)
6472 (let (re)
6473 (if (eq x 'line)
6474 (save-excursion
6475 (beginning-of-line 1)
6476 (setq re (get-text-property (point) 'org-not-done-regexp))
6477 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6478 (and (looking-at (concat "[ \t]*" re))
6479 (add-text-properties (match-beginning 0) (match-end 0)
6480 '(face org-todo))))
6481 (setq re (get-text-property 0 'org-not-done-regexp x))
6482 (and re (string-match re x)
6483 (add-text-properties (match-beginning 0) (match-end 0)
6484 '(face org-todo) x))
6485 x)))
6487 (defsubst org-cmp-priority (a b)
6488 "Compare the priorities of string A and B."
6489 (let ((pa (or (get-text-property 1 'priority a) 0))
6490 (pb (or (get-text-property 1 'priority b) 0)))
6491 (cond ((> pa pb) +1)
6492 ((< pa pb) -1)
6493 (t nil))))
6495 (defsubst org-cmp-category (a b)
6496 "Compare the string values of categories of strings A and B."
6497 (let ((ca (or (get-text-property 1 'category a) ""))
6498 (cb (or (get-text-property 1 'category b) "")))
6499 (cond ((string-lessp ca cb) -1)
6500 ((string-lessp cb ca) +1)
6501 (t nil))))
6503 (defsubst org-cmp-time (a b)
6504 "Compare the time-of-day values of strings A and B."
6505 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6506 (ta (or (get-text-property 1 'time-of-day a) def))
6507 (tb (or (get-text-property 1 'time-of-day b) def)))
6508 (cond ((< ta tb) -1)
6509 ((< tb ta) +1)
6510 (t nil))))
6512 (defun org-entries-lessp (a b)
6513 "Predicate for sorting agenda entries."
6514 ;; The following variables will be used when the form is evaluated.
6515 (let* ((time-up (org-cmp-time a b))
6516 (time-down (if time-up (- time-up) nil))
6517 (priority-up (org-cmp-priority a b))
6518 (priority-down (if priority-up (- priority-up) nil))
6519 (category-up (org-cmp-category a b))
6520 (category-down (if category-up (- category-up) nil))
6521 (category-keep (if category-up +1 nil)))
6522 (cdr (assoc
6523 (eval (cons 'or org-agenda-sorting-strategy))
6524 '((-1 . t) (1 . nil) (nil . nil))))))
6526 (defun org-agenda-show-priority ()
6527 "Show the priority of the current item.
6528 This priority is composed of the main priority given with the [#A] cookies,
6529 and by additional input from the age of a schedules or deadline entry."
6530 (interactive)
6531 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6532 (message "Priority is %d" (if pri pri -1000))))
6534 (defun org-agenda-show-tags ()
6535 "Show the tags applicable to the current item."
6536 (interactive)
6537 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6538 (if tags
6539 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6540 (message "No tags associated with this line"))))
6542 (defun org-agenda-goto (&optional highlight)
6543 "Go to the Org-mode file which contains the item at point."
6544 (interactive)
6545 (let* ((marker (or (get-text-property (point) 'org-marker)
6546 (org-agenda-error)))
6547 (buffer (marker-buffer marker))
6548 (pos (marker-position marker)))
6549 (switch-to-buffer-other-window buffer)
6550 (widen)
6551 (goto-char pos)
6552 (when (eq major-mode 'org-mode)
6553 (org-show-hidden-entry)
6554 (save-excursion
6555 (and (outline-next-heading)
6556 (org-flag-heading nil)))) ; show the next heading
6557 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6559 (defun org-agenda-switch-to ()
6560 "Go to the Org-mode file which contains the item at point."
6561 (interactive)
6562 (let* ((marker (or (get-text-property (point) 'org-marker)
6563 (org-agenda-error)))
6564 (buffer (marker-buffer marker))
6565 (pos (marker-position marker)))
6566 (switch-to-buffer buffer)
6567 (delete-other-windows)
6568 (widen)
6569 (goto-char pos)
6570 (when (eq major-mode 'org-mode)
6571 (org-show-hidden-entry)
6572 (save-excursion
6573 (and (outline-next-heading)
6574 (org-flag-heading nil)))))) ; show the next heading
6576 (defun org-agenda-goto-mouse (ev)
6577 "Go to the Org-mode file which contains the item at the mouse click."
6578 (interactive "e")
6579 (mouse-set-point ev)
6580 (org-agenda-goto))
6582 (defun org-agenda-show ()
6583 "Display the Org-mode file which contains the item at point."
6584 (interactive)
6585 (let ((win (selected-window)))
6586 (org-agenda-goto t)
6587 (select-window win)))
6589 (defun org-agenda-recenter (arg)
6590 "Display the Org-mode file which contains the item at point and recenter."
6591 (interactive "P")
6592 (let ((win (selected-window)))
6593 (org-agenda-goto t)
6594 (recenter arg)
6595 (select-window win)))
6597 (defun org-agenda-show-mouse (ev)
6598 "Display the Org-mode file which contains the item at the mouse click."
6599 (interactive "e")
6600 (mouse-set-point ev)
6601 (org-agenda-show))
6603 (defun org-agenda-check-no-diary ()
6604 "Check if the entry is a diary link and abort if yes."
6605 (if (get-text-property (point) 'org-agenda-diary-link)
6606 (org-agenda-error)))
6608 (defun org-agenda-error ()
6609 (error "Command not allowed in this line"))
6611 (defvar org-last-heading-marker (make-marker)
6612 "Marker pointing to the headline that last changed its TODO state
6613 by a remote command from the agenda.")
6615 (defun org-agenda-todo (&optional arg)
6616 "Cycle TODO state of line at point, also in Org-mode file.
6617 This changes the line at point, all other lines in the agenda referring to
6618 the same tree node, and the headline of the tree node in the Org-mode file."
6619 (interactive "P")
6620 (org-agenda-check-no-diary)
6621 (let* ((col (current-column))
6622 (marker (or (get-text-property (point) 'org-marker)
6623 (org-agenda-error)))
6624 (buffer (marker-buffer marker))
6625 (pos (marker-position marker))
6626 (hdmarker (get-text-property (point) 'org-hd-marker))
6627 (buffer-read-only nil)
6628 newhead)
6629 (with-current-buffer buffer
6630 (widen)
6631 (goto-char pos)
6632 (org-show-hidden-entry)
6633 (save-excursion
6634 (and (outline-next-heading)
6635 (org-flag-heading nil))) ; show the next heading
6636 (org-todo arg)
6637 (and (bolp) (forward-char 1))
6638 (setq newhead (org-get-heading))
6639 (save-excursion
6640 (org-back-to-heading)
6641 (move-marker org-last-heading-marker (point))))
6642 (beginning-of-line 1)
6643 (save-excursion
6644 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6645 (move-to-column col)))
6647 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6648 "Change all lines in the agenda buffer which match HDMARKER.
6649 The new content of the line will be NEWHEAD (as modified by
6650 `org-format-agenda-item'). HDMARKER is checked with
6651 `equal' against all `org-hd-marker' text properties in the file.
6652 If FIXFACE is non-nil, the face of each item is modified acording to
6653 the new TODO state."
6654 (let* (props m pl undone-face done-face finish new dotime cat tags)
6655 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6656 (save-excursion
6657 (goto-char (point-max))
6658 (beginning-of-line 1)
6659 (while (not finish)
6660 (setq finish (bobp))
6661 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6662 (equal m hdmarker))
6663 (setq props (text-properties-at (point))
6664 dotime (get-text-property (point) 'dotime)
6665 cat (get-text-property (point) 'category)
6666 tags (get-text-property (point) 'tags)
6667 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6668 pl (get-text-property (point) 'prefix-length)
6669 undone-face (get-text-property (point) 'undone-face)
6670 done-face (get-text-property (point) 'done-face))
6671 (move-to-column pl)
6672 (if (looking-at ".*")
6673 (progn
6674 (replace-match new t t)
6675 (beginning-of-line 1)
6676 (add-text-properties (point-at-bol) (point-at-eol) props)
6677 (when fixface
6678 (add-text-properties
6679 (point-at-bol) (point-at-eol)
6680 (list 'face
6681 (if org-last-todo-state-is-todo
6682 undone-face done-face)))
6683 (org-agenda-highlight-todo 'line))
6684 (beginning-of-line 1))
6685 (error "Line update did not work")))
6686 (beginning-of-line 0)))))
6688 (defun org-agenda-priority-up ()
6689 "Increase the priority of line at point, also in Org-mode file."
6690 (interactive)
6691 (org-agenda-priority 'up))
6693 (defun org-agenda-priority-down ()
6694 "Decrease the priority of line at point, also in Org-mode file."
6695 (interactive)
6696 (org-agenda-priority 'down))
6698 (defun org-agenda-priority (&optional force-direction)
6699 "Set the priority of line at point, also in Org-mode file.
6700 This changes the line at point, all other lines in the agenda referring to
6701 the same tree node, and the headline of the tree node in the Org-mode file."
6702 (interactive)
6703 (org-agenda-check-no-diary)
6704 (let* ((marker (or (get-text-property (point) 'org-marker)
6705 (org-agenda-error)))
6706 (buffer (marker-buffer marker))
6707 (pos (marker-position marker))
6708 (hdmarker (get-text-property (point) 'org-hd-marker))
6709 (buffer-read-only nil)
6710 newhead)
6711 (with-current-buffer buffer
6712 (widen)
6713 (goto-char pos)
6714 (org-show-hidden-entry)
6715 (save-excursion
6716 (and (outline-next-heading)
6717 (org-flag-heading nil))) ; show the next heading
6718 (funcall 'org-priority force-direction)
6719 (end-of-line 1)
6720 (setq newhead (org-get-heading)))
6721 (org-agenda-change-all-lines newhead hdmarker)
6722 (beginning-of-line 1)))
6724 (defun org-get-tags-at (&optional pos)
6725 "Get a list of all headline targs applicable at POS.
6726 POS defaults to point. If tags are inherited, the list contains
6727 the targets in the same sequence as the headlines appear, i.e.
6728 the tags of the current headline come last."
6729 (interactive)
6730 (let (tags)
6731 (save-excursion
6732 (goto-char (or pos (point)))
6733 (save-match-data
6734 (org-back-to-heading t)
6735 (condition-case nil
6736 (while t
6737 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6738 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6739 (or org-use-tag-inheritance (error ""))
6740 (org-up-heading-all 1))
6741 (error nil))))
6742 (message "%s" tags)
6743 tags))
6745 (defun org-agenda-set-tags ()
6746 "Set tags for the current headline."
6747 (interactive)
6748 (org-agenda-check-no-diary)
6749 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6750 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6751 (org-agenda-error)))
6752 (buffer (marker-buffer hdmarker))
6753 (pos (marker-position hdmarker))
6754 (buffer-read-only nil)
6755 newhead)
6756 (with-current-buffer buffer
6757 (widen)
6758 (goto-char pos)
6759 (org-show-hidden-entry)
6760 (save-excursion
6761 (and (outline-next-heading)
6762 (org-flag-heading nil))) ; show the next heading
6763 (call-interactively 'org-set-tags)
6764 (end-of-line 1)
6765 (setq newhead (org-get-heading)))
6766 (org-agenda-change-all-lines newhead hdmarker)
6767 (beginning-of-line 1)))
6769 (defun org-agenda-date-later (arg &optional what)
6770 "Change the date of this item to one day later."
6771 (interactive "p")
6772 (org-agenda-check-type t 'agenda 'timeline)
6773 (org-agenda-check-no-diary)
6774 (let* ((marker (or (get-text-property (point) 'org-marker)
6775 (org-agenda-error)))
6776 (buffer (marker-buffer marker))
6777 (pos (marker-position marker)))
6778 (with-current-buffer buffer
6779 (widen)
6780 (goto-char pos)
6781 (if (not (org-at-timestamp-p))
6782 (error "Cannot find time stamp"))
6783 (org-timestamp-change arg (or what 'day))
6784 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6786 (defun org-agenda-date-earlier (arg &optional what)
6787 "Change the date of this item to one day earlier."
6788 (interactive "p")
6789 (org-agenda-date-later (- arg) what))
6791 (defun org-agenda-date-prompt (arg)
6792 "Change the date of this item. Date is prompted for, with default today.
6793 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6794 be used to request time specification in the time stamp."
6795 (interactive "P")
6796 (org-agenda-check-type t 'agenda 'timeline)
6797 (org-agenda-check-no-diary)
6798 (let* ((marker (or (get-text-property (point) 'org-marker)
6799 (org-agenda-error)))
6800 (buffer (marker-buffer marker))
6801 (pos (marker-position marker)))
6802 (with-current-buffer buffer
6803 (widen)
6804 (goto-char pos)
6805 (if (not (org-at-timestamp-p))
6806 (error "Cannot find time stamp"))
6807 (org-time-stamp arg)
6808 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6810 (defun org-get-heading ()
6811 "Return the heading of the current entry, without the stars."
6812 (save-excursion
6813 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6814 (if (and (re-search-backward "[\r\n]\\*" nil t)
6815 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6816 (match-string 1)
6817 "")))
6819 (defun org-agenda-diary-entry ()
6820 "Make a diary entry, like the `i' command from the calendar.
6821 All the standard commands work: block, weekly etc."
6822 (interactive)
6823 (org-agenda-check-type t 'agenda 'timeline)
6824 (require 'diary-lib)
6825 (let* ((char (progn
6826 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6827 (read-char-exclusive)))
6828 (cmd (cdr (assoc char
6829 '((?d . insert-diary-entry)
6830 (?w . insert-weekly-diary-entry)
6831 (?m . insert-monthly-diary-entry)
6832 (?y . insert-yearly-diary-entry)
6833 (?a . insert-anniversary-diary-entry)
6834 (?b . insert-block-diary-entry)
6835 (?c . insert-cyclic-diary-entry)))))
6836 (oldf (symbol-function 'calendar-cursor-to-date))
6837 (point (point))
6838 (mark (or (mark t) (point))))
6839 (unless cmd
6840 (error "No command associated with <%c>" char))
6841 (unless (and (get-text-property point 'day)
6842 (or (not (equal ?b char))
6843 (get-text-property mark 'day)))
6844 (error "Don't know which date to use for diary entry"))
6845 ;; We implement this by hacking the `calendar-cursor-to-date' function
6846 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6847 (let ((calendar-mark-ring
6848 (list (calendar-gregorian-from-absolute
6849 (or (get-text-property mark 'day)
6850 (get-text-property point 'day))))))
6851 (unwind-protect
6852 (progn
6853 (fset 'calendar-cursor-to-date
6854 (lambda (&optional error)
6855 (calendar-gregorian-from-absolute
6856 (get-text-property point 'day))))
6857 (call-interactively cmd))
6858 (fset 'calendar-cursor-to-date oldf)))))
6861 (defun org-agenda-execute-calendar-command (cmd)
6862 "Execute a calendar command from the agenda, with the date associated to
6863 the cursor position."
6864 (org-agenda-check-type t 'agenda 'timeline)
6865 (require 'diary-lib)
6866 (unless (get-text-property (point) 'day)
6867 (error "Don't know which date to use for calendar command"))
6868 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6869 (point (point))
6870 (date (calendar-gregorian-from-absolute
6871 (get-text-property point 'day)))
6872 (displayed-day (extract-calendar-day date))
6873 (displayed-month (extract-calendar-month date))
6874 (displayed-year (extract-calendar-year date)))
6875 (unwind-protect
6876 (progn
6877 (fset 'calendar-cursor-to-date
6878 (lambda (&optional error)
6879 (calendar-gregorian-from-absolute
6880 (get-text-property point 'day))))
6881 (call-interactively cmd))
6882 (fset 'calendar-cursor-to-date oldf))))
6884 (defun org-agenda-phases-of-moon ()
6885 "Display the phases of the moon for the 3 months around the cursor date."
6886 (interactive)
6887 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6889 (defun org-agenda-holidays ()
6890 "Display the holidays for the 3 months around the cursor date."
6891 (interactive)
6892 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6894 (defun org-agenda-sunrise-sunset (arg)
6895 "Display sunrise and sunset for the cursor date.
6896 Latitude and longitude can be specified with the variables
6897 `calendar-latitude' and `calendar-longitude'. When called with prefix
6898 argument, latitude and longitude will be prompted for."
6899 (interactive "P")
6900 (let ((calendar-longitude (if arg nil calendar-longitude))
6901 (calendar-latitude (if arg nil calendar-latitude))
6902 (calendar-location-name
6903 (if arg "the given coordinates" calendar-location-name)))
6904 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6906 (defun org-agenda-goto-calendar ()
6907 "Open the Emacs calendar with the date at the cursor."
6908 (interactive)
6909 (org-agenda-check-type t 'agenda 'timeline)
6910 (let* ((day (or (get-text-property (point) 'day)
6911 (error "Don't know which date to open in calendar")))
6912 (date (calendar-gregorian-from-absolute day))
6913 (calendar-move-hook nil)
6914 (view-diary-entries-initially nil))
6915 (calendar)
6916 (calendar-goto-date date)))
6918 (defun org-calendar-goto-agenda ()
6919 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6920 This is a command that has to be installed in `calendar-mode-map'."
6921 (interactive)
6922 (org-agenda-list nil (calendar-absolute-from-gregorian
6923 (calendar-cursor-to-date))
6924 nil t))
6926 (defun org-agenda-convert-date ()
6927 (interactive)
6928 (org-agenda-check-type t 'agenda 'timeline)
6929 (let ((day (get-text-property (point) 'day))
6930 date s)
6931 (unless day
6932 (error "Don't know which date to convert"))
6933 (setq date (calendar-gregorian-from-absolute day))
6934 (setq s (concat
6935 "Gregorian: " (calendar-date-string date) "\n"
6936 "ISO: " (calendar-iso-date-string date) "\n"
6937 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6938 "Julian: " (calendar-julian-date-string date) "\n"
6939 "Astron. JD: " (calendar-astro-date-string date)
6940 " (Julian date number at noon UTC)\n"
6941 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6942 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6943 "French: " (calendar-french-date-string date) "\n"
6944 "Mayan: " (calendar-mayan-date-string date) "\n"
6945 "Coptic: " (calendar-coptic-date-string date) "\n"
6946 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6947 "Persian: " (calendar-persian-date-string date) "\n"
6948 "Chinese: " (calendar-chinese-date-string date) "\n"))
6949 (with-output-to-temp-buffer "*Dates*"
6950 (princ s))
6951 (if (fboundp 'fit-window-to-buffer)
6952 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6954 ;;; Tags
6956 (defun org-scan-tags (action matcher &optional todo-only)
6957 "Scan headline tags with inheritance and produce output ACTION.
6958 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6959 evaluated, testing if a given set of tags qualifies a headline for
6960 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6961 are included in the output."
6962 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6963 (mapconcat 'regexp-quote
6964 (nreverse (cdr (reverse org-todo-keywords)))
6965 "\\|")
6966 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6967 (props (list 'face nil
6968 'done-face 'org-done
6969 'undone-face nil
6970 'mouse-face 'highlight
6971 'keymap org-agenda-keymap
6972 'help-echo
6973 (format "mouse-2 or RET jump to org file %s"
6974 (abbreviate-file-name buffer-file-name))))
6975 lspos
6976 tags tags-list tags-alist (llast 0) rtn level category i txt
6977 todo marker)
6979 (save-excursion
6980 (goto-char (point-min))
6981 (when (eq action 'sparse-tree) (hide-sublevels 1))
6982 (while (re-search-forward re nil t)
6983 (setq todo (if (match-end 1) (match-string 2))
6984 tags (if (match-end 4) (match-string 4)))
6985 (goto-char (setq lspos (1+ (match-beginning 0))))
6986 (setq level (funcall outline-level)
6987 category (org-get-category))
6988 (setq i llast llast level)
6989 ;; remove tag lists from same and sublevels
6990 (while (>= i level)
6991 (when (setq entry (assoc i tags-alist))
6992 (setq tags-alist (delete entry tags-alist)))
6993 (setq i (1- i)))
6994 ;; add the nex tags
6995 (when tags
6996 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6997 tags-alist
6998 (cons (cons level tags) tags-alist)))
6999 ;; compile tags for current headline
7000 (setq tags-list
7001 (if org-use-tag-inheritance
7002 (apply 'append (mapcar 'cdr tags-alist))
7003 tags))
7004 (when (and (or (not todo-only) todo)
7005 (eval matcher))
7006 ;; list this headline
7007 (if (eq action 'sparse-tree)
7008 (progn
7009 (org-show-hierarchy-above))
7010 (setq txt (org-format-agenda-item
7012 (concat
7013 (if org-tags-match-list-sublevels
7014 (make-string (1- level) ?.) "")
7015 (org-get-heading))
7016 category tags-list))
7017 (goto-char lspos)
7018 (setq marker (org-agenda-new-marker))
7019 (org-add-props txt props
7020 'org-marker marker 'org-hd-marker marker 'category category)
7021 (push txt rtn))
7022 ;; if we are to skip sublevels, jump to end of subtree
7023 (point)
7024 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7025 (nreverse rtn)))
7027 (defun org-tags-sparse-tree (&optional arg match)
7028 "Create a sparse tree according to tags search string MATCH.
7029 MATCH can contain positive and negative selection of tags, like
7030 \"+WORK+URGENT-WITHBOSS\"."
7031 (interactive "P")
7032 (let ((org-show-following-heading nil)
7033 (org-show-hierarchy-above nil))
7034 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7036 (defun org-make-tags-matcher (match)
7037 "Create the TAGS matcher form for the tags-selecting string MATCH."
7038 (unless match
7039 ;; Get a new match request, with completion
7040 (setq org-last-tags-completion-table
7041 (or (org-get-buffer-tags)
7042 org-last-tags-completion-table))
7043 (setq match (completing-read
7044 "Tags: " 'org-tags-completion-function nil nil nil
7045 'org-tags-history)))
7046 ;; parse the string and create a lisp form
7047 (let ((match0 match) minus tag mm matcher orterms term orlist)
7048 (setq orterms (org-split-string match "|"))
7049 (while (setq term (pop orterms))
7050 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7051 (setq minus (and (match-end 1)
7052 (equal (match-string 1 term) "-"))
7053 tag (match-string 2 term)
7054 term (substring term (match-end 0))
7055 mm (list 'member (downcase tag) 'tags-list)
7056 mm (if minus (list 'not mm) mm))
7057 (push mm matcher))
7058 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7059 orlist)
7060 (setq matcher nil))
7061 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7062 ;; Return the string and lisp forms of the matcher
7063 (cons match0 matcher)))
7065 ;;;###autoload
7066 (defun org-tags-view (&optional todo-only match keep-modes)
7067 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7068 The prefix arg TODO-ONLY limits the search to TODO entries."
7069 (interactive "P")
7070 (org-agenda-maybe-reset-markers 'force)
7071 (org-compile-prefix-format org-agenda-prefix-format)
7072 (let* ((org-agenda-keep-modes keep-modes)
7073 (org-tags-match-list-sublevels
7074 (if todo-only t org-tags-match-list-sublevels))
7075 (win (selected-window))
7076 (completion-ignore-case t)
7077 rtn rtnall files file pos matcher
7078 buffer)
7079 (setq matcher (org-make-tags-matcher match)
7080 match (car matcher) matcher (cdr matcher))
7081 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7082 (progn
7083 (delete-other-windows)
7084 (switch-to-buffer-other-window
7085 (get-buffer-create org-agenda-buffer-name))))
7086 (setq buffer-read-only nil)
7087 (erase-buffer)
7088 (org-agenda-mode) (setq buffer-read-only nil)
7089 (set (make-local-variable 'org-agenda-type) 'tags)
7090 (set (make-local-variable 'org-agenda-redo-command)
7091 (list 'org-tags-view (list 'quote todo-only)
7092 (list 'if 'current-prefix-arg nil match) t))
7093 (setq files (org-agenda-files)
7094 rtnall nil)
7095 (while (setq file (pop files))
7096 (catch 'nextfile
7097 (org-check-agenda-file file)
7098 (setq buffer (if (file-exists-p file)
7099 (org-get-agenda-file-buffer file)
7100 (error "No such file %s" file)))
7101 (if (not buffer)
7102 ;; If file does not exist, merror message to agenda
7103 (setq rtn (list
7104 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7105 rtnall (append rtnall rtn))
7106 (with-current-buffer buffer
7107 (unless (eq major-mode 'org-mode)
7108 (error "Agenda file %s is not in `org-mode'" file))
7109 (save-excursion
7110 (save-restriction
7111 (if org-respect-restriction
7112 (if (org-region-active-p)
7113 ;; Respect a region to restrict search
7114 (narrow-to-region (region-beginning) (region-end)))
7115 ;; If we work for the calendar or many files,
7116 ;; get rid of any restriction
7117 (widen))
7118 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7119 (setq rtnall (append rtnall rtn))))))))
7120 (insert "Headlines with TAGS match: ")
7121 (add-text-properties (point-min) (1- (point))
7122 (list 'face 'org-level-3))
7123 (setq pos (point))
7124 (insert match "\n")
7125 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7126 (setq pos (point))
7127 (insert "Press `C-u r' to search again with new search string\n")
7128 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7129 (when rtnall
7130 (insert (mapconcat 'identity rtnall "\n")))
7131 (goto-char (point-min))
7132 (setq buffer-read-only t)
7133 (org-fit-agenda-window)
7134 (if (not org-select-agenda-window) (select-window win))))
7136 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7137 (defun org-set-tags (&optional arg just-align)
7138 "Set the tags for the current headline.
7139 With prefix ARG, realign all tags in headings in the current buffer."
7140 (interactive)
7141 (let* (;(inherit (org-get-inherited-tags))
7142 (re (concat "^" outline-regexp))
7143 (col (current-column))
7144 (current (org-get-tags))
7145 tags hd empty invis)
7146 (if arg
7147 (save-excursion
7148 (goto-char (point-min))
7149 (while (re-search-forward re nil t)
7150 (org-set-tags nil t))
7151 (message "All tags realigned to column %d" org-tags-column))
7152 (if just-align
7153 (setq tags current)
7154 (setq org-last-tags-completion-table
7155 (or (org-get-buffer-tags)
7156 org-last-tags-completion-table))
7157 (setq tags
7158 (let ((org-add-colon-after-tag-completion t))
7159 (completing-read "Tags: " 'org-tags-completion-function
7160 nil nil current 'org-tags-history)))
7161 (while (string-match "[-+&]+" tags)
7162 (setq tags (replace-match ":" t t tags))))
7163 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7164 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7165 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7166 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7167 (if (equal current "")
7168 (progn
7169 (end-of-line 1)
7170 (or empty (insert-before-markers " ")))
7171 (beginning-of-line 1)
7172 (setq invis (org-invisible-p))
7173 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7174 (setq hd (match-string 1))
7175 (delete-region (match-beginning 0) (match-end 0))
7176 (insert-before-markers (org-trim hd) (if empty "" " ")))
7177 (unless (equal tags "")
7178 (move-to-column (max (current-column)
7179 (if (> org-tags-column 0)
7180 org-tags-column
7181 (- (- org-tags-column) (length tags))))
7183 (insert-before-markers tags)
7184 (if (and (not invis) (org-invisible-p))
7185 (outline-flag-region (point-at-bol) (point) nil)))
7186 (move-to-column col))))
7188 (defun org-tags-completion-function (string predicate &optional flag)
7189 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7190 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7191 (setq s1 (match-string 1 string)
7192 s2 (match-string 2 string))
7193 (setq s1 "" s2 string))
7194 (cond
7195 ((eq flag nil)
7196 ;; try completion
7197 (setq rtn (try-completion s2 ctable))
7198 (if (stringp rtn)
7199 (concat s1 s2 (substring rtn (length s2))
7200 (if (and org-add-colon-after-tag-completion
7201 (assoc rtn ctable))
7202 ":" "")))
7204 ((eq flag t)
7205 ;; all-completions
7206 (all-completions s2 ctable)
7208 ((eq flag 'lambda)
7209 ;; exact match?
7210 (assoc s2 ctable)))
7213 (defun org-get-tags ()
7214 "Get the TAGS string in the current headline."
7215 (unless (org-on-heading-p)
7216 (error "Not on a heading"))
7217 (save-excursion
7218 (beginning-of-line 1)
7219 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7220 (org-match-string-no-properties 1)
7221 "")))
7223 (defun org-get-buffer-tags ()
7224 "Get a table of all tags used in the buffer, for completion."
7225 (let (tags)
7226 (save-excursion
7227 (goto-char (point-min))
7228 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7229 (mapc (lambda (x) (add-to-list 'tags x))
7230 (org-split-string (org-match-string-no-properties 1) ":"))))
7231 (mapcar 'list tags)))
7233 ;;; Link Stuff
7235 (defun org-find-file-at-mouse (ev)
7236 "Open file link or URL at mouse."
7237 (interactive "e")
7238 (mouse-set-point ev)
7239 (org-open-at-point 'in-emacs))
7241 (defun org-open-at-mouse (ev)
7242 "Open file link or URL at mouse."
7243 (interactive "e")
7244 (mouse-set-point ev)
7245 (org-open-at-point))
7247 (defun org-open-at-point (&optional in-emacs)
7248 "Open link at or after point.
7249 If there is no link at point, this function will search forward up to
7250 the end of the current subtree.
7251 Normally, files will be opened by an appropriate application. If the
7252 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7253 (interactive "P")
7254 (org-remove-occur-highlights nil nil t)
7255 (if (org-at-timestamp-p)
7256 (org-agenda-list nil (time-to-days (org-time-string-to-time
7257 (substring (match-string 1) 0 10)))
7259 (let (type path link line search (pos (point)))
7260 (catch 'match
7261 (save-excursion
7262 (skip-chars-forward "^]\n\r")
7263 (when (and (re-search-backward "\\[\\[" nil t)
7264 (looking-at org-bracket-link-regexp)
7265 (<= (match-beginning 0) pos)
7266 (>= (match-end 0) pos))
7267 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7268 (while (string-match " *\n *" link)
7269 (setq link (replace-match " " t t link)))
7270 (if (string-match org-link-re-with-space2 link)
7271 (setq type (match-string 1 link)
7272 path (match-string 2 link))
7273 (setq type "thisfile"
7274 path link))
7275 (throw 'match t)))
7277 (when (get-text-property (point) 'org-linked-text)
7278 (setq type "thisfile"
7279 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7280 (1+ (point)) (point))
7281 path (buffer-substring
7282 (previous-single-property-change pos 'org-linked-text)
7283 (next-single-property-change pos 'org-linked-text)))
7284 (throw 'match t))
7286 (save-excursion
7287 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7288 (if (equal (char-before) ?<) (backward-char 1))
7289 (when (or (looking-at org-angle-link-re)
7290 (looking-at org-plain-link-re)
7291 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7292 (re-search-forward org-plain-link-re (point-at-eol) t))
7293 (<= (match-beginning 0) pos)
7294 (>= (match-end 0) pos)))
7295 (setq type (match-string 1)
7296 path (match-string 2))
7297 (throw 'match t)))
7298 (save-excursion
7299 (skip-chars-backward "^ \t\n\r")
7300 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7301 (setq type "tags"
7302 path (match-string 1))
7303 (while (string-match ":" path)
7304 (setq path (replace-match "+" t t path)))
7305 (throw 'match t)))
7306 (save-excursion
7307 (skip-chars-backward "a-zA-Z_")
7308 (when (and (memq 'camel org-activate-links)
7309 (looking-at org-camel-regexp))
7310 (setq type "camel" path (match-string 0))
7311 (if (equal (char-before) ?*)
7312 (setq path (concat "*" path))))
7313 (throw 'match t)))
7314 (unless path
7315 (error "No link found"))
7316 ;; Remove any trailing spaces in path
7317 (if (string-match " +\\'" path)
7318 (setq path (replace-match "" t t path)))
7320 (cond
7322 ((member type '("http" "https" "ftp" "mailto" "news"))
7323 (browse-url (concat type ":" path)))
7325 ((string= type "tags")
7326 (org-tags-view in-emacs path))
7327 ((or (string= type "camel")
7328 (string= type "thisfile"))
7329 (org-mark-ring-push)
7330 (org-link-search
7331 path
7332 (cond ((equal in-emacs '(4)) 'occur)
7333 ((equal in-emacs '(16)) 'org-occur)
7334 (t nil))))
7336 ((string= type "file")
7337 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7338 (setq line (string-to-number (match-string 1 path))
7339 path (substring path 0 (match-beginning 0)))
7340 (if (string-match "::\\(.+\\)\\'" path)
7341 (setq search (match-string 1 path)
7342 path (substring path 0 (match-beginning 0)))))
7343 (org-open-file path in-emacs line search))
7345 ((string= type "news")
7346 (org-follow-gnus-link path))
7348 ((string= type "bbdb")
7349 (org-follow-bbdb-link path))
7351 ((string= type "gnus")
7352 (let (group article)
7353 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7354 (error "Error in Gnus link"))
7355 (setq group (match-string 1 path)
7356 article (match-string 3 path))
7357 (org-follow-gnus-link group article)))
7359 ((string= type "vm")
7360 (let (folder article)
7361 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7362 (error "Error in VM link"))
7363 (setq folder (match-string 1 path)
7364 article (match-string 3 path))
7365 ;; in-emacs is the prefix arg, will be interpreted as read-only
7366 (org-follow-vm-link folder article in-emacs)))
7368 ((string= type "wl")
7369 (let (folder article)
7370 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7371 (error "Error in Wanderlust link"))
7372 (setq folder (match-string 1 path)
7373 article (match-string 3 path))
7374 (org-follow-wl-link folder article)))
7376 ((string= type "mhe")
7377 (let (folder article)
7378 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7379 (error "Error in MHE link"))
7380 (setq folder (match-string 1 path)
7381 article (match-string 3 path))
7382 (org-follow-mhe-link folder article)))
7384 ((string= type "rmail")
7385 (let (folder article)
7386 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7387 (error "Error in RMAIL link"))
7388 (setq folder (match-string 1 path)
7389 article (match-string 3 path))
7390 (org-follow-rmail-link folder article)))
7392 ((string= type "shell")
7393 (let ((cmd path))
7394 (while (string-match "@{" cmd)
7395 (setq cmd (replace-match "<" t t cmd)))
7396 (while (string-match "@}" cmd)
7397 (setq cmd (replace-match ">" t t cmd)))
7398 (if (or (not org-confirm-shell-links)
7399 (funcall org-confirm-shell-links
7400 (format "Execute \"%s\" in shell? "
7401 (org-add-props cmd nil
7402 'face 'org-warning))))
7403 (progn
7404 (message "Executing %s" cmd)
7405 (shell-command cmd))
7406 (error "Abort"))))
7409 (browse-url-at-point))))))
7411 (defun org-link-search (s &optional type)
7412 "Search for a link search option.
7413 When S is a CamelCaseWord, search for a target, or for a sentence containing
7414 the words. If S is surrounded by forward slashes, it is interpreted as a
7415 regular expression. In org-mode files, this will create an `org-occur'
7416 sparse tree. In ordinary files, `occur' will be used to list matches.
7417 If the current buffer is in `dired-mode', grep will be used to search
7418 in all files."
7419 (let ((case-fold-search t)
7420 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7421 (pos (point))
7422 (pre "") (post "")
7423 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7424 (cond ((save-excursion
7425 (goto-char (point-min))
7426 (and
7427 (re-search-forward
7428 (concat "<<" (regexp-quote s0) ">>") nil t)
7429 (setq pos (match-beginning 0))))
7430 ;; There is an exact target for this
7431 (goto-char pos))
7432 ((string-match "^/\\(.*\\)/$" s)
7433 ;; A regular expression
7434 (cond
7435 ((eq major-mode 'org-mode)
7436 (org-occur (match-string 1 s)))
7437 ;;((eq major-mode 'dired-mode)
7438 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7439 (t (org-do-occur (match-string 1 s)))))
7440 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7442 ;; A camel or a normal search string
7443 (when (equal (string-to-char s) ?*)
7444 ;; Anchor on headlines, post may include tags.
7445 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7446 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7447 s (substring s 1)))
7448 (remove-text-properties
7449 0 (length s)
7450 '(face nil mouse-face nil keymap nil fontified nil) s)
7451 ;; Make a series of regular expressions to find a match
7452 (setq words
7453 (if camel
7454 (org-camel-to-words s)
7455 (org-split-string s "[ \n\r\t]+"))
7456 re0 (concat "<<" (regexp-quote s0) ">>")
7457 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7458 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7459 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7460 re1 (concat pre re2 post)
7461 re3 (concat pre re4 post)
7462 re5 (concat pre ".*" re4)
7463 re2 (concat pre re2)
7464 re2a (concat pre re2a)
7465 re4 (concat pre re4)
7466 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7467 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7468 re5 "\\)"
7470 (cond
7471 ((eq type 'org-occur) (org-occur reall))
7472 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7473 (t (goto-char (point-min))
7474 (if (or (org-search-not-link re0 nil t)
7475 (org-search-not-link re1 nil t)
7476 (org-search-not-link re2 nil t)
7477 (org-search-not-link re2a nil t)
7478 (org-search-not-link re3 nil t)
7479 (org-search-not-link re4 nil t)
7480 (org-search-not-link re5 nil t)
7482 (goto-char (match-beginning 0))
7483 (goto-char pos)
7484 (error "No match")))))
7486 ;; Normal string-search
7487 (goto-char (point-min))
7488 (if (search-forward s nil t)
7489 (goto-char (match-beginning 0))
7490 (error "No match"))))
7491 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7493 (defun org-search-not-link (&rest args)
7494 "Execute `re-search-forward', but only accept matches that are not a link."
7495 (catch 'exit
7496 (let ((pos (point)) p1)
7497 (while (apply 're-search-forward args)
7498 (setq p1 (point))
7499 (if (not (save-match-data
7500 (and (re-search-backward "\\[\\[" nil t)
7501 (looking-at org-bracket-link-regexp)
7502 (<= (match-beginning 0) p1)
7503 (>= (match-end 0) p1))))
7504 (progn (goto-char (match-end 0))
7505 (throw 'exit (point)))
7506 (goto-char (match-end 0)))))))
7508 (defun org-do-occur (regexp &optional cleanup)
7509 "Call the Emacs command `occur'.
7510 If CLEANUP is non-nil, remove the printout of the regular expression
7511 in the *Occur* buffer. This is useful if the regex is long and not useful
7512 to read."
7513 (occur regexp)
7514 (when cleanup
7515 (let ((cwin (selected-window)) win beg end)
7516 (when (setq win (get-buffer-window "*Occur*"))
7517 (select-window win))
7518 (goto-char (point-min))
7519 (when (re-search-forward "match[a-z]+" nil t)
7520 (setq beg (match-end 0))
7521 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7522 (setq end (1- (match-beginning 0)))))
7523 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7524 (goto-char (point-min))
7525 (select-window cwin))))
7527 (defvar org-mark-ring nil
7528 "Mark ring for positions before jumps in Org-mode.")
7529 (defvar org-mark-ring-last-goto nil
7530 "Last position in the mark ring used to go back.")
7531 ;; Fill and close the ring
7532 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7533 (loop for i from 1 to org-mark-ring-length do
7534 (push (make-marker) org-mark-ring))
7535 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7536 org-mark-ring)
7538 (defun org-mark-ring-push (&optional pos buffer)
7539 "Put the current position or POS into the mark ring and rotate it."
7540 (interactive)
7541 (setq pos (or pos (point)))
7542 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7543 (move-marker (car org-mark-ring)
7544 (or pos (point))
7545 (or buffer (current-buffer)))
7546 (message
7547 (substitute-command-keys
7548 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7550 (defun org-mark-ring-goto (&optional n)
7551 "Jump to the previous position in the mark ring.
7552 With prefix arg N, jump back that many stored positions. When
7553 called several times in succession, walk through the entire ring.
7554 Org-mode commands jumping to a different position in the current file,
7555 or to another Org-mode file, automatically push the old position
7556 onto the ring."
7557 (interactive "p")
7558 (let (p m)
7559 (if (eq last-command this-command)
7560 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7561 (setq p org-mark-ring))
7562 (setq org-mark-ring-last-goto p)
7563 (setq m (car p))
7564 (switch-to-buffer (marker-buffer m))
7565 (goto-char m)
7566 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7568 (defun org-camel-to-words (s)
7569 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7570 (let ((case-fold-search nil)
7571 words)
7572 (while (string-match "[a-z][A-Z]" s)
7573 (push (substring s 0 (1+ (match-beginning 0))) words)
7574 (setq s (substring s (1+ (match-beginning 0)))))
7575 (nreverse (cons s words))))
7577 (defun org-remove-angle-brackets (s)
7578 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7579 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7581 (defun org-add-angle-brackets (s)
7582 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7583 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7586 (defun org-follow-bbdb-link (name)
7587 "Follow a BBDB link to NAME."
7588 (require 'bbdb)
7589 (let ((inhibit-redisplay t)
7590 (bbdb-electric-p nil))
7591 (catch 'exit
7592 ;; Exact match on name
7593 (bbdb-name (concat "\\`" name "\\'") nil)
7594 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7595 ;; Exact match on name
7596 (bbdb-company (concat "\\`" name "\\'") nil)
7597 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7598 ;; Partial match on name
7599 (bbdb-name name nil)
7600 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7601 ;; Partial match on company
7602 (bbdb-company name nil)
7603 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7604 ;; General match including network address and notes
7605 (bbdb name nil)
7606 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7607 (delete-window (get-buffer-window "*BBDB*"))
7608 (error "No matching BBDB record")))))
7610 (defun org-follow-gnus-link (&optional group article)
7611 "Follow a Gnus link to GROUP and ARTICLE."
7612 (require 'gnus)
7613 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7614 (if group (gnus-fetch-group group))
7615 (if article
7616 (or (gnus-summary-goto-article article nil 'force)
7617 (if (fboundp 'gnus-summary-insert-cached-articles)
7618 (progn
7619 (gnus-summary-insert-cached-articles)
7620 (gnus-summary-goto-article article nil 'force))
7621 (message "Message could not be found.")))))
7623 (defun org-follow-vm-link (&optional folder article readonly)
7624 "Follow a VM link to FOLDER and ARTICLE."
7625 (require 'vm)
7626 (setq article (org-add-angle-brackets article))
7627 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7628 ;; ange-ftp or efs or tramp access
7629 (let ((user (or (match-string 1 folder) (user-login-name)))
7630 (host (match-string 2 folder))
7631 (file (match-string 3 folder)))
7632 (cond
7633 ((featurep 'tramp)
7634 ;; use tramp to access the file
7635 (if (featurep 'xemacs)
7636 (setq folder (format "[%s@%s]%s" user host file))
7637 (setq folder (format "/%s@%s:%s" user host file))))
7639 ;; use ange-ftp or efs
7640 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7641 (setq folder (format "/%s@%s:%s" user host file))))))
7642 (when folder
7643 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7644 (sit-for 0.1)
7645 (when article
7646 (vm-select-folder-buffer)
7647 (widen)
7648 (let ((case-fold-search t))
7649 (goto-char (point-min))
7650 (if (not (re-search-forward
7651 (concat "^" "message-id: *" (regexp-quote article))))
7652 (error "Could not find the specified message in this folder"))
7653 (vm-isearch-update)
7654 (vm-isearch-narrow)
7655 (vm-beginning-of-message)
7656 (vm-summarize)))))
7658 (defun org-follow-wl-link (folder article)
7659 "Follow a Wanderlust link to FOLDER and ARTICLE."
7660 (setq article (org-add-angle-brackets article))
7661 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7662 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7663 (wl-summary-redisplay))
7665 (defun org-follow-rmail-link (folder article)
7666 "Follow an RMAIL link to FOLDER and ARTICLE."
7667 (setq article (org-add-angle-brackets article))
7668 (let (message-number)
7669 (save-excursion
7670 (save-window-excursion
7671 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7672 (setq message-number
7673 (save-restriction
7674 (widen)
7675 (goto-char (point-max))
7676 (if (re-search-backward
7677 (concat "^Message-ID:\\s-+" (regexp-quote
7678 (or article "")))
7679 nil t)
7680 (rmail-what-message))))))
7681 (if message-number
7682 (progn
7683 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7684 (rmail-show-message message-number)
7685 message-number)
7686 (error "Message not found"))))
7688 ;; mh-e integration based on planner-mode
7689 (defun org-mhe-get-message-real-folder ()
7690 "Return the name of the current message real folder, so if you use
7691 sequences, it will now work."
7692 (save-excursion
7693 (let* ((folder
7694 (if (equal major-mode 'mh-folder-mode)
7695 mh-current-folder
7696 ;; Refer to the show buffer
7697 mh-show-folder-buffer))
7698 (end-index
7699 (if (boundp 'mh-index-folder)
7700 (min (length mh-index-folder) (length folder))))
7702 ;; a simple test on mh-index-data does not work, because
7703 ;; mh-index-data is always nil in a show buffer.
7704 (if (and (boundp 'mh-index-folder)
7705 (string= mh-index-folder (substring folder 0 end-index)))
7706 (if (equal major-mode 'mh-show-mode)
7707 (save-window-excursion
7708 (when (buffer-live-p (get-buffer folder))
7709 (progn
7710 (pop-to-buffer folder)
7711 (org-mhe-get-message-folder-from-index)
7714 (org-mhe-get-message-folder-from-index)
7716 folder
7720 (defun org-mhe-get-message-folder-from-index ()
7721 "Returns the name of the message folder in a index folder buffer."
7722 (save-excursion
7723 (mh-index-previous-folder)
7724 (re-search-forward "^\\(+.*\\)$" nil t)
7725 (message (match-string 1))))
7727 (defun org-mhe-get-message-folder ()
7728 "Return the name of the current message folder. Be careful if you
7729 use sequences."
7730 (save-excursion
7731 (if (equal major-mode 'mh-folder-mode)
7732 mh-current-folder
7733 ;; Refer to the show buffer
7734 mh-show-folder-buffer)))
7736 (defun org-mhe-get-message-num ()
7737 "Return the number of the current message. Be careful if you
7738 use sequences."
7739 (save-excursion
7740 (if (equal major-mode 'mh-folder-mode)
7741 (mh-get-msg-num nil)
7742 ;; Refer to the show buffer
7743 (mh-show-buffer-message-number))))
7745 (defun org-mhe-get-header (header)
7746 "Return a header of the message in folder mode. This will create a
7747 show buffer for the corresponding message. If you have a more clever
7748 idea..."
7749 (let* ((folder (org-mhe-get-message-folder))
7750 (num (org-mhe-get-message-num))
7751 (buffer (get-buffer-create (concat "show-" folder)))
7752 (header-field))
7753 (with-current-buffer buffer
7754 (mh-display-msg num folder)
7755 (if (equal major-mode 'mh-folder-mode)
7756 (mh-header-display)
7757 (mh-show-header-display))
7758 (set-buffer buffer)
7759 (setq header-field (mh-get-header-field header))
7760 (if (equal major-mode 'mh-folder-mode)
7761 (mh-show)
7762 (mh-show-show))
7763 header-field)))
7765 (defun org-follow-mhe-link (folder article)
7766 "Follow an MHE link to FOLDER and ARTICLE.
7767 If ARTICLE is nil FOLDER is shown. If the configuration variable
7768 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7769 ARTICLE is searched in all folders. Indexed searches (swish++,
7770 namazu, and others supported by MH-E) will always search in all
7771 folders."
7772 (require 'mh-e)
7773 (require 'mh-search)
7774 (require 'mh-utils)
7775 (mh-find-path)
7776 (if (not article)
7777 (mh-visit-folder (mh-normalize-folder-name folder))
7778 (setq article (org-add-angle-brackets article))
7779 (mh-search-choose)
7780 (if (equal mh-searcher 'pick)
7781 (progn
7782 (mh-search folder (list "--message-id" article))
7783 (when (and org-mhe-search-all-folders
7784 (not (org-mhe-get-message-real-folder)))
7785 (kill-this-buffer)
7786 (mh-search "+" (list "--message-id" article))))
7787 (mh-search "+" article))
7788 (if (org-mhe-get-message-real-folder)
7789 (mh-show-msg 1)
7790 (kill-this-buffer)
7791 (error "Message not found"))))
7793 (defun org-upgrade-old-links (&optional query-description)
7794 "Transfer old <...> style links to new [[...]] style links.
7795 With arg query-description, ask at each match for a description text to use
7796 for this link."
7797 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
7798 (save-excursion
7799 (goto-char (point-min))
7800 (let ((re (concat "\\([^[]\\)<\\("
7801 "\\(" (mapconcat 'identity org-link-types "\\|")
7802 "\\):"
7803 "[^" org-non-link-chars "]+\\)>"))
7804 l1 l2 (cnt 0))
7805 (while (re-search-forward re nil t)
7806 (setq cnt (1+ cnt)
7807 l1 (org-match-string-no-properties 2)
7808 l2 (save-match-data (org-link-escape l1)))
7809 (when query-description (setq l1 (read-string "Desc: " l1)))
7810 (if (equal l1 l2)
7811 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
7812 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
7813 (message "%d matches have beed treated" cnt))))
7815 (defun org-open-file (path &optional in-emacs line search)
7816 "Open the file at PATH.
7817 First, this expands any special file name abbreviations. Then the
7818 configuration variable `org-file-apps' is checked if it contains an
7819 entry for this file type, and if yes, the corresponding command is launched.
7820 If no application is found, Emacs simply visits the file.
7821 With optional argument IN-EMACS, Emacs will visit the file.
7822 Optional LINE specifies a line to go to, optional SEARCH a string to
7823 search for. If LINE or SEARCH is given, the file will always be
7824 opened in Emacs.
7825 If the file does not exist, an error is thrown."
7826 (setq in-emacs (or in-emacs line search))
7827 (let* ((file (if (equal path "")
7828 buffer-file-name
7829 (convert-standard-filename (org-expand-file-name path))))
7830 (dirp (file-directory-p file))
7831 (dfile (downcase file))
7832 (old-buffer (current-buffer))
7833 (old-pos (point))
7834 (old-mode major-mode)
7835 ext cmd apps)
7836 (if (and (not (file-exists-p file))
7837 (not org-open-non-existing-files))
7838 (error "No such file: %s" file))
7839 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7840 (setq ext (match-string 1 dfile))
7841 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7842 (setq ext (match-string 1 dfile))))
7843 (setq apps (append org-file-apps (org-default-apps)))
7844 (if in-emacs
7845 (setq cmd 'emacs)
7846 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7847 (cdr (assoc ext apps))
7848 (cdr (assoc t apps)))))
7849 (when (eq cmd 'mailcap)
7850 (require 'mailcap)
7851 (mailcap-parse-mailcaps)
7852 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7853 (command (mailcap-mime-info mime-type)))
7854 (if (stringp command)
7855 (setq cmd command)
7856 (setq cmd 'emacs))))
7857 (cond
7858 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7859 ;; Normalize use of quote, this can vary.
7860 (if (string-match "['\"]%s['\"]" cmd)
7861 (setq cmd (replace-match "'%s'" t t cmd)))
7862 (setq cmd (format cmd file))
7863 (save-window-excursion
7864 (shell-command (concat cmd " &"))))
7865 ((or (stringp cmd)
7866 (eq cmd 'emacs))
7867 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7868 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7869 (if line (goto-line line)
7870 (if search (org-link-search search))))
7871 ((consp cmd)
7872 (eval cmd))
7873 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7874 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7875 (or (not (equal old-buffer (current-buffer)))
7876 (not (equal old-pos (point))))
7877 (org-mark-ring-push old-pos old-buffer))))
7879 (defun org-default-apps ()
7880 "Return the default applications for this operating system."
7881 (cond
7882 ((eq system-type 'darwin)
7883 org-file-apps-defaults-macosx)
7884 ((eq system-type 'windows-nt)
7885 org-file-apps-defaults-windowsnt)
7886 (t org-file-apps-defaults-gnu)))
7888 (defun org-expand-file-name (path)
7889 "Replace special path abbreviations and expand the file name."
7890 (expand-file-name path))
7893 (defvar org-insert-link-history nil
7894 "Minibuffer history for links inserted with `org-insert-link'.")
7896 (defvar org-stored-links nil
7897 "Contains the links stored with `org-store-link'.")
7899 ;;;###autoload
7900 (defun org-store-link (arg)
7901 "\\<org-mode-map>Store an org-link to the current location.
7902 This link can later be inserted into an org-buffer with
7903 \\[org-insert-link].
7904 For some link types, a prefix arg is interpreted:
7905 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7906 For file links, arg negates `org-context-in-file-links'."
7907 (interactive "P")
7908 (let (link cpltxt desc txt (pos (point)))
7909 (cond
7911 ((eq major-mode 'bbdb-mode)
7912 (setq cpltxt (concat
7913 "bbdb:"
7914 (or (bbdb-record-name (bbdb-current-record))
7915 (bbdb-record-company (bbdb-current-record))))
7916 link (org-make-link cpltxt)))
7918 ((eq major-mode 'calendar-mode)
7919 (let ((cd (calendar-cursor-to-date)))
7920 (setq link
7921 (format-time-string
7922 (car org-time-stamp-formats)
7923 (apply 'encode-time
7924 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7925 nil nil nil))))))
7927 ((or (eq major-mode 'vm-summary-mode)
7928 (eq major-mode 'vm-presentation-mode))
7929 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7930 (vm-follow-summary-cursor)
7931 (save-excursion
7932 (vm-select-folder-buffer)
7933 (let* ((message (car vm-message-pointer))
7934 (folder buffer-file-name)
7935 (subject (vm-su-subject message))
7936 (author (vm-su-full-name message))
7937 (message-id (vm-su-message-id message)))
7938 (setq message-id (org-remove-angle-brackets message-id))
7939 (setq folder (abbreviate-file-name folder))
7940 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7941 folder)
7942 (setq folder (replace-match "" t t folder)))
7943 (setq cpltxt (concat author " on: " subject))
7944 (setq link (org-make-link "vm:" folder "#" message-id)))))
7946 ((eq major-mode 'wl-summary-mode)
7947 (let* ((msgnum (wl-summary-message-number))
7948 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7949 msgnum 'message-id))
7950 (wl-message-entity (elmo-msgdb-overview-get-entity
7951 msgnum (wl-summary-buffer-msgdb)))
7952 (author (wl-summary-line-from)) ; FIXME: correct?
7953 (subject "???")) ; FIXME:
7954 (setq message-id (org-remove-angle-brackets message-id))
7955 (setq cpltxt (concat author " on: " subject))
7956 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
7957 "#" message-id))))
7959 ((or (equal major-mode 'mh-folder-mode)
7960 (equal major-mode 'mh-show-mode))
7961 (let ((from-header (org-mhe-get-header "From:"))
7962 (to-header (org-mhe-get-header "To:"))
7963 (subject (org-mhe-get-header "Subject:")))
7964 (setq cpltxt (concat from-header " on: " subject))
7965 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
7966 (org-remove-angle-brackets
7967 (org-mhe-get-header "Message-Id:"))))))
7969 ((eq major-mode 'rmail-mode)
7970 (save-excursion
7971 (save-restriction
7972 (rmail-narrow-to-non-pruned-header)
7973 (let ((folder buffer-file-name)
7974 (message-id (mail-fetch-field "message-id"))
7975 (author (mail-fetch-field "from"))
7976 (subject (mail-fetch-field "subject")))
7977 (setq message-id (org-remove-angle-brackets message-id))
7978 (setq cpltxt (concat author " on: " subject))
7979 (setq link (org-make-link "rmail:" folder "#" message-id))))))
7981 ((eq major-mode 'gnus-group-mode)
7982 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7983 (gnus-group-group-name)) ; version
7984 ((fboundp 'gnus-group-name)
7985 (gnus-group-name))
7986 (t "???"))))
7987 (setq cpltxt (concat
7988 (if (org-xor arg org-usenet-links-prefer-google)
7989 "http://groups.google.com/groups?group="
7990 "gnus:")
7991 group)
7992 link (org-make-link cpltxt))))
7994 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7995 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7996 (gnus-summary-beginning-of-article)
7997 (let* ((group (car gnus-article-current))
7998 (article (cdr gnus-article-current))
7999 (header (gnus-summary-article-header article))
8000 (author (mail-header-from header))
8001 (message-id (mail-header-id header))
8002 (date (mail-header-date header))
8003 (subject (gnus-summary-subject-string)))
8004 (setq cpltxt (concat author " on: " subject))
8005 (if (org-xor arg org-usenet-links-prefer-google)
8006 (setq link
8007 (concat
8008 cpltxt "\n "
8009 (format "http://groups.google.com/groups?as_umsgid=%s"
8010 (org-fixup-message-id-for-http message-id))))
8011 (setq link (org-make-link "gnus:" group
8012 "#" (number-to-string article))))))
8014 ((eq major-mode 'w3-mode)
8015 (setq cpltxt (url-view-url t)
8016 link (org-make-link cpltxt)))
8017 ((eq major-mode 'w3m-mode)
8018 (setq cpltxt w3m-current-url
8019 link (org-make-link cpltxt)))
8021 ((eq major-mode 'org-mode)
8022 ;; Just link to current headline
8023 (setq cpltxt (concat "file:"
8024 (abbreviate-file-name buffer-file-name)))
8025 ;; Add a context search string
8026 (when (org-xor org-context-in-file-links arg)
8027 ;; Check if we are on a target
8028 (if (save-excursion
8029 (skip-chars-forward "^>\n\r")
8030 (and (re-search-backward "<<" nil t)
8031 (looking-at "<<\\(.*?\\)>>")
8032 (<= (match-beginning 0) pos)
8033 (>= (match-end 0) pos)))
8034 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8035 (setq txt (cond
8036 ((org-on-heading-p) nil)
8037 ((org-region-active-p)
8038 (buffer-substring (region-beginning) (region-end)))
8039 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8040 (setq cpltxt
8041 (concat cpltxt "::"
8042 (if org-file-link-context-use-camel-case
8043 (org-make-org-heading-camel txt)
8044 (org-make-org-heading-search-string txt)))
8045 desc "NONE")))
8046 (if (string-match "::\\'" cpltxt)
8047 (setq cpltxt (substring cpltxt 0 -2)))
8048 (setq link (org-make-link cpltxt)))
8050 (buffer-file-name
8051 ;; Just link to this file here.
8052 (setq cpltxt (concat "file:"
8053 (abbreviate-file-name buffer-file-name)))
8054 ;; Add a context string
8055 (when (org-xor org-context-in-file-links arg)
8056 (setq txt (if (org-region-active-p)
8057 (buffer-substring (region-beginning) (region-end))
8058 (buffer-substring (point-at-bol) (point-at-eol))))
8059 (setq cpltxt
8060 (concat cpltxt "::"
8061 (if org-file-link-context-use-camel-case
8062 (org-make-org-heading-camel txt)
8063 (org-make-org-heading-search-string txt)))
8064 desc "NONE"))
8065 (setq link (org-make-link cpltxt)))
8067 ((interactive-p)
8068 (error "Cannot link to a buffer which is not visiting a file"))
8070 (t (setq link nil)))
8072 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8073 (setq link (or link cpltxt)
8074 desc (or desc cpltxt))
8075 (if (equal desc "NONE") (setq desc nil))
8077 (if (and (interactive-p) link)
8078 (progn
8079 (setq org-stored-links
8080 (cons (list cpltxt link desc) org-stored-links))
8081 (message "Stored: %s" (or cpltxt link)))
8082 (org-make-link-string link desc))))
8084 (defun org-make-org-heading-search-string (&optional string heading)
8085 "Make search string for STRING or current headline."
8086 (interactive)
8087 (let ((s (or string (org-get-heading))))
8088 (unless (and string (not heading))
8089 ;; We are using a headline, clean up garbage in there.
8090 (if (string-match org-todo-regexp s)
8091 (setq s (replace-match "" t t s)))
8092 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8093 (setq s (replace-match "" t t s)))
8094 (setq s (org-trim s))
8095 (if (string-match (concat "^\\(" org-quote-string "\\|"
8096 org-comment-string "\\)") s)
8097 (setq s (replace-match "" t t s)))
8098 (while (string-match org-ts-regexp s)
8099 (setq s (replace-match "" t t s))))
8100 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8101 (setq s (replace-match " " t t s)))
8102 (or string (setq s (concat "*" s))) ; Add * for headlines
8103 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8105 (defun org-make-org-heading-camel (&optional string heading)
8106 "Make a CamelCase string for STRING or the current headline."
8107 (interactive)
8108 (let ((s (or string (org-get-heading))))
8109 (unless (and string (not heading))
8110 ;; We are using a headline, clean up garbage in there.
8111 (if (string-match org-todo-regexp s)
8112 (setq s (replace-match "" t t s)))
8113 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8114 (setq s (replace-match "" t t s)))
8115 (setq s (org-trim s))
8116 (if (string-match (concat "^\\(" org-quote-string "\\|"
8117 org-comment-string "\\)") s)
8118 (setq s (replace-match "" t t s)))
8119 (while (string-match org-ts-regexp s)
8120 (setq s (replace-match "" t t s))))
8121 (while (string-match "[^a-zA-Z_ \t]+" s)
8122 (setq s (replace-match " " t t s)))
8123 (or string (setq s (concat "*" s))) ; Add * for headlines
8124 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8126 (defun org-make-link (&rest strings)
8127 "Concatenate STRINGS, format resulting string with `org-link-format'."
8128 (format org-link-format (apply 'concat strings)))
8130 (defun org-make-link-string (link &optional description)
8131 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8132 (if (eq org-link-style 'plain)
8133 (if (equal description link)
8134 link
8135 (concat description "\n" link))
8136 (when (stringp description)
8137 ;; Remove brackets from the description, they are fatal.
8138 (while (string-match "\\[\\|\\]" description)
8139 (setq description (replace-match "" t t description))))
8140 (when (equal (org-link-escape link) description)
8141 ;; No description needed, it is identical
8142 (setq description nil))
8143 (when (and (not description)
8144 (not (equal link (org-link-escape link))))
8145 (setq description link))
8146 (concat "[[" (org-link-escape link) "]"
8147 (if description (concat "[" description "]") "")
8148 "]")))
8150 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8151 "Association list of escapes for some characters problematic in links.")
8153 (defun org-link-escape (text)
8154 "Escape charaters in TEXT that are problematic for links."
8155 (when text
8156 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8157 org-link-escape-chars "\\|")))
8158 (while (string-match re text)
8159 (setq text
8160 (replace-match
8161 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8162 t t text)))
8163 text)))
8165 (defun org-link-unescape (text)
8166 "Reverse the action of `org-link-escape'."
8167 (when text
8168 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8169 org-link-escape-chars "\\|")))
8170 (while (string-match re text)
8171 (setq text
8172 (replace-match
8173 (car (rassoc (match-string 0 text) org-link-escape-chars))
8174 t t text)))
8175 text)))
8177 (defun org-xor (a b)
8178 "Exclusive or."
8179 (if a (not b) b))
8181 (defun org-get-header (header)
8182 "Find a header field in the current buffer."
8183 (save-excursion
8184 (goto-char (point-min))
8185 (let ((case-fold-search t) s)
8186 (cond
8187 ((eq header 'from)
8188 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8189 (setq s (match-string 1)))
8190 (while (string-match "\"" s)
8191 (setq s (replace-match "" t t s)))
8192 (if (string-match "[<(].*" s)
8193 (setq s (replace-match "" t t s))))
8194 ((eq header 'message-id)
8195 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8196 (setq s (match-string 1))))
8197 ((eq header 'subject)
8198 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8199 (setq s (match-string 1)))))
8200 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8201 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8202 s)))
8205 (defun org-fixup-message-id-for-http (s)
8206 "Replace special characters in a message id, so it can be used in an http query."
8207 (while (string-match "<" s)
8208 (setq s (replace-match "%3C" t t s)))
8209 (while (string-match ">" s)
8210 (setq s (replace-match "%3E" t t s)))
8211 (while (string-match "@" s)
8212 (setq s (replace-match "%40" t t s)))
8215 (defun org-insert-link (&optional complete-file)
8216 "Insert a link. At the prompt, enter the link.
8218 Completion can be used to select a link previously stored with
8219 `org-store-link'. When the empty string is entered (i.e. if you just
8220 press RET at the prompt), the link defaults to the most recently
8221 stored link. As SPC triggers completion in the minibuffer, you need to
8222 use M-SPC or C-q SPC to force the insertion of a space character.
8224 You will also be prompted for a description, and if one is given, it will
8225 be displayed in the buffer instead of the link.
8227 If there is already a link at point, this command will allow you to edit link
8228 and description parts.
8230 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8231 selected using completion. The path to the file will be relative to
8232 the current directory if the file is in the current directory or a
8233 subdirectory. Otherwise, the link will be the absolute path as
8234 completed in the minibuffer (i.e. normally ~/path/to/file).
8236 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8237 is in the current directory or below."
8238 (interactive "P")
8239 (let (link desc entry remove file (pos (point)))
8240 (cond
8241 ((save-excursion
8242 (skip-chars-forward "^]\n\r")
8243 (and (re-search-backward "\\[\\[" nil t)
8244 (looking-at org-bracket-link-regexp)
8245 (<= (match-beginning 0) pos)
8246 (>= (match-end 0) pos)))
8247 ;; We do have a link at point, and we are going to edit it.
8248 (setq remove (list (match-beginning 0) (match-end 0)))
8249 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8250 (setq link (read-string "Link: "
8251 (org-link-unescape
8252 (org-match-string-no-properties 1)))))
8253 (complete-file
8254 ;; Completing read for file names.
8255 (setq file (read-file-name "File: "))
8256 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8257 (pwd1 (file-name-as-directory (abbreviate-file-name
8258 (expand-file-name ".")))))
8259 (cond
8260 ((equal complete-file '(16))
8261 (setq link (org-make-link
8262 "file:"
8263 (abbreviate-file-name (expand-file-name file)))))
8264 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8265 (setq link (org-make-link "file:" (match-string 1 file))))
8266 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8267 (expand-file-name file))
8268 (setq link (org-make-link
8269 "file:" (match-string 1 (expand-file-name file)))))
8270 (t (setq link (org-make-link "file:" file))))))
8272 ;; Read link, with completion for stored links.
8273 (setq link (org-completing-read
8274 "Link: " org-stored-links nil nil nil
8275 org-insert-link-history
8276 (or (car (car org-stored-links)))))
8277 (setq entry (assoc link org-stored-links))
8278 (if (not org-keep-stored-link-after-insertion)
8279 (setq org-stored-links (delq (assoc link org-stored-links)
8280 org-stored-links)))
8281 (setq link (if entry (nth 1 entry) link)
8282 desc (or desc (nth 2 entry)))))
8284 (if (string-match org-plain-link-re link)
8285 ;; URL-like link, normalize the use of angular brackets.
8286 (setq link (org-make-link (org-remove-angle-brackets link))))
8288 ;; Check if we are linking to the current file. If yes, simplify the link.
8289 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8290 (let* ((path (match-string 1 link))
8291 (case-fold-search nil)
8292 (search (match-string 2 link)))
8293 (when (save-match-data
8294 (equal (file-truename buffer-file-name)
8295 (file-truename path)))
8296 ;; We are linking to this same file, with a search option
8297 (setq link search))))
8298 (setq desc (read-string "Description: " desc))
8299 (unless (string-match "\\S-" desc) (setq desc nil))
8300 (if remove (apply 'delete-region remove))
8301 (insert (org-make-link-string link desc))))
8303 (defun org-completing-read (&rest args)
8304 (let ((minibuffer-local-completion-map
8305 (copy-keymap minibuffer-local-completion-map)))
8306 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8307 (apply 'completing-read args)))
8309 ;;; Hooks for remember.el
8311 (defvar org-finish-function nil)
8313 ;;;###autoload
8314 (defun org-remember-annotation ()
8315 "Return a link to the current location as an annotation for remember.el.
8316 If you are using Org-mode files as target for data storage with
8317 remember.el, then the annotations should include a link compatible with the
8318 conventions in Org-mode. This function returns such a link."
8319 (org-store-link nil))
8321 (defconst org-remember-help
8322 "Select a destination location for the note.
8323 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8324 RET at beg-of-buf -> Append to file as level 2 headline
8325 RET on headline -> Store as sublevel entry to current headline
8326 <left>/<right> -> before/after current headline, same headings level")
8328 ;;;###autoload
8329 (defun org-remember-apply-template ()
8330 "Initialize *remember* buffer with template, invode `org-mode'.
8331 This function should be placed into `remember-mode-hook' and in fact requires
8332 to be run from that hook to fucntion properly."
8333 (when org-remember-templates
8334 (let* ((entry (if (= (length org-remember-templates) 1)
8335 (cdar org-remember-templates)
8336 (message "Select template: %s"
8337 (mapconcat
8338 (lambda (x) (char-to-string (car x)))
8339 org-remember-templates " "))
8340 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8341 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8342 (file (if (consp (cdr entry)) (nth 2 entry)))
8343 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8344 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8345 (v-u (concat "[" (substring v-t 1 -1) "]"))
8346 (v-U (concat "[" (substring v-T 1 -1) "]"))
8347 (v-a annotation) ; defined in `remember-mode'
8348 (v-i initial) ; defined in `remember-mode'
8349 (v-n user-full-name)
8351 (unless tpl (setq tpl "") (message "No template") (ding))
8352 (insert tpl) (goto-char (point-min))
8353 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8354 (when (and initial (equal (match-string 0) "%i"))
8355 (save-match-data
8356 (let* ((lead (buffer-substring
8357 (point-at-bol) (match-beginning 0))))
8358 (setq v-i (mapconcat 'identity
8359 (org-split-string initial "\n")
8360 (concat "\n" lead))))))
8361 (replace-match
8362 (or (eval (intern (concat "v-" (match-string 1)))) "")
8363 t t))
8364 (let ((org-startup-folded nil)
8365 (org-startup-with-deadline-check nil))
8366 (org-mode))
8367 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8368 (set (make-local-variable 'org-default-notes-file) file))
8369 (goto-char (point-min))
8370 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8371 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8373 ;;;###autoload
8374 (defun org-remember-handler ()
8375 "Store stuff from remember.el into an org file.
8376 First prompts for an org file. If the user just presses return, the value
8377 of `org-default-notes-file' is used.
8378 Then the command offers the headings tree of the selected file in order to
8379 file the text at a specific location.
8380 You can either immediately press RET to get the note appended to the
8381 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8382 find a better place. Then press RET or <left> or <right> in insert the note.
8384 Key Cursor position Note gets inserted
8385 -----------------------------------------------------------------------------
8386 RET buffer-start as level 2 heading at end of file
8387 RET on headline as sublevel of the heading at cursor
8388 RET no heading at cursor position, level taken from context.
8389 Or use prefix arg to specify level manually.
8390 <left> on headline as same level, before current heading
8391 <right> on headline as same level, after current heading
8393 So the fastest way to store the note is to press RET RET to append it to
8394 the default file. This way your current train of thought is not
8395 interrupted, in accordance with the principles of remember.el. But with
8396 little extra effort, you can push it directly to the correct location.
8398 Before being stored away, the function ensures that the text has a
8399 headline, i.e. a first line that starts with a \"*\". If not, a headline
8400 is constructed from the current date and some additional data.
8402 If the variable `org-adapt-indentation' is non-nil, the entire text is
8403 also indented so that it starts in the same column as the headline
8404 \(i.e. after the stars).
8406 See also the variable `org-reverse-note-order'."
8407 (catch 'quit
8408 (let* ((txt (buffer-substring (point-min) (point-max)))
8409 (fastp current-prefix-arg)
8410 (file (if fastp org-default-notes-file (org-get-org-file)))
8411 (visiting (find-buffer-visiting file))
8412 (org-startup-with-deadline-check nil)
8413 (org-startup-folded nil)
8414 (org-startup-align-all-tables nil)
8415 spos level indent reversed)
8416 ;; Modify text so that it becomes a nice subtree which can be inserted
8417 ;; into an org tree.
8418 (let* ((lines (split-string txt "\n"))
8419 first)
8420 ;; remove empty lines at the beginning
8421 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8422 (setq lines (cdr lines)))
8423 (setq first (car lines) lines (cdr lines))
8424 (if (string-match "^\\*+" first)
8425 ;; Is already a headline
8426 (setq indent nil)
8427 ;; We need to add a headline: Use time and first buffer line
8428 (setq lines (cons first lines)
8429 first (concat "* " (current-time-string)
8430 " (" (remember-buffer-desc) ")")
8431 indent " "))
8432 (if (and org-adapt-indentation indent)
8433 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8434 (setq txt (concat first "\n"
8435 (mapconcat 'identity lines "\n"))))
8436 ;; Find the file
8437 (if (not visiting)
8438 (find-file-noselect file))
8439 (with-current-buffer (get-file-buffer file)
8440 (setq reversed (org-notes-order-reversed-p))
8441 (save-excursion
8442 (save-restriction
8443 (widen)
8444 ;; Ask the User for a location
8445 (setq spos (if fastp 1 (org-get-location
8446 (current-buffer)
8447 org-remember-help)))
8448 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8449 ; not handle this note
8450 (goto-char spos)
8451 (cond ((bobp)
8452 ;; Put it at the start or end, as level 2
8453 (save-restriction
8454 (widen)
8455 (goto-char (if reversed (point-min) (point-max)))
8456 (if (not (bolp)) (newline))
8457 (org-paste-subtree 2 txt)))
8458 ((and (org-on-heading-p nil) (not current-prefix-arg))
8459 ;; Put it below this entry, at the beg/end of the subtree
8460 (org-back-to-heading)
8461 (setq level (funcall outline-level))
8462 (if reversed
8463 (outline-end-of-heading)
8464 (outline-end-of-subtree))
8465 (if (not (bolp)) (newline))
8466 (beginning-of-line 1)
8467 (org-paste-subtree (1+ level) txt))
8469 ;; Put it right there, with automatic level determined by
8470 ;; org-paste-subtree or from prefix arg
8471 (org-paste-subtree current-prefix-arg txt)))
8472 (when remember-save-after-remembering
8473 (save-buffer)
8474 (if (not visiting) (kill-buffer (current-buffer)))))))))
8475 t) ;; return t to indicate that we took care of this note.
8477 (defun org-get-org-file ()
8478 "Read a filename, with default directory `org-directory'."
8479 (let ((default (or org-default-notes-file remember-data-file)))
8480 (read-file-name (format "File name [%s]: " default)
8481 (file-name-as-directory org-directory)
8482 default)))
8484 (defun org-notes-order-reversed-p ()
8485 "Check if the current file should receive notes in reversed order."
8486 (cond
8487 ((not org-reverse-note-order) nil)
8488 ((eq t org-reverse-note-order) t)
8489 ((not (listp org-reverse-note-order)) nil)
8490 (t (catch 'exit
8491 (let ((all org-reverse-note-order)
8492 entry)
8493 (while (setq entry (pop all))
8494 (if (string-match (car entry) buffer-file-name)
8495 (throw 'exit (cdr entry))))
8496 nil)))))
8498 ;;; Tables
8500 ;; Watch out: Here we are talking about two different kind of tables.
8501 ;; Most of the code is for the tables created with the Org-mode table editor.
8502 ;; Sometimes, we talk about tables created and edited with the table.el
8503 ;; Emacs package. We call the former org-type tables, and the latter
8504 ;; table.el-type tables.
8507 (defun org-before-change-function (beg end)
8508 "Every change indicates that a table might need an update."
8509 (setq org-table-may-need-update t))
8511 (defconst org-table-line-regexp "^[ \t]*|"
8512 "Detects an org-type table line.")
8513 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8514 "Detects an org-type table line.")
8515 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8516 "Detects a table line marked for automatic recalculation.")
8517 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8518 "Detects a table line marked for automatic recalculation.")
8519 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8520 "Detects a table line marked for automatic recalculation.")
8521 (defconst org-table-hline-regexp "^[ \t]*|-"
8522 "Detects an org-type table hline.")
8523 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8524 "Detects a table-type table hline.")
8525 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8526 "Detects an org-type or table-type table.")
8527 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8528 "Searching from within a table (any type) this finds the first line
8529 outside the table.")
8530 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8531 "Searching from within a table (any type) this finds the first line
8532 outside the table.")
8534 (defun org-table-create-with-table.el ()
8535 "Use the table.el package to insert a new table.
8536 If there is already a table at point, convert between Org-mode tables
8537 and table.el tables."
8538 (interactive)
8539 (require 'table)
8540 (cond
8541 ((org-at-table.el-p)
8542 (if (y-or-n-p "Convert table to Org-mode table? ")
8543 (org-table-convert)))
8544 ((org-at-table-p)
8545 (if (y-or-n-p "Convert table to table.el table? ")
8546 (org-table-convert)))
8547 (t (call-interactively 'table-insert))))
8549 (defun org-table-create-or-convert-from-region (arg)
8550 "Convert region to table, or create an empty table.
8551 If there is an active region, convert it to a table. If there is no such
8552 region, create an empty table."
8553 (interactive "P")
8554 (if (org-region-active-p)
8555 (org-table-convert-region (region-beginning) (region-end) arg)
8556 (org-table-create arg)))
8558 (defun org-table-create (&optional size)
8559 "Query for a size and insert a table skeleton.
8560 SIZE is a string Columns x Rows like for example \"3x2\"."
8561 (interactive "P")
8562 (unless size
8563 (setq size (read-string
8564 (concat "Table size Columns x Rows [e.g. "
8565 org-table-default-size "]: ")
8566 "" nil org-table-default-size)))
8568 (let* ((pos (point))
8569 (indent (make-string (current-column) ?\ ))
8570 (split (org-split-string size " *x *"))
8571 (rows (string-to-number (nth 1 split)))
8572 (columns (string-to-number (car split)))
8573 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8574 "\n")))
8575 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8576 (point-at-bol) (point)))
8577 (beginning-of-line 1)
8578 (newline))
8579 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8580 (dotimes (i rows) (insert line))
8581 (goto-char pos)
8582 (if (> rows 1)
8583 ;; Insert a hline after the first row.
8584 (progn
8585 (end-of-line 1)
8586 (insert "\n|-")
8587 (goto-char pos)))
8588 (org-table-align)))
8590 (defun org-table-convert-region (beg0 end0 &optional nspace)
8591 "Convert region to a table.
8592 The region goes from BEG0 to END0, but these borders will be moved
8593 slightly, to make sure a beginning of line in the first line is included.
8594 When NSPACE is non-nil, it indicates the minimum number of spaces that
8595 separate columns (default: just one space)."
8596 (interactive "rP")
8597 (let* ((beg (min beg0 end0))
8598 (end (max beg0 end0))
8599 (tabsep t)
8601 (goto-char beg)
8602 (beginning-of-line 1)
8603 (setq beg (move-marker (make-marker) (point)))
8604 (goto-char end)
8605 (if (bolp) (backward-char 1) (end-of-line 1))
8606 (setq end (move-marker (make-marker) (point)))
8607 ;; Lets see if this is tab-separated material. If every nonempty line
8608 ;; contains a tab, we will assume that it is tab-separated material
8609 (if nspace
8610 (setq tabsep nil)
8611 (goto-char beg)
8612 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8613 (if nspace (setq tabsep nil))
8614 (if tabsep
8615 (setq re "^\\|\t")
8616 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8617 (max 1 (prefix-numeric-value nspace)))))
8618 (goto-char beg)
8619 (while (re-search-forward re end t)
8620 (replace-match "|" t t))
8621 (goto-char beg)
8622 (insert " ")
8623 (org-table-align)))
8625 (defun org-table-import (file arg)
8626 "Import FILE as a table.
8627 The file is assumed to be tab-separated. Such files can be produced by most
8628 spreadsheet and database applications. If no tabs (at least one per line)
8629 are found, lines will be split on whitespace into fields."
8630 (interactive "f\nP")
8631 (or (bolp) (newline))
8632 (let ((beg (point))
8633 (pm (point-max)))
8634 (insert-file-contents file)
8635 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8637 (defun org-table-export ()
8638 "Export table as a tab-separated file.
8639 Such a file can be imported into a spreadsheet program like Excel."
8640 (interactive)
8641 (let* ((beg (org-table-begin))
8642 (end (org-table-end))
8643 (table (buffer-substring beg end))
8644 (file (read-file-name "Export table to: "))
8645 buf)
8646 (unless (or (not (file-exists-p file))
8647 (y-or-n-p (format "Overwrite file %s? " file)))
8648 (error "Abort"))
8649 (with-current-buffer (find-file-noselect file)
8650 (setq buf (current-buffer))
8651 (erase-buffer)
8652 (fundamental-mode)
8653 (insert table)
8654 (goto-char (point-min))
8655 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8656 (replace-match "" t t)
8657 (end-of-line 1))
8658 (goto-char (point-min))
8659 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8660 (replace-match "" t t)
8661 (goto-char (min (1+ (point)) (point-max))))
8662 (goto-char (point-min))
8663 (while (re-search-forward "^-[-+]*$" nil t)
8664 (replace-match "")
8665 (if (looking-at "\n")
8666 (delete-char 1)))
8667 (goto-char (point-min))
8668 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8669 (replace-match "\t" t t))
8670 (save-buffer))
8671 (kill-buffer buf)))
8673 (defvar org-table-aligned-begin-marker (make-marker)
8674 "Marker at the beginning of the table last aligned.
8675 Used to check if cursor still is in that table, to minimize realignment.")
8676 (defvar org-table-aligned-end-marker (make-marker)
8677 "Marker at the end of the table last aligned.
8678 Used to check if cursor still is in that table, to minimize realignment.")
8679 (defvar org-table-last-alignment nil
8680 "List of flags for flushright alignment, from the last re-alignment.
8681 This is being used to correctly align a single field after TAB or RET.")
8682 (defvar org-table-last-column-widths nil
8683 "List of max width of fields in each column.
8684 This is being used to correctly align a single field after TAB or RET.")
8686 (defvar org-last-recalc-line nil)
8687 (defconst org-narrow-column-arrow "=>"
8688 "Used as display property in narrowed table columns.")
8690 (defun org-table-align ()
8691 "Align the table at point by aligning all vertical bars."
8692 (interactive)
8693 (let* (
8694 ;; Limits of table
8695 (beg (org-table-begin))
8696 (end (org-table-end))
8697 ;; Current cursor position
8698 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8699 (colpos (org-table-current-column))
8700 (winstart (window-start))
8701 text lines (new "") lengths l typenums ty fields maxfields i
8702 column
8703 (indent "") cnt frac
8704 rfmt hfmt
8705 (spaces '(1 . 1))
8706 (sp1 (car spaces))
8707 (sp2 (cdr spaces))
8708 (rfmt1 (concat
8709 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8710 (hfmt1 (concat
8711 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8712 emptystrings xx links narrow fmax fmin f1 len c e)
8713 (untabify beg end)
8714 (remove-text-properties beg end '(org-cwidth t display t))
8715 ;; Check if we have links
8716 (goto-char beg)
8717 (setq links (re-search-forward org-bracket-link-regexp end t))
8718 ;; Make sure the link properties are right FIXME: Can this be optimized????
8719 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8720 ;; Check if we are narrowing any columns
8721 (goto-char beg)
8722 (setq narrow (and org-format-transports-properties-p
8723 (re-search-forward "<[0-9]+>" end t)))
8724 ;; Get the rows
8725 (setq lines (org-split-string
8726 (buffer-substring beg end) "\n"))
8727 ;; Store the indentation of the first line
8728 (if (string-match "^ *" (car lines))
8729 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8730 ;; Mark the hlines by setting the corresponding element to nil
8731 ;; At the same time, we remove trailing space.
8732 (setq lines (mapcar (lambda (l)
8733 (if (string-match "^ *|-" l)
8735 (if (string-match "[ \t]+$" l)
8736 (substring l 0 (match-beginning 0))
8737 l)))
8738 lines))
8739 ;; Get the data fields by splitting the lines.
8740 (setq fields (mapcar
8741 (lambda (l)
8742 (org-split-string l " *| *"))
8743 (delq nil (copy-sequence lines))))
8744 ;; How many fields in the longest line?
8745 (condition-case nil
8746 (setq maxfields (apply 'max (mapcar 'length fields)))
8747 (error
8748 (kill-region beg end)
8749 (org-table-create org-table-default-size)
8750 (error "Empty table - created default table")))
8751 ;; A list of empty string to fill any short rows on output
8752 (setq emptystrings (make-list maxfields ""))
8753 ;; Check for special formatting.
8754 (setq i -1)
8755 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8756 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8757 ;; Check if there is an explicit width specified
8758 (when (and org-table-limit-column-width narrow)
8759 (setq c column fmax nil)
8760 (while c
8761 (setq e (pop c))
8762 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8763 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8764 ;; Find fields that are wider than fmax, and shorten them
8765 (when fmax
8766 (loop for xx in column do
8767 (when (and (stringp xx)
8768 (> (org-string-width xx) fmax))
8769 (org-add-props xx nil
8770 'help-echo
8771 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8772 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8773 (unless (> f1 1)
8774 (error "Cannot narrow field starting with wide link \"%s\""
8775 (match-string 0 xx)))
8776 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8777 (add-text-properties (- f1 2) f1
8778 (list 'display org-narrow-column-arrow)
8779 xx)))))
8780 ;; Get the maximum width for each column
8781 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8782 ;; Get the fraction of numbers, to decide about alignment of the column
8783 (setq cnt 0 frac 0.0)
8784 (loop for x in column do
8785 (if (equal x "")
8787 (setq frac ( / (+ (* frac cnt)
8788 (if (string-match org-table-number-regexp x) 1 0))
8789 (setq cnt (1+ cnt))))))
8790 (push (>= frac org-table-number-fraction) typenums))
8791 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8793 ;; Store the alignment of this table, for later editing of single fields
8794 (setq org-table-last-alignment typenums
8795 org-table-last-column-widths lengths)
8797 ;; With invisible characters, `format' does not get the field width right
8798 ;; So we need to make these fields wide by hand.
8799 (when links
8800 (loop for i from 0 upto (1- maxfields) do
8801 (setq len (nth i lengths))
8802 (loop for j from 0 upto (1- (length fields)) do
8803 (setq c (nthcdr i (car (nthcdr j fields))))
8804 (if (and (stringp (car c))
8805 (string-match org-bracket-link-regexp (car c))
8806 (< (org-string-width (car c)) len))
8807 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8809 ;; Compute the formats needed for output of the table
8810 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8811 (while (setq l (pop lengths))
8812 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8813 (setq rfmt (concat rfmt (format rfmt1 ty l))
8814 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8815 (setq rfmt (concat rfmt "\n")
8816 hfmt (concat (substring hfmt 0 -1) "|\n"))
8818 (setq new (mapconcat
8819 (lambda (l)
8820 (if l (apply 'format rfmt
8821 (append (pop fields) emptystrings))
8822 hfmt))
8823 lines ""))
8824 ;; Replace the old one
8825 (delete-region beg end)
8826 (move-marker end nil)
8827 (move-marker org-table-aligned-begin-marker (point))
8828 (insert new)
8829 (move-marker org-table-aligned-end-marker (point))
8830 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8831 (goto-char org-table-aligned-begin-marker)
8832 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8833 ;; Try to move to the old location (approximately)
8834 (goto-line linepos)
8835 (set-window-start (selected-window) winstart 'noforce)
8836 (org-table-goto-column colpos)
8837 (setq org-table-may-need-update nil)
8840 (defun org-string-width (s)
8841 "Compute width of string, ignoring invisible characters.
8842 This ignores character with invisibility property `org-link', and also
8843 characters with property `org-cwidth', because these will become invisible
8844 upon the next fontification round."
8845 (let (b)
8846 (when (or (eq t buffer-invisibility-spec)
8847 (assq 'org-link buffer-invisibility-spec))
8848 (while (setq b (text-property-any 0 (length s)
8849 'invisible 'org-link s))
8850 (setq s (concat (substring s 0 b)
8851 (substring s (or (next-single-property-change
8852 b 'invisible s) (length s)))))))
8853 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8854 (setq s (concat (substring s 0 b)
8855 (substring s (or (next-single-property-change
8856 b 'org-cwidth s) (length s))))))
8857 (string-width s)))
8859 (defun org-table-begin (&optional table-type)
8860 "Find the beginning of the table and return its position.
8861 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8862 (save-excursion
8863 (if (not (re-search-backward
8864 (if table-type org-table-any-border-regexp
8865 org-table-border-regexp)
8866 nil t))
8867 (error "Can't find beginning of table")
8868 (goto-char (match-beginning 0))
8869 (beginning-of-line 2)
8870 (point))))
8872 (defun org-table-end (&optional table-type)
8873 "Find the end of the table and return its position.
8874 With argument TABLE-TYPE, go to the end of a table.el-type table."
8875 (save-excursion
8876 (if (not (re-search-forward
8877 (if table-type org-table-any-border-regexp
8878 org-table-border-regexp)
8879 nil t))
8880 (goto-char (point-max))
8881 (goto-char (match-beginning 0)))
8882 (point-marker)))
8884 (defun org-table-justify-field-maybe (&optional new)
8885 "Justify the current field, text to left, number to right.
8886 Optional argument NEW may specify text to replace the current field content."
8887 (cond
8888 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8889 ((org-at-table-hline-p))
8890 ((and (not new)
8891 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8892 (current-buffer)))
8893 (< (point) org-table-aligned-begin-marker)
8894 (>= (point) org-table-aligned-end-marker)))
8895 ;; This is not the same table, force a full re-align
8896 (setq org-table-may-need-update t))
8897 (t ;; realign the current field, based on previous full realign
8898 (let* ((pos (point)) s
8899 (col (org-table-current-column))
8900 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8901 l f n o e)
8902 (when (> col 0)
8903 (skip-chars-backward "^|\n")
8904 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8905 (progn
8906 (setq s (match-string 1)
8907 o (match-string 0)
8908 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8909 e (not (= (match-beginning 2) (match-end 2))))
8910 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8911 l (if e "|" (setq org-table-may-need-update t) ""))
8912 n (format f s))
8913 (if new
8914 (if (<= (length new) l) ;; FIXME: length -> str-width?
8915 (setq n (format f new t t)) ;; FIXME: t t?
8916 (setq n (concat new "|") org-table-may-need-update t)))
8917 (or (equal n o)
8918 (let (org-table-may-need-update)
8919 (replace-match n))))
8920 (setq org-table-may-need-update t))
8921 (goto-char pos))))))
8923 (defun org-table-next-field ()
8924 "Go to the next field in the current table, creating new lines as needed.
8925 Before doing so, re-align the table if necessary."
8926 (interactive)
8927 (org-table-maybe-eval-formula)
8928 (org-table-maybe-recalculate-line)
8929 (if (and org-table-automatic-realign
8930 org-table-may-need-update)
8931 (org-table-align))
8932 (let ((end (org-table-end)))
8933 (if (org-at-table-hline-p)
8934 (end-of-line 1))
8935 (condition-case nil
8936 (progn
8937 (re-search-forward "|" end)
8938 (if (looking-at "[ \t]*$")
8939 (re-search-forward "|" end))
8940 (if (and (looking-at "-")
8941 org-table-tab-jumps-over-hlines
8942 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8943 (goto-char (match-beginning 1)))
8944 (if (looking-at "-")
8945 (progn
8946 (beginning-of-line 0)
8947 (org-table-insert-row 'below))
8948 (if (looking-at " ") (forward-char 1))))
8949 (error
8950 (org-table-insert-row 'below)))))
8952 (defun org-table-previous-field ()
8953 "Go to the previous field in the table.
8954 Before doing so, re-align the table if necessary."
8955 (interactive)
8956 (org-table-justify-field-maybe)
8957 (org-table-maybe-recalculate-line)
8958 (if (and org-table-automatic-realign
8959 org-table-may-need-update)
8960 (org-table-align))
8961 (if (org-at-table-hline-p)
8962 (end-of-line 1))
8963 (re-search-backward "|" (org-table-begin))
8964 (re-search-backward "|" (org-table-begin))
8965 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8966 (re-search-backward "|" (org-table-begin)))
8967 (if (looking-at "| ?")
8968 (goto-char (match-end 0))))
8970 (defun org-table-next-row ()
8971 "Go to the next row (same column) in the current table.
8972 Before doing so, re-align the table if necessary."
8973 (interactive)
8974 (org-table-maybe-eval-formula)
8975 (org-table-maybe-recalculate-line)
8976 (if (or (looking-at "[ \t]*$")
8977 (save-excursion (skip-chars-backward " \t") (bolp)))
8978 (newline)
8979 (if (and org-table-automatic-realign
8980 org-table-may-need-update)
8981 (org-table-align))
8982 (let ((col (org-table-current-column)))
8983 (beginning-of-line 2)
8984 (if (or (not (org-at-table-p))
8985 (org-at-table-hline-p))
8986 (progn
8987 (beginning-of-line 0)
8988 (org-table-insert-row 'below)))
8989 (org-table-goto-column col)
8990 (skip-chars-backward "^|\n\r")
8991 (if (looking-at " ") (forward-char 1)))))
8993 (defun org-table-copy-down (n)
8994 "Copy a field down in the current column.
8995 If the field at the cursor is empty, copy into it the content of the nearest
8996 non-empty field above. With argument N, use the Nth non-empty field.
8997 If the current field is not empty, it is copied down to the next row, and
8998 the cursor is moved with it. Therefore, repeating this command causes the
8999 column to be filled row-by-row.
9000 If the variable `org-table-copy-increment' is non-nil and the field is an
9001 integer, it will be incremented while copying."
9002 (interactive "p")
9003 (let* ((colpos (org-table-current-column))
9004 (field (org-table-get-field))
9005 (non-empty (string-match "[^ \t]" field))
9006 (beg (org-table-begin))
9007 txt)
9008 (org-table-check-inside-data-field)
9009 (if non-empty
9010 (progn
9011 (setq txt (org-trim field))
9012 (org-table-next-row)
9013 (org-table-blank-field))
9014 (save-excursion
9015 (setq txt
9016 (catch 'exit
9017 (while (progn (beginning-of-line 1)
9018 (re-search-backward org-table-dataline-regexp
9019 beg t))
9020 (org-table-goto-column colpos t)
9021 (if (and (looking-at
9022 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9023 (= (setq n (1- n)) 0))
9024 (throw 'exit (match-string 1))))))))
9025 (if txt
9026 (progn
9027 (if (and org-table-copy-increment
9028 (string-match "^[0-9]+$" txt))
9029 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9030 (insert txt)
9031 (org-table-maybe-recalculate-line)
9032 (org-table-align))
9033 (error "No non-empty field found"))))
9035 (defun org-table-check-inside-data-field ()
9036 "Is point inside a table data field?
9037 I.e. not on a hline or before the first or after the last column?
9038 This actually throws an error, so it aborts the current command."
9039 (if (or (not (org-at-table-p))
9040 (= (org-table-current-column) 0)
9041 (org-at-table-hline-p)
9042 (looking-at "[ \t]*$"))
9043 (error "Not in table data field")))
9045 (defvar org-table-clip nil
9046 "Clipboard for table regions.")
9048 (defun org-table-blank-field ()
9049 "Blank the current table field or active region."
9050 (interactive)
9051 (org-table-check-inside-data-field)
9052 (if (and (interactive-p) (org-region-active-p))
9053 (let (org-table-clip)
9054 (org-table-cut-region (region-beginning) (region-end)))
9055 (skip-chars-backward "^|")
9056 (backward-char 1)
9057 (if (looking-at "|[^|\n]+")
9058 (let* ((pos (match-beginning 0))
9059 (match (match-string 0))
9060 (len (org-string-width match)))
9061 (replace-match (concat "|" (make-string (1- len) ?\ )))
9062 (goto-char (+ 2 pos))
9063 (substring match 1)))))
9065 (defun org-table-get-field (&optional n replace)
9066 "Return the value of the field in column N of current row.
9067 N defaults to current field.
9068 If REPLACE is a string, replace field with this value. The return value
9069 is always the old value."
9070 (and n (org-table-goto-column n))
9071 (skip-chars-backward "^|\n")
9072 (backward-char 1)
9073 (if (looking-at "|[^|\r\n]*")
9074 (let* ((pos (match-beginning 0))
9075 (val (buffer-substring (1+ pos) (match-end 0))))
9076 (if replace
9077 (replace-match (concat "|" replace)))
9078 (goto-char (min (point-at-eol) (+ 2 pos)))
9079 val)
9080 (forward-char 1) ""))
9082 (defun org-table-current-column ()
9083 "Find out which column we are in.
9084 When called interactively, column is also displayed in echo area."
9085 (interactive)
9086 (if (interactive-p) (org-table-check-inside-data-field))
9087 (save-excursion
9088 (let ((cnt 0) (pos (point)))
9089 (beginning-of-line 1)
9090 (while (search-forward "|" pos t)
9091 (setq cnt (1+ cnt)))
9092 (if (interactive-p) (message "This is table column %d" cnt))
9093 cnt)))
9095 (defun org-table-goto-column (n &optional on-delim force)
9096 "Move the cursor to the Nth column in the current table line.
9097 With optional argument ON-DELIM, stop with point before the left delimiter
9098 of the field.
9099 If there are less than N fields, just go to after the last delimiter.
9100 However, when FORCE is non-nil, create new columns if necessary."
9101 (interactive "p")
9102 (let ((pos (point-at-eol)))
9103 (beginning-of-line 1)
9104 (when (> n 0)
9105 (while (and (> (setq n (1- n)) -1)
9106 (or (search-forward "|" pos t)
9107 (and force
9108 (progn (end-of-line 1)
9109 (skip-chars-backward "^|")
9110 (insert " | "))))))
9111 ; (backward-char 2) t)))))
9112 (when (and force (not (looking-at ".*|")))
9113 (save-excursion (end-of-line 1) (insert " | ")))
9114 (if on-delim
9115 (backward-char 1)
9116 (if (looking-at " ") (forward-char 1))))))
9118 (defun org-at-table-p (&optional table-type)
9119 "Return t if the cursor is inside an org-type table.
9120 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9121 (if org-enable-table-editor
9122 (save-excursion
9123 (beginning-of-line 1)
9124 (looking-at (if table-type org-table-any-line-regexp
9125 org-table-line-regexp)))
9126 nil))
9128 (defun org-at-table.el-p ()
9129 "Return t if and only if we are at a table.el table."
9130 (and (org-at-table-p 'any)
9131 (save-excursion
9132 (goto-char (org-table-begin 'any))
9133 (looking-at org-table1-hline-regexp))))
9135 (defun org-table-recognize-table.el ()
9136 "If there is a table.el table nearby, recognize it and move into it."
9137 (if org-table-tab-recognizes-table.el
9138 (if (org-at-table.el-p)
9139 (progn
9140 (beginning-of-line 1)
9141 (if (looking-at org-table-dataline-regexp)
9143 (if (looking-at org-table1-hline-regexp)
9144 (progn
9145 (beginning-of-line 2)
9146 (if (looking-at org-table-any-border-regexp)
9147 (beginning-of-line -1)))))
9148 (if (re-search-forward "|" (org-table-end t) t)
9149 (progn
9150 (require 'table)
9151 (if (table--at-cell-p (point))
9153 (message "recognizing table.el table...")
9154 (table-recognize-table)
9155 (message "recognizing table.el table...done")))
9156 (error "This should not happen..."))
9158 nil)
9159 nil))
9161 (defun org-at-table-hline-p ()
9162 "Return t if the cursor is inside a hline in a table."
9163 (if org-enable-table-editor
9164 (save-excursion
9165 (beginning-of-line 1)
9166 (looking-at org-table-hline-regexp))
9167 nil))
9169 (defun org-table-insert-column ()
9170 "Insert a new column into the table."
9171 (interactive)
9172 (if (not (org-at-table-p))
9173 (error "Not at a table"))
9174 (org-table-find-dataline)
9175 (let* ((col (max 1 (org-table-current-column)))
9176 (beg (org-table-begin))
9177 (end (org-table-end))
9178 ;; Current cursor position
9179 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9180 (colpos col))
9181 (goto-char beg)
9182 (while (< (point) end)
9183 (if (org-at-table-hline-p)
9185 (org-table-goto-column col t)
9186 (insert "| "))
9187 (beginning-of-line 2))
9188 (move-marker end nil)
9189 (goto-line linepos)
9190 (org-table-goto-column colpos)
9191 (org-table-align)
9192 (org-table-modify-formulas 'insert col)))
9194 (defun org-table-find-dataline ()
9195 "Find a dataline in the current table, which is needed for column commands."
9196 (if (and (org-at-table-p)
9197 (not (org-at-table-hline-p)))
9199 (let ((col (current-column))
9200 (end (org-table-end)))
9201 (move-to-column col)
9202 (while (and (< (point) end)
9203 (or (not (= (current-column) col))
9204 (org-at-table-hline-p)))
9205 (beginning-of-line 2)
9206 (move-to-column col))
9207 (if (and (org-at-table-p)
9208 (not (org-at-table-hline-p)))
9210 (error
9211 "Please position cursor in a data line for column operations")))))
9213 (defun org-table-delete-column ()
9214 "Delete a column into the table."
9215 (interactive)
9216 (if (not (org-at-table-p))
9217 (error "Not at a table"))
9218 (org-table-find-dataline)
9219 (org-table-check-inside-data-field)
9220 (let* ((col (org-table-current-column))
9221 (beg (org-table-begin))
9222 (end (org-table-end))
9223 ;; Current cursor position
9224 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9225 (colpos col))
9226 (goto-char beg)
9227 (while (< (point) end)
9228 (if (org-at-table-hline-p)
9230 (org-table-goto-column col t)
9231 (and (looking-at "|[^|\n]+|")
9232 (replace-match "|")))
9233 (beginning-of-line 2))
9234 (move-marker end nil)
9235 (goto-line linepos)
9236 (org-table-goto-column colpos)
9237 (org-table-align)
9238 (org-table-modify-formulas 'remove col)))
9240 (defun org-table-move-column-right ()
9241 "Move column to the right."
9242 (interactive)
9243 (org-table-move-column nil))
9244 (defun org-table-move-column-left ()
9245 "Move column to the left."
9246 (interactive)
9247 (org-table-move-column 'left))
9249 (defun org-table-move-column (&optional left)
9250 "Move the current column to the right. With arg LEFT, move to the left."
9251 (interactive "P")
9252 (if (not (org-at-table-p))
9253 (error "Not at a table"))
9254 (org-table-find-dataline)
9255 (org-table-check-inside-data-field)
9256 (let* ((col (org-table-current-column))
9257 (col1 (if left (1- col) col))
9258 (beg (org-table-begin))
9259 (end (org-table-end))
9260 ;; Current cursor position
9261 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9262 (colpos (if left (1- col) (1+ col))))
9263 (if (and left (= col 1))
9264 (error "Cannot move column further left"))
9265 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9266 (error "Cannot move column further right"))
9267 (goto-char beg)
9268 (while (< (point) end)
9269 (if (org-at-table-hline-p)
9271 (org-table-goto-column col1 t)
9272 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9273 (replace-match "|\\2|\\1|")))
9274 (beginning-of-line 2))
9275 (move-marker end nil)
9276 (goto-line linepos)
9277 (org-table-goto-column colpos)
9278 (org-table-align)
9279 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9281 (defun org-table-move-row-down ()
9282 "Move table row down."
9283 (interactive)
9284 (org-table-move-row nil))
9285 (defun org-table-move-row-up ()
9286 "Move table row up."
9287 (interactive)
9288 (org-table-move-row 'up))
9290 (defun org-table-move-row (&optional up)
9291 "Move the current table line down. With arg UP, move it up."
9292 (interactive "P")
9293 (let ((col (current-column))
9294 (pos (point))
9295 (tonew (if up 0 2))
9296 txt)
9297 (beginning-of-line tonew)
9298 (if (not (org-at-table-p))
9299 (progn
9300 (goto-char pos)
9301 (error "Cannot move row further")))
9302 (goto-char pos)
9303 (beginning-of-line 1)
9304 (setq pos (point))
9305 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9306 (delete-region (point) (1+ (point-at-eol)))
9307 (beginning-of-line tonew)
9308 (insert txt)
9309 (beginning-of-line 0)
9310 (move-to-column col)))
9312 (defun org-table-insert-row (&optional arg)
9313 "Insert a new row above the current line into the table.
9314 With prefix ARG, insert below the current line."
9315 (interactive "P")
9316 (if (not (org-at-table-p))
9317 (error "Not at a table"))
9318 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9319 (new (org-table-clean-line line)))
9320 ;; Fix the first field if necessary
9321 (if (string-match "^[ \t]*| *[#$] *|" line)
9322 (setq new (replace-match (match-string 0 line) t t new)))
9323 (beginning-of-line (if arg 2 1))
9324 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9325 (beginning-of-line 0)
9326 (re-search-forward "| ?" (point-at-eol) t)
9327 (and org-table-may-need-update (org-table-align))))
9329 (defun org-table-insert-hline (&optional arg)
9330 "Insert a horizontal-line below the current line into the table.
9331 With prefix ARG, insert above the current line."
9332 (interactive "P")
9333 (if (not (org-at-table-p))
9334 (error "Not at a table"))
9335 (let ((line (org-table-clean-line
9336 (buffer-substring (point-at-bol) (point-at-eol))))
9337 (col (current-column)))
9338 (while (string-match "|\\( +\\)|" line)
9339 (setq line (replace-match
9340 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9341 ?-) "|") t t line)))
9342 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9343 (beginning-of-line (if arg 1 2))
9344 (insert line "\n")
9345 (beginning-of-line (if arg 1 -1))
9346 (move-to-column col)))
9348 (defun org-table-clean-line (s)
9349 "Convert a table line S into a string with only \"|\" and space.
9350 In particular, this does handle wide and invisible characters."
9351 (if (string-match "^[ \t]*|-" s)
9352 ;; It's a hline, just map the characters
9353 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9354 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9355 (setq s (replace-match
9356 (concat "|" (make-string (org-string-width (match-string 1 s))
9357 ?\ ) "|")
9358 t t s)))
9361 (defun org-table-kill-row ()
9362 "Delete the current row or horizontal line from the table."
9363 (interactive)
9364 (if (not (org-at-table-p))
9365 (error "Not at a table"))
9366 (let ((col (current-column)))
9367 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9368 (if (not (org-at-table-p)) (beginning-of-line 0))
9369 (move-to-column col)))
9371 (defun org-table-sort-lines (beg end numericp)
9372 "Sort table lines in region.
9373 Point and mark define the first and last line to include. Both point and
9374 mark should be in the column that is used for sorting. For example, to
9375 sort according to column 3, put the mark in the first line to sort, in
9376 table column 3. Put point into the last line to be included in the sorting,
9377 also in table column 3. The command will prompt for the sorting method
9378 \(n for numerical, a for alphanumeric)."
9379 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9380 (setq numericp (string-match "[nN]" numericp))
9381 (org-table-align) ;; Just to be safe
9382 (let* (bcol ecol cmp column lns)
9383 (goto-char beg)
9384 (org-table-check-inside-data-field)
9385 (setq column (org-table-current-column)
9386 beg (move-marker (make-marker) (point-at-bol)))
9387 (goto-char end)
9388 (org-table-check-inside-data-field)
9389 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9390 (untabify beg end)
9391 (goto-char beg)
9392 (org-table-goto-column column)
9393 (skip-chars-backward "^|")
9394 (setq bcol (current-column))
9395 (org-table-goto-column (1+ column))
9396 (skip-chars-backward "^|")
9397 (setq ecol (1- (current-column)))
9398 (setq cmp (if numericp
9399 (lambda (a b) (< (car a) (car b)))
9400 (lambda (a b) (string< (car a) (car b)))))
9401 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9402 (split-string (buffer-substring beg end) "\n")))
9403 (if numericp
9404 (setq lns (mapcar (lambda(x)
9405 (cons (string-to-number (car x)) (cdr x)))
9406 lns)))
9407 (delete-region beg end)
9408 (move-marker beg nil)
9409 (move-marker end nil)
9410 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9411 (message "%d lines sorted %s based on column %d"
9412 (length lns)
9413 (if numericp "numerically" "alphabetically") column)))
9415 (defun org-table-cut-region (beg end)
9416 "Copy region in table to the clipboard and blank all relevant fields."
9417 (interactive "r")
9418 (org-table-copy-region beg end 'cut))
9420 (defun org-table-copy-region (beg end &optional cut)
9421 "Copy rectangular region in table to clipboard.
9422 A special clipboard is used which can only be accessed
9423 with `org-table-paste-rectangle'."
9424 (interactive "rP")
9425 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9426 region cols
9427 (rpl (if cut " " nil)))
9428 (goto-char beg)
9429 (org-table-check-inside-data-field)
9430 (setq l01 (count-lines (point-min) (point))
9431 c01 (org-table-current-column))
9432 (goto-char end)
9433 (org-table-check-inside-data-field)
9434 (setq l02 (count-lines (point-min) (point))
9435 c02 (org-table-current-column))
9436 (setq l1 (min l01 l02) l2 (max l01 l02)
9437 c1 (min c01 c02) c2 (max c01 c02))
9438 (catch 'exit
9439 (while t
9440 (catch 'nextline
9441 (if (> l1 l2) (throw 'exit t))
9442 (goto-line l1)
9443 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9444 (setq cols nil ic1 c1 ic2 c2)
9445 (while (< ic1 (1+ ic2))
9446 (push (org-table-get-field ic1 rpl) cols)
9447 (setq ic1 (1+ ic1)))
9448 (push (nreverse cols) region)
9449 (setq l1 (1+ l1)))))
9450 (setq org-table-clip (nreverse region))
9451 (if cut (org-table-align))
9452 org-table-clip))
9454 (defun org-table-paste-rectangle ()
9455 "Paste a rectangular region into a table.
9456 The upper right corner ends up in the current field. All involved fields
9457 will be overwritten. If the rectangle does not fit into the present table,
9458 the table is enlarged as needed. The process ignores horizontal separator
9459 lines."
9460 (interactive)
9461 (unless (and org-table-clip (listp org-table-clip))
9462 (error "First cut/copy a region to paste!"))
9463 (org-table-check-inside-data-field)
9464 (let* ((clip org-table-clip)
9465 (line (count-lines (point-min) (point)))
9466 (col (org-table-current-column))
9467 (org-enable-table-editor t)
9468 (org-table-automatic-realign nil)
9469 c cols field)
9470 (while (setq cols (pop clip))
9471 (while (org-at-table-hline-p) (beginning-of-line 2))
9472 (if (not (org-at-table-p))
9473 (progn (end-of-line 0) (org-table-next-field)))
9474 (setq c col)
9475 (while (setq field (pop cols))
9476 (org-table-goto-column c nil 'force)
9477 (org-table-get-field nil field)
9478 (setq c (1+ c)))
9479 (beginning-of-line 2))
9480 (goto-line line)
9481 (org-table-goto-column col)
9482 (org-table-align)))
9484 (defun org-table-convert ()
9485 "Convert from `org-mode' table to table.el and back.
9486 Obviously, this only works within limits. When an Org-mode table is
9487 converted to table.el, all horizontal separator lines get lost, because
9488 table.el uses these as cell boundaries and has no notion of horizontal lines.
9489 A table.el table can be converted to an Org-mode table only if it does not
9490 do row or column spanning. Multiline cells will become multiple cells.
9491 Beware, Org-mode does not test if the table can be successfully converted - it
9492 blindly applies a recipe that works for simple tables."
9493 (interactive)
9494 (require 'table)
9495 (if (org-at-table.el-p)
9496 ;; convert to Org-mode table
9497 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9498 (end (move-marker (make-marker) (org-table-end t))))
9499 (table-unrecognize-region beg end)
9500 (goto-char beg)
9501 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9502 (replace-match ""))
9503 (goto-char beg))
9504 (if (org-at-table-p)
9505 ;; convert to table.el table
9506 (let ((beg (move-marker (make-marker) (org-table-begin)))
9507 (end (move-marker (make-marker) (org-table-end))))
9508 ;; first, get rid of all horizontal lines
9509 (goto-char beg)
9510 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9511 (replace-match ""))
9512 ;; insert a hline before first
9513 (goto-char beg)
9514 (org-table-insert-hline 'above)
9515 (beginning-of-line -1)
9516 ;; insert a hline after each line
9517 (while (progn (beginning-of-line 3) (< (point) end))
9518 (org-table-insert-hline))
9519 (goto-char beg)
9520 (setq end (move-marker end (org-table-end)))
9521 ;; replace "+" at beginning and ending of hlines
9522 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9523 (replace-match "\\1+-"))
9524 (goto-char beg)
9525 (while (re-search-forward "-|[ \t]*$" end t)
9526 (replace-match "-+"))
9527 (goto-char beg)))))
9529 (defun org-table-wrap-region (arg)
9530 "Wrap several fields in a column like a paragraph.
9531 This is useful if you'd like to spread the contents of a field over several
9532 lines, in order to keep the table compact.
9534 If there is an active region, and both point and mark are in the same column,
9535 the text in the column is wrapped to minimum width for the given number of
9536 lines. Generally, this makes the table more compact. A prefix ARG may be
9537 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9538 formats the selected text to two lines. If the region was longer than two
9539 lines, the remaining lines remain empty. A negative prefix argument reduces
9540 the current number of lines by that amount. The wrapped text is pasted back
9541 into the table. If you formatted it to more lines than it was before, fields
9542 further down in the table get overwritten - so you might need to make space in
9543 the table first.
9545 If there is no region, the current field is split at the cursor position and
9546 the text fragment to the right of the cursor is prepended to the field one
9547 line down.
9549 If there is no region, but you specify a prefix ARG, the current field gets
9550 blank, and the content is appended to the field above."
9551 (interactive "P")
9552 (org-table-check-inside-data-field)
9553 (if (org-region-active-p)
9554 ;; There is a region: fill as a paragraph
9555 (let ((beg (region-beginning))
9556 nlines)
9557 (org-table-cut-region (region-beginning) (region-end))
9558 (if (> (length (car org-table-clip)) 1)
9559 (error "Region must be limited to single column"))
9560 (setq nlines (if arg
9561 (if (< arg 1)
9562 (+ (length org-table-clip) arg)
9563 arg)
9564 (length org-table-clip)))
9565 (setq org-table-clip
9566 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9567 nil nlines)))
9568 (goto-char beg)
9569 (org-table-paste-rectangle))
9570 ;; No region, split the current field at point
9571 (if arg
9572 ;; combine with field above
9573 (let ((s (org-table-blank-field))
9574 (col (org-table-current-column)))
9575 (beginning-of-line 0)
9576 (while (org-at-table-hline-p) (beginning-of-line 0))
9577 (org-table-goto-column col)
9578 (skip-chars-forward "^|")
9579 (skip-chars-backward " ")
9580 (insert " " (org-trim s))
9581 (org-table-align))
9582 ;; split field
9583 (when (looking-at "\\([^|]+\\)+|")
9584 (let ((s (match-string 1)))
9585 (replace-match " |")
9586 (goto-char (match-beginning 0))
9587 (org-table-next-row)
9588 (insert (org-trim s) " ")
9589 (org-table-align))))))
9591 (defvar org-field-marker nil)
9593 (defun org-table-edit-field (arg)
9594 "Edit table field in a different window.
9595 This is mainly useful for fields that contain hidden parts.
9596 When called with a \\[universal-argument] prefix, just make the full field visible so that
9597 it can be edited in place."
9598 (interactive "P")
9599 (if arg
9600 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9601 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9602 (remove-text-properties b e '(org-cwidth t invisible t
9603 display t intangible t))
9604 (if (and (boundp 'font-lock-mode) font-lock-mode)
9605 (font-lock-fontify-block)))
9606 (let ((pos (move-marker (make-marker) (point)))
9607 (field (org-table-get-field))
9608 (cw (current-window-configuration))
9610 (switch-to-buffer-other-window "*Org tmp*")
9611 (erase-buffer)
9612 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9613 (org-mode)
9614 (goto-char (setq p (point-max)))
9615 (insert (org-trim field))
9616 (remove-text-properties p (point-max)
9617 '(invisible t org-cwidth t display t
9618 intangible t))
9619 (goto-char p)
9620 (set (make-local-variable 'org-finish-function)
9621 'org-table-finish-edit-field)
9622 (set (make-local-variable 'org-window-configuration) cw)
9623 (set (make-local-variable 'org-field-marker) pos)
9624 (message "Edit and finish with C-c C-c"))))
9626 (defun org-table-finish-edit-field ()
9627 "Finish editing a table data field.
9628 Remove all newline characters, insert the result into the table, realign
9629 the table and kill the editing buffer."
9630 (let ((pos org-field-marker)
9631 (cw org-window-configuration)
9632 (cb (current-buffer))
9633 text)
9634 (goto-char (point-min))
9635 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9636 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9637 (replace-match " "))
9638 (setq text (org-trim (buffer-string)))
9639 (set-window-configuration cw)
9640 (kill-buffer cb)
9641 (select-window (get-buffer-window (marker-buffer pos)))
9642 (goto-char pos)
9643 (move-marker pos nil)
9644 (org-table-check-inside-data-field)
9645 (org-table-get-field nil text)
9646 (org-table-align)
9647 (message "New field value inserted")))
9649 (defun org-trim (s)
9650 "Remove whitespace at beginning and end of string."
9651 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9652 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9655 (defun org-wrap (string &optional width lines)
9656 "Wrap string to either a number of lines, or a width in characters.
9657 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9658 that costs. If there is a word longer than WIDTH, the text is actually
9659 wrapped to the length of that word.
9660 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9661 many lines, whatever width that takes.
9662 The return value is a list of lines, without newlines at the end."
9663 (let* ((words (org-split-string string "[ \t\n]+"))
9664 (maxword (apply 'max (mapcar 'org-string-width words)))
9665 w ll)
9666 (cond (width
9667 (org-do-wrap words (max maxword width)))
9668 (lines
9669 (setq w maxword)
9670 (setq ll (org-do-wrap words maxword))
9671 (if (<= (length ll) lines)
9673 (setq ll words)
9674 (while (> (length ll) lines)
9675 (setq w (1+ w))
9676 (setq ll (org-do-wrap words w)))
9677 ll))
9678 (t (error "Cannot wrap this")))))
9681 (defun org-do-wrap (words width)
9682 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9683 (let (lines line)
9684 (while words
9685 (setq line (pop words))
9686 (while (and words (< (+ (length line) (length (car words))) width))
9687 (setq line (concat line " " (pop words))))
9688 (setq lines (push line lines)))
9689 (nreverse lines)))
9691 (defun org-split-string (string &optional separators)
9692 "Splits STRING into substrings at SEPARATORS.
9693 No empty strings are returned if there are matches at the beginning
9694 and end of string."
9695 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9696 (start 0)
9697 notfirst
9698 (list nil))
9699 (while (and (string-match rexp string
9700 (if (and notfirst
9701 (= start (match-beginning 0))
9702 (< start (length string)))
9703 (1+ start) start))
9704 (< (match-beginning 0) (length string)))
9705 (setq notfirst t)
9706 (or (eq (match-beginning 0) 0)
9707 (and (eq (match-beginning 0) (match-end 0))
9708 (eq (match-beginning 0) start))
9709 (setq list
9710 (cons (substring string start (match-beginning 0))
9711 list)))
9712 (setq start (match-end 0)))
9713 (or (eq start (length string))
9714 (setq list
9715 (cons (substring string start)
9716 list)))
9717 (nreverse list)))
9719 (defun org-table-map-tables (function)
9720 "Apply FUNCTION to the start of all tables in the buffer."
9721 (save-excursion
9722 (save-restriction
9723 (widen)
9724 (goto-char (point-min))
9725 (while (re-search-forward org-table-any-line-regexp nil t)
9726 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9727 (beginning-of-line 1)
9728 (if (looking-at org-table-line-regexp)
9729 (save-excursion (funcall function)))
9730 (re-search-forward org-table-any-border-regexp nil 1))))
9731 (message "Mapping tables: done"))
9733 (defun org-table-sum (&optional beg end nlast)
9734 "Sum numbers in region of current table column.
9735 The result will be displayed in the echo area, and will be available
9736 as kill to be inserted with \\[yank].
9738 If there is an active region, it is interpreted as a rectangle and all
9739 numbers in that rectangle will be summed. If there is no active
9740 region and point is located in a table column, sum all numbers in that
9741 column.
9743 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9744 numbers are assumed to be times as well (in decimal hours) and the
9745 numbers are added as such.
9747 If NLAST is a number, only the NLAST fields will actually be summed."
9748 (interactive)
9749 (save-excursion
9750 (let (col (timecnt 0) diff h m s org-table-clip)
9751 (cond
9752 ((and beg end)) ; beg and end given explicitly
9753 ((org-region-active-p)
9754 (setq beg (region-beginning) end (region-end)))
9756 (setq col (org-table-current-column))
9757 (goto-char (org-table-begin))
9758 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9759 (error "No table data"))
9760 (org-table-goto-column col)
9761 ;not needed? (skip-chars-backward "^|")
9762 (setq beg (point))
9763 (goto-char (org-table-end))
9764 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9765 (error "No table data"))
9766 (org-table-goto-column col)
9767 ;not needed? (skip-chars-forward "^|")
9768 (setq end (point))))
9769 (let* ((items (apply 'append (org-table-copy-region beg end)))
9770 (items1 (cond ((not nlast) items)
9771 ((>= nlast (length items)) items)
9772 (t (setq items (reverse items))
9773 (setcdr (nthcdr (1- nlast) items) nil)
9774 (nreverse items))))
9775 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9776 items1)))
9777 (res (apply '+ numbers))
9778 (sres (if (= timecnt 0)
9779 (format "%g" res)
9780 (setq diff (* 3600 res)
9781 h (floor (/ diff 3600)) diff (mod diff 3600)
9782 m (floor (/ diff 60)) diff (mod diff 60)
9783 s diff)
9784 (format "%d:%02d:%02d" h m s))))
9785 (kill-new sres)
9786 (if (interactive-p)
9787 (message "%s"
9788 (substitute-command-keys
9789 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9790 (length numbers) sres))))
9791 sres))))
9793 (defun org-table-get-number-for-summing (s)
9794 (let (n)
9795 (if (string-match "^ *|? *" s)
9796 (setq s (replace-match "" nil nil s)))
9797 (if (string-match " *|? *$" s)
9798 (setq s (replace-match "" nil nil s)))
9799 (setq n (string-to-number s))
9800 (cond
9801 ((and (string-match "0" s)
9802 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9803 ((string-match "\\`[ \t]+\\'" s) nil)
9804 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9805 (let ((h (string-to-number (or (match-string 1 s) "0")))
9806 (m (string-to-number (or (match-string 2 s) "0")))
9807 (s (string-to-number (or (match-string 4 s) "0"))))
9808 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9809 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9810 ((equal n 0) nil)
9811 (t n))))
9813 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9814 "Get a calc vector from a column, accorting to descriptor DESC.
9815 Optional arguments TBEG and COL can give the beginning of the table and
9816 the current column, to avoid unnecessary parsing."
9817 (save-excursion
9818 (or tbeg (setq tbeg (org-table-begin)))
9819 (or col (setq col (org-table-current-column)))
9820 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9821 (cond
9822 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9823 (setq n1 (- (match-end 1) (match-beginning 1)))
9824 (if (match-beginning 3)
9825 (setq n2 (- (match-end 2) (match-beginning 3))))
9826 (setq n (if n2 (max n1 n2) n1))
9827 (setq n1 (if n2 (min n1 n2)))
9828 (setq nn n)
9829 (while (and (> nn 0)
9830 (re-search-backward org-table-hline-regexp tbeg t))
9831 (push (org-current-line) hline-list)
9832 (setq nn (1- nn)))
9833 (setq hline-list (nreverse hline-list))
9834 (goto-line (nth (1- n) hline-list))
9835 (when (re-search-forward org-table-dataline-regexp)
9836 (org-table-goto-column col)
9837 (setq beg (point)))
9838 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9839 (when (re-search-backward org-table-dataline-regexp)
9840 (org-table-goto-column col)
9841 (setq end (point)))
9842 (setq l (apply 'append (org-table-copy-region beg end)))
9843 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9844 (if (equal x "") "0" x))
9845 l ",") "]"))
9846 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9847 (setq n1 (string-to-number (match-string 1 desc))
9848 n2 (string-to-number (match-string 2 desc)))
9849 (beginning-of-line 1)
9850 (save-excursion
9851 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9852 (org-table-goto-column col)
9853 (setq beg (point))))
9854 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9855 (org-table-goto-column col)
9856 (setq end (point)))
9857 (setq l (apply 'append (org-table-copy-region beg end)))
9858 (concat "[" (mapconcat
9859 (lambda (x) (setq x (org-trim x))
9860 (if (equal x "") "0" x))
9861 l ",") "]"))
9862 ((string-match "\\([0-9]+\\)" desc)
9863 (beginning-of-line 1)
9864 (when (re-search-backward org-table-dataline-regexp tbeg t
9865 (string-to-number (match-string 0 desc)))
9866 (org-table-goto-column col)
9867 (org-trim (org-table-get-field))))))))
9869 (defvar org-table-formula-history nil)
9871 (defvar org-table-column-names nil
9872 "Alist with column names, derived from the `!' line.")
9873 (defvar org-table-column-name-regexp nil
9874 "Regular expression matching the current column names.")
9875 (defvar org-table-local-parameters nil
9876 "Alist with parameter names, derived from the `$' line.")
9877 (defvar org-table-named-field-locations nil
9878 "Alist with locations of named fields.")
9880 (defun org-table-get-formula (&optional equation named)
9881 "Read a formula from the minibuffer, offer stored formula as default."
9882 (let* ((name (car (rassoc (list (org-current-line)
9883 (org-table-current-column))
9884 org-table-named-field-locations)))
9885 (scol (if named
9886 (if name name
9887 (error "Not in a named field"))
9888 (int-to-string (org-table-current-column))))
9889 (dummy (and name (not named)
9890 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9891 (error "Abort")))
9892 (org-table-may-need-update nil)
9893 (stored-list (org-table-get-stored-formulas))
9894 (stored (cdr (assoc scol stored-list)))
9895 (eq (cond
9896 ((and stored equation (string-match "^ *=? *$" equation))
9897 stored)
9898 ((stringp equation)
9899 equation)
9900 (t (read-string
9901 (format "%s formula $%s=" (if named "Field" "Column") scol)
9902 (or stored "") 'org-table-formula-history
9903 ;stored
9904 ))))
9905 mustsave)
9906 (when (not (string-match "\\S-" eq))
9907 ;; remove formula
9908 (setq stored-list (delq (assoc scol stored-list) stored-list))
9909 (org-table-store-formulas stored-list)
9910 (error "Formula removed"))
9911 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9912 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9913 (if (and name (not named))
9914 ;; We set the column equation, delete the named one.
9915 (setq stored-list (delq (assoc name stored-list) stored-list)
9916 mustsave t))
9917 (if stored
9918 (setcdr (assoc scol stored-list) eq)
9919 (setq stored-list (cons (cons scol eq) stored-list)))
9920 (if (or mustsave (not (equal stored eq)))
9921 (org-table-store-formulas stored-list))
9922 eq))
9924 (defun org-table-store-formulas (alist)
9925 "Store the list of formulas below the current table."
9926 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9927 (save-excursion
9928 (goto-char (org-table-end))
9929 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9930 (delete-region (point) (match-end 0)))
9931 (insert "#+TBLFM: "
9932 (mapconcat (lambda (x)
9933 (concat "$" (car x) "=" (cdr x)))
9934 alist "::")
9935 "\n")))
9937 (defun org-table-get-stored-formulas ()
9938 "Return an alist with the t=stored formulas directly after current table."
9939 (interactive)
9940 (let (scol eq eq-alist strings string seen)
9941 (save-excursion
9942 (goto-char (org-table-end))
9943 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9944 (setq strings (org-split-string (match-string 2) " *:: *"))
9945 (while (setq string (pop strings))
9946 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9947 (setq scol (match-string 1 string)
9948 eq (match-string 2 string)
9949 eq-alist (cons (cons scol eq) eq-alist))
9950 (if (member scol seen)
9951 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9952 (push scol seen))))))
9953 (nreverse eq-alist)))
9955 (defun org-table-modify-formulas (action &rest columns)
9956 "Modify the formulas stored below the current table.
9957 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9958 expected, for the other actions only a single column number is needed."
9959 (let ((list (org-table-get-stored-formulas))
9960 (nmax (length (org-split-string
9961 (buffer-substring (point-at-bol) (point-at-eol))
9962 "|")))
9963 col col1 col2 scol si sc1 sc2)
9964 (cond
9965 ((null list)) ; No action needed if there are no stored formulas
9966 ((eq action 'remove)
9967 (setq col (car columns)
9968 scol (int-to-string col))
9969 (org-table-replace-in-formulas list scol "INVALID")
9970 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9971 (loop for i from (1+ col) upto nmax by 1 do
9972 (setq si (int-to-string i))
9973 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9974 (if (assoc si list) (setcar (assoc si list)
9975 (int-to-string (1- i))))))
9976 ((eq action 'insert)
9977 (setq col (car columns))
9978 (loop for i from nmax downto col by 1 do
9979 (setq si (int-to-string i))
9980 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9981 (if (assoc si list) (setcar (assoc si list)
9982 (int-to-string (1+ i))))))
9983 ((eq action 'swap)
9984 (setq col1 (car columns) col2 (nth 1 columns)
9985 sc1 (int-to-string col1) sc2 (int-to-string col2))
9986 ;; Hopefully, ZqZtZ will never be a name in a table
9987 (org-table-replace-in-formulas list sc1 "ZqZtZ")
9988 (org-table-replace-in-formulas list sc2 sc1)
9989 (org-table-replace-in-formulas list "ZqZtZ" sc2)
9990 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
9991 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9992 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
9993 (t (error "Invalid action in `org-table-modify-formulas'")))
9994 (if list (org-table-store-formulas list))))
9996 (defun org-table-replace-in-formulas (list s1 s2)
9997 (let (elt re s)
9998 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9999 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10000 re (concat (regexp-quote s1) "\\>"))
10001 (while (setq elt (pop list))
10002 (setq s (cdr elt))
10003 (while (string-match re s)
10004 (setq s (replace-match s2 t t s)))
10005 (setcdr elt s))))
10007 (defun org-table-get-specials ()
10008 "Get the column names and local parameters for this table."
10009 (save-excursion
10010 (let ((beg (org-table-begin)) (end (org-table-end))
10011 names name fields fields1 field cnt c v line col)
10012 (setq org-table-column-names nil
10013 org-table-local-parameters nil
10014 org-table-named-field-locations nil)
10015 (goto-char beg)
10016 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10017 (setq names (org-split-string (match-string 1) " *| *")
10018 cnt 1)
10019 (while (setq name (pop names))
10020 (setq cnt (1+ cnt))
10021 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10022 (push (cons name (int-to-string cnt)) org-table-column-names))))
10023 (setq org-table-column-names (nreverse org-table-column-names))
10024 (setq org-table-column-name-regexp
10025 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10026 (goto-char beg)
10027 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10028 (setq fields (org-split-string (match-string 1) " *| *"))
10029 (while (setq field (pop fields))
10030 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10031 (push (cons (match-string 1 field) (match-string 2 field))
10032 org-table-local-parameters))))
10033 (goto-char beg)
10034 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10035 (setq c (match-string 1)
10036 fields (org-split-string (match-string 2) " *| *"))
10037 (save-excursion
10038 (beginning-of-line (if (equal c "_") 2 0))
10039 (setq line (org-current-line) col 1)
10040 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10041 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10042 (while (and fields1 (setq field (pop fields)))
10043 (setq v (pop fields1) col (1+ col))
10044 (when (and (stringp field) (stringp v)
10045 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10046 (push (cons field v) org-table-local-parameters)
10047 (push (list field line col) org-table-named-field-locations)))))))
10049 (defun org-this-word ()
10050 ;; Get the current word
10051 (save-excursion
10052 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10053 (end (progn (skip-chars-forward "^ \t\n") (point))))
10054 (buffer-substring-no-properties beg end))))
10056 (defun org-table-maybe-eval-formula ()
10057 "Check if the current field starts with \"=\" or \":=\".
10058 If yes, store the formula and apply it."
10059 ;; We already know we are in a table. Get field will only return a formula
10060 ;; when appropriate. It might return a separator line, but no problem.
10061 (when org-table-formula-evaluate-inline
10062 (let* ((field (org-trim (or (org-table-get-field) "")))
10063 named eq)
10064 (when (string-match "^:?=\\(.*\\)" field)
10065 (setq named (equal (string-to-char field) ?:)
10066 eq (match-string 1 field))
10067 (if (fboundp 'calc-eval)
10068 (org-table-eval-formula (if named '(4) nil) eq))))))
10070 (defvar org-recalc-commands nil
10071 "List of commands triggering the recalculation of a line.
10072 Will be filled automatically during use.")
10074 (defvar org-recalc-marks
10075 '((" " . "Unmarked: no special line, no automatic recalculation")
10076 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10077 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10078 ("!" . "Column name definition line. Reference in formula as $name.")
10079 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10080 ("_" . "Names for values in row below this one.")
10081 ("^" . "Names for values in row above this one.")))
10083 (defun org-table-rotate-recalc-marks (&optional newchar)
10084 "Rotate the recalculation mark in the first column.
10085 If in any row, the first field is not consistent with a mark,
10086 insert a new column for the markers.
10087 When there is an active region, change all the lines in the region,
10088 after prompting for the marking character.
10089 After each change, a message will be displayed indicating the meaning
10090 of the new mark."
10091 (interactive)
10092 (unless (org-at-table-p) (error "Not at a table"))
10093 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10094 (beg (org-table-begin))
10095 (end (org-table-end))
10096 (l (org-current-line))
10097 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10098 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10099 (have-col
10100 (save-excursion
10101 (goto-char beg)
10102 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10103 (col (org-table-current-column))
10104 (forcenew (car (assoc newchar org-recalc-marks)))
10105 epos new)
10106 (when l1
10107 (message "Change region to what mark? Type # * ! $ or SPC: ")
10108 (setq newchar (char-to-string (read-char-exclusive))
10109 forcenew (car (assoc newchar org-recalc-marks))))
10110 (if (and newchar (not forcenew))
10111 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10112 newchar))
10113 (if l1 (goto-line l1))
10114 (save-excursion
10115 (beginning-of-line 1)
10116 (unless (looking-at org-table-dataline-regexp)
10117 (error "Not at a table data line")))
10118 (unless have-col
10119 (org-table-goto-column 1)
10120 (org-table-insert-column)
10121 (org-table-goto-column (1+ col)))
10122 (setq epos (point-at-eol))
10123 (save-excursion
10124 (beginning-of-line 1)
10125 (org-table-get-field
10126 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10127 (concat " "
10128 (setq new (or forcenew
10129 (cadr (member (match-string 1) marks))))
10130 " ")
10131 " # ")))
10132 (if (and l1 l2)
10133 (progn
10134 (goto-line l1)
10135 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10136 (and (looking-at org-table-dataline-regexp)
10137 (org-table-get-field 1 (concat " " new " "))))
10138 (goto-line l1)))
10139 (if (not (= epos (point-at-eol))) (org-table-align))
10140 (goto-line l)
10141 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10143 (defun org-table-maybe-recalculate-line ()
10144 "Recompute the current line if marked for it, and if we haven't just done it."
10145 (interactive)
10146 (and org-table-allow-automatic-line-recalculation
10147 (not (and (memq last-command org-recalc-commands)
10148 (equal org-last-recalc-line (org-current-line))))
10149 (save-excursion (beginning-of-line 1)
10150 (looking-at org-table-auto-recalculate-regexp))
10151 (fboundp 'calc-eval)
10152 (org-table-recalculate) t))
10154 (defvar org-table-formula-debug nil
10155 "Non-nil means, debug table formulas.
10156 When nil, simply write \"#ERROR\" in corrupted fields.")
10158 (defvar modes)
10159 (defsubst org-set-calc-mode (var &optional value)
10160 (if (stringp var)
10161 (setq var (assoc var '(("D" calc-angle-mode deg)
10162 ("R" calc-angle-mode rad)
10163 ("F" calc-prefer-frac t)
10164 ("S" calc-symbolic-mode t)))
10165 value (nth 2 var) var (nth 1 var)))
10166 (if (memq var modes)
10167 (setcar (cdr (memq var modes)) value)
10168 (cons var (cons value modes)))
10169 modes)
10171 (defun org-table-eval-formula (&optional arg equation
10172 suppress-align suppress-const
10173 suppress-store)
10174 "Replace the table field value at the cursor by the result of a calculation.
10176 This function makes use of Dave Gillespie's Calc package, in my view the
10177 most exciting program ever written for GNU Emacs. So you need to have Calc
10178 installed in order to use this function.
10180 In a table, this command replaces the value in the current field with the
10181 result of a formula. It also installs the formula as the \"current\" column
10182 formula, by storing it in a special line below the table. When called
10183 with a `C-u' prefix, the current field must ba a named field, and the
10184 formula is installed as valid in only this specific field.
10186 When called, the command first prompts for a formula, which is read in
10187 the minibuffer. Previously entered formulas are available through the
10188 history list, and the last used formula is offered as a default.
10189 These stored formulas are adapted correctly when moving, inserting, or
10190 deleting columns with the corresponding commands.
10192 The formula can be any algebraic expression understood by the Calc package.
10193 For details, see the Org-mode manual.
10195 This function can also be called from Lisp programs and offers
10196 additional arguments: EQUATION can be the formula to apply. If this
10197 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10198 used to speed-up recursive calls by by-passing unnecessary aligns.
10199 SUPPRESS-CONST suppresses the interpretation of constants in the
10200 formula, assuming that this has been done already outside the function.
10201 SUPPRESS-STORE means the formula should not be stored, either because
10202 it is already stored, or because it is a modified equation that should
10203 not overwrite the stored one."
10204 (interactive "P")
10205 (require 'calc)
10206 (org-table-check-inside-data-field)
10207 (org-table-get-specials)
10208 (let* (fields
10209 (ndown (if (integerp arg) arg 1))
10210 (org-table-automatic-realign nil)
10211 (case-fold-search nil)
10212 (down (> ndown 1))
10213 (formula (if (and equation suppress-store)
10214 equation
10215 (org-table-get-formula equation (equal arg '(4)))))
10216 (n0 (org-table-current-column))
10217 (modes (copy-sequence org-calc-default-modes))
10218 n form fmt x ev orig c)
10219 ;; Parse the format string. Since we have a lot of modes, this is
10220 ;; a lot of work. However, I think calc still uses most of the time.
10221 (if (string-match ";" formula)
10222 (let ((tmp (org-split-string formula ";")))
10223 (setq formula (car tmp)
10224 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10225 (nth 1 tmp)))
10226 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10227 (setq c (string-to-char (match-string 1 fmt))
10228 n (string-to-number (or (match-string 1 fmt) "")))
10229 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10230 (setq modes (org-set-calc-mode
10231 'calc-float-format
10232 (list (cdr (assoc c '((?n . float) (?f . fix)
10233 (?s . sci) (?e . eng))))
10234 n))))
10235 (setq fmt (replace-match "" t t fmt)))
10236 (while (string-match "[DRFS]" fmt)
10237 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10238 (setq fmt (replace-match "" t t fmt)))
10239 (unless (string-match "\\S-" fmt)
10240 (setq fmt nil))))
10241 (if (and (not suppress-const) org-table-formula-use-constants)
10242 (setq formula (org-table-formula-substitute-names formula)))
10243 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10244 (while (> ndown 0)
10245 (setq fields (org-split-string
10246 (buffer-substring
10247 (point-at-bol) (point-at-eol)) " *| *"))
10248 (if org-table-formula-numbers-only
10249 (setq fields (mapcar
10250 (lambda (x) (number-to-string (string-to-number x)))
10251 fields)))
10252 (setq ndown (1- ndown))
10253 (setq form (copy-sequence formula))
10254 ;; Insert the references to fields in same row
10255 (while (string-match "\\$\\([0-9]+\\)?" form)
10256 (setq n (if (match-beginning 1)
10257 (string-to-number (match-string 1 form))
10259 x (nth (1- n) fields))
10260 (unless x (error "Invalid field specifier \"%s\""
10261 (match-string 0 form)))
10262 (if (equal x "") (setq x "0"))
10263 (setq form (replace-match (concat "(" x ")") t t form)))
10264 ;; Insert ranges in current column
10265 (while (string-match "\\&[-I0-9]+" form)
10266 (setq form (replace-match
10267 (save-match-data
10268 (org-table-get-vertical-vector (match-string 0 form)
10269 nil n0))
10270 t t form)))
10271 (setq ev (calc-eval (cons form modes)
10272 (if org-table-formula-numbers-only 'num)))
10274 (when org-table-formula-debug
10275 (with-output-to-temp-buffer "*Help*"
10276 (princ (format "Substitution history of formula
10277 Orig: %s
10278 $xyz-> %s
10279 $1-> %s\n" orig formula form))
10280 (if (listp ev)
10281 (princ (format " %s^\nError: %s"
10282 (make-string (car ev) ?\-) (nth 1 ev)))
10283 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10284 ev (or fmt "NONE")
10285 (if fmt (format fmt (string-to-number ev)) ev)))))
10286 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10287 (unless (and (interactive-p) (not ndown))
10288 (unless (let (inhibit-redisplay)
10289 (y-or-n-p "Debugging Formula. Continue to next? "))
10290 (org-table-align)
10291 (error "Abort"))
10292 (delete-window (get-buffer-window "*Help*"))
10293 (message "")))
10294 (if (listp ev) (setq fmt nil ev "#ERROR"))
10295 (org-table-justify-field-maybe
10296 (if fmt (format fmt (string-to-number ev)) ev))
10297 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10298 (call-interactively 'org-return)
10299 (setq ndown 0)))
10300 (and down (org-table-maybe-recalculate-line))
10301 (or suppress-align (and org-table-may-need-update
10302 (org-table-align)))))
10304 (defun org-table-recalculate (&optional all noalign)
10305 "Recalculate the current table line by applying all stored formulas.
10306 With prefix arg ALL, do this for all lines in the table."
10307 (interactive "P")
10308 (or (memq this-command org-recalc-commands)
10309 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10310 (unless (org-at-table-p) (error "Not at a table"))
10311 (org-table-get-specials)
10312 (let* ((eqlist (sort (org-table-get-stored-formulas)
10313 (lambda (a b) (string< (car a) (car b)))))
10314 (inhibit-redisplay t)
10315 (line-re org-table-dataline-regexp)
10316 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10317 (thiscol (org-table-current-column))
10318 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10319 ;; Insert constants in all formulas
10320 (setq eqlist
10321 (mapcar (lambda (x)
10322 (setcdr x (org-table-formula-substitute-names (cdr x)))
10324 eqlist))
10325 ;; Split the equation list
10326 (while (setq eq (pop eqlist))
10327 (if (<= (string-to-char (car eq)) ?9)
10328 (push eq eqlnum)
10329 (push eq eqlname)))
10330 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10331 (if all
10332 (progn
10333 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10334 (goto-char (setq beg (org-table-begin)))
10335 (if (re-search-forward org-table-calculate-mark-regexp end t)
10336 ;; This is a table with marked lines, only compute selected lines
10337 (setq line-re org-table-recalculate-regexp)
10338 ;; Move forward to the first non-header line
10339 (if (and (re-search-forward org-table-dataline-regexp end t)
10340 (re-search-forward org-table-hline-regexp end t)
10341 (re-search-forward org-table-dataline-regexp end t))
10342 (setq beg (match-beginning 0))
10343 nil))) ;; just leave beg where it is
10344 (setq beg (point-at-bol)
10345 end (move-marker (make-marker) (1+ (point-at-eol)))))
10346 (goto-char beg)
10347 (and all (message "Re-applying formulas to full table..."))
10348 (while (re-search-forward line-re end t)
10349 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10350 ;; Unprotected line, recalculate
10351 (and all (message "Re-applying formulas to full table...(line %d)"
10352 (setq cnt (1+ cnt))))
10353 (setq org-last-recalc-line (org-current-line))
10354 (setq eql eqlnum)
10355 (while (setq entry (pop eql))
10356 (goto-line org-last-recalc-line)
10357 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10358 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10359 (goto-line thisline)
10360 (org-table-goto-column thiscol)
10361 (or noalign (and org-table-may-need-update (org-table-align))
10362 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10363 ;; Now do the names fields
10364 (while (setq eq (pop eqlname))
10365 (setq name (car eq)
10366 a (assoc name org-table-named-field-locations))
10367 (when a
10368 (message "Re-applying formula to named field: %s" name)
10369 (goto-line (nth 1 a))
10370 (org-table-goto-column (nth 2 a))
10371 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10372 ;; back to initial position
10373 (goto-line thisline)
10374 (org-table-goto-column thiscol)
10375 (or noalign (and org-table-may-need-update (org-table-align))
10376 (and all (message "Re-applying formulas...done")))))
10378 (defun org-table-formula-substitute-names (f)
10379 "Replace $const with values in string F."
10380 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10381 ;; First, check for column names
10382 (while (setq start (string-match org-table-column-name-regexp f start))
10383 (setq start (1+ start))
10384 (setq a (assoc (match-string 1 f) org-table-column-names))
10385 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10386 ;; Expand ranges to vectors
10387 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10388 (setq n1 (string-to-number (match-string 1 f))
10389 n2 (string-to-number (match-string 2 f))
10390 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10391 s (concat "[($" (number-to-string (1- nn1)) ")"))
10392 (loop for i from nn1 upto nn2 do
10393 (setq s (concat s ",($" (int-to-string i) ")")))
10394 (setq s (concat s "]"))
10395 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10396 (setq f (replace-match s t t f)))
10397 ;; Parameters and constants
10398 (setq start 0)
10399 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10400 (setq start (1+ start))
10401 (if (setq a (save-match-data
10402 (org-table-get-constant (match-string 1 f))))
10403 (setq f (replace-match (concat "(" a ")") t t f))))
10404 (if org-table-formula-debug
10405 (put-text-property 0 (length f) :orig-formula f1 f))
10408 (defun org-table-get-constant (const)
10409 "Find the value for a parameter or constant in a formula.
10410 Parameters get priority."
10411 (or (cdr (assoc const org-table-local-parameters))
10412 (cdr (assoc const org-table-formula-constants))
10413 (and (fboundp 'constants-get) (constants-get const))
10414 "#UNDEFINED_NAME"))
10416 (defvar org-edit-formulas-map (make-sparse-keymap))
10417 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10418 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10419 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10421 (defvar org-pos)
10423 (defun org-table-edit-formulas ()
10424 "Edit the formulas of the current table in a separate buffer."
10425 (interactive)
10426 (unless (org-at-table-p)
10427 (error "Not at a table"))
10428 (org-table-get-specials)
10429 (let ((eql (org-table-get-stored-formulas))
10430 (pos (move-marker (make-marker) (point)))
10431 (wc (current-window-configuration))
10432 entry loc s)
10433 (switch-to-buffer-other-window "*Edit Formulas*")
10434 (erase-buffer)
10435 (fundamental-mode)
10436 (set (make-local-variable 'org-pos) pos)
10437 (set (make-local-variable 'org-window-configuration) wc)
10438 (use-local-map org-edit-formulas-map)
10439 (setq s "# Edit formulas and finish with `C-c C-c'.
10440 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10441 # Use `C-c ?' to get information about $name at point.
10442 # To cancel editing, press `C-c C-q'.\n")
10443 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10444 (insert s)
10445 (while (setq entry (pop eql))
10446 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10447 (setq s (format "# Named formula, referring to column %d in line %d\n"
10448 (nth 2 loc) (nth 1 loc)))
10449 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10450 (insert s))
10451 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10452 (remove-text-properties 0 (length s) '(face nil) s)
10453 (insert s))
10454 (goto-char (point-min))
10455 (message "Edit formulas and finish with `C-c C-c'.")))
10457 (defun org-show-variable ()
10458 "Show the location/value of the $ expression at point."
10459 (interactive)
10460 (let (var (pos org-pos) (win (selected-window)) e)
10461 (save-excursion
10462 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10463 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10464 (setq var (match-string 1))
10465 (error "No variable at point")))
10466 (cond
10467 ((setq e (assoc var org-table-named-field-locations))
10468 (switch-to-buffer-other-window (marker-buffer pos))
10469 (goto-line (nth 1 e))
10470 (org-table-goto-column (nth 2 e))
10471 (select-window win)
10472 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10473 ((setq e (assoc var org-table-column-names))
10474 (switch-to-buffer-other-window (marker-buffer pos))
10475 (goto-char pos)
10476 (goto-char (org-table-begin))
10477 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10478 (org-table-end) t)
10479 (progn
10480 (goto-char (match-beginning 1))
10481 (message "Named column (column %s)" (cdr e)))
10482 (error "Column name not found"))
10483 (select-window win))
10484 ((string-match "^[0-9]$" var)
10485 ;; column number
10486 (switch-to-buffer-other-window (marker-buffer pos))
10487 (goto-char pos)
10488 (goto-char (org-table-begin))
10489 (recenter 1)
10490 (if (re-search-forward org-table-dataline-regexp
10491 (org-table-end) t)
10492 (progn
10493 (goto-char (match-beginning 0))
10494 (org-table-goto-column (string-to-number var))
10495 (message "Column %s" var))
10496 (error "Column name not found"))
10497 (select-window win))
10498 ((setq e (assoc var org-table-local-parameters))
10499 (switch-to-buffer-other-window (marker-buffer pos))
10500 (goto-char pos)
10501 (goto-char (org-table-begin))
10502 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10503 (progn
10504 (goto-char (match-beginning 1))
10505 (message "Local parameter."))
10506 (error "Parameter not found"))
10507 (select-window win))
10509 (cond
10510 ((setq e (assoc var org-table-formula-constants))
10511 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10512 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10513 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10514 (t (error "Undefined name $%s" var)))))))
10516 (defun org-finish-edit-formulas (&optional arg)
10517 "Parse the buffer for formula definitions and install them.
10518 With prefix ARG, apply the new formulas to the table."
10519 (interactive "P")
10520 (let ((pos org-pos) eql)
10521 (goto-char (point-min))
10522 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10523 (push (cons (match-string 1) (match-string 2)) eql))
10524 (set-window-configuration org-window-configuration)
10525 (select-window (get-buffer-window (marker-buffer pos)))
10526 (goto-char pos)
10527 (unless (org-at-table-p)
10528 (error "Lost table position - cannot install formulae"))
10529 (org-table-store-formulas eql)
10530 (move-marker pos nil)
10531 (kill-buffer "*Edit Formulas*")
10532 (if arg
10533 (org-table-recalculate 'all)
10534 (message "New formulas installed - press C-u C-c C-c to apply."))))
10536 (defun org-abort-edit-formulas ()
10537 "Abort editing formulas, without installing the changes."
10538 (interactive)
10539 (let ((pos org-pos))
10540 (set-window-configuration org-window-configuration)
10541 (select-window (get-buffer-window (marker-buffer pos)))
10542 (goto-char pos)
10543 (message "Formula editing aborted without installing changes")))
10545 ;;; The orgtbl minor mode
10547 ;; Define a minor mode which can be used in other modes in order to
10548 ;; integrate the org-mode table editor.
10550 ;; This is really a hack, because the org-mode table editor uses several
10551 ;; keys which normally belong to the major mode, for example the TAB and
10552 ;; RET keys. Here is how it works: The minor mode defines all the keys
10553 ;; necessary to operate the table editor, but wraps the commands into a
10554 ;; function which tests if the cursor is currently inside a table. If that
10555 ;; is the case, the table editor command is executed. However, when any of
10556 ;; those keys is used outside a table, the function uses `key-binding' to
10557 ;; look up if the key has an associated command in another currently active
10558 ;; keymap (minor modes, major mode, global), and executes that command.
10559 ;; There might be problems if any of the keys used by the table editor is
10560 ;; otherwise used as a prefix key.
10562 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10563 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10564 ;; addresses this by checking explicitly for both bindings.
10566 ;; The optimized version (see variable `orgtbl-optimized') takes over
10567 ;; all keys which are bound to `self-insert-command' in the *global map*.
10568 ;; Some modes bind other commands to simple characters, for example
10569 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10570 ;; active, this binding is ignored inside tables and replaced with a
10571 ;; modified self-insert.
10573 (defvar orgtbl-mode nil
10574 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10575 table editor in arbitrary modes.")
10576 (make-variable-buffer-local 'orgtbl-mode)
10578 (defvar orgtbl-mode-map (make-keymap)
10579 "Keymap for `orgtbl-mode'.")
10581 ;;;###autoload
10582 (defun turn-on-orgtbl ()
10583 "Unconditionally turn on `orgtbl-mode'."
10584 (orgtbl-mode 1))
10586 ;;;###autoload
10587 (defun orgtbl-mode (&optional arg)
10588 "The `org-mode' table editor as a minor mode for use in other modes."
10589 (interactive)
10590 (if (eq major-mode 'org-mode)
10591 ;; Exit without error, in case some hook functions calls this
10592 ;; by accident in org-mode.
10593 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10594 (setq orgtbl-mode
10595 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10596 (if orgtbl-mode
10597 (progn
10598 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10599 ;; Make sure we are first in minor-mode-map-alist
10600 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10601 (and c (setq minor-mode-map-alist
10602 (cons c (delq c minor-mode-map-alist)))))
10603 (set (make-local-variable (quote org-table-may-need-update)) t)
10604 (org-add-hook 'before-change-functions 'org-before-change-function
10605 nil 'local)
10606 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10607 auto-fill-inhibit-regexp)
10608 (set (make-local-variable 'auto-fill-inhibit-regexp)
10609 (if auto-fill-inhibit-regexp
10610 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10611 "[ \t]*|"))
10612 (org-add-to-invisibility-spec '(org-cwidth))
10613 (easy-menu-add orgtbl-mode-menu)
10614 (run-hooks 'orgtbl-mode-hook))
10615 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10616 (org-cleanup-narrow-column-properties)
10617 (org-remove-from-invisibility-spec '(org-cwidth))
10618 (remove-hook 'before-change-functions 'org-before-change-function t)
10619 (easy-menu-remove orgtbl-mode-menu)
10620 (force-mode-line-update 'all))))
10622 (defun org-cleanup-narrow-column-properties ()
10623 "Remove all properties related to narrow-column invisibility."
10624 (let ((s 1))
10625 (while (setq s (text-property-any s (point-max)
10626 'display org-narrow-column-arrow))
10627 (remove-text-properties s (1+ s) '(display t)))
10628 (setq s 1)
10629 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10630 (remove-text-properties s (1+ s) '(org-cwidth t)))
10631 (setq s 1)
10632 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10633 (remove-text-properties s (1+ s) '(invisible t)))))
10635 ;; Install it as a minor mode.
10636 (put 'orgtbl-mode :included t)
10637 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10638 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10640 (defun orgtbl-make-binding (fun n &rest keys)
10641 "Create a function for binding in the table minor mode.
10642 FUN is the command to call inside a table. N is used to create a unique
10643 command name. KEYS are keys that should be checked in for a command
10644 to execute outside of tables."
10645 (eval
10646 (list 'defun
10647 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10648 '(arg)
10649 (concat "In tables, run `" (symbol-name fun) "'.\n"
10650 "Outside of tables, run the binding of `"
10651 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10652 "'.")
10653 '(interactive "p")
10654 (list 'if
10655 '(org-at-table-p)
10656 (list 'call-interactively (list 'quote fun))
10657 (list 'let '(orgtbl-mode)
10658 (list 'call-interactively
10659 (append '(or)
10660 (mapcar (lambda (k)
10661 (list 'key-binding k))
10662 keys)
10663 '('orgtbl-error))))))))
10665 (defun orgtbl-error ()
10666 "Error when there is no default binding for a table key."
10667 (interactive)
10668 (error "This key is has no function outside tables"))
10670 (defun orgtbl-setup ()
10671 "Setup orgtbl keymaps."
10672 (let ((nfunc 0)
10673 (bindings
10674 (list
10675 '([(meta shift left)] org-table-delete-column)
10676 '([(meta left)] org-table-move-column-left)
10677 '([(meta right)] org-table-move-column-right)
10678 '([(meta shift right)] org-table-insert-column)
10679 '([(meta shift up)] org-table-kill-row)
10680 '([(meta shift down)] org-table-insert-row)
10681 '([(meta up)] org-table-move-row-up)
10682 '([(meta down)] org-table-move-row-down)
10683 '("\C-c\C-w" org-table-cut-region)
10684 '("\C-c\M-w" org-table-copy-region)
10685 '("\C-c\C-y" org-table-paste-rectangle)
10686 '("\C-c-" org-table-insert-hline)
10687 ; '([(shift tab)] org-table-previous-field)
10688 '("\C-m" org-table-next-row)
10689 (list (org-key 'S-return) 'org-table-copy-down)
10690 '([(meta return)] org-table-wrap-region)
10691 '("\C-c\C-q" org-table-wrap-region)
10692 '("\C-c?" org-table-current-column)
10693 '("\C-c " org-table-blank-field)
10694 '("\C-c+" org-table-sum)
10695 '("\C-c=" org-table-eval-formula)
10696 '("\C-c'" org-table-edit-formulas)
10697 '("\C-c`" org-table-edit-field)
10698 '("\C-c*" org-table-recalculate)
10699 '("\C-c|" org-table-create-or-convert-from-region)
10700 '("\C-c^" org-table-sort-lines)
10701 '([(control ?#)] org-table-rotate-recalc-marks)))
10702 elt key fun cmd)
10703 (while (setq elt (pop bindings))
10704 (setq nfunc (1+ nfunc))
10705 (setq key (car elt)
10706 fun (nth 1 elt)
10707 cmd (orgtbl-make-binding fun nfunc key))
10708 (define-key orgtbl-mode-map key cmd))
10709 ;; Special treatment needed for TAB and RET
10710 (define-key orgtbl-mode-map [(return)]
10711 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10712 (define-key orgtbl-mode-map "\C-m"
10713 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10714 (define-key orgtbl-mode-map [(tab)]
10715 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10716 (define-key orgtbl-mode-map "\C-i"
10717 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10718 (define-key orgtbl-mode-map "\C-i"
10719 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10720 (define-key orgtbl-mode-map "\C-c\C-c"
10721 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10722 (when orgtbl-optimized
10723 ;; If the user wants maximum table support, we need to hijack
10724 ;; some standard editing functions
10725 (org-remap orgtbl-mode-map
10726 'self-insert-command 'orgtbl-self-insert-command
10727 'delete-char 'org-delete-char
10728 'delete-backward-char 'org-delete-backward-char)
10729 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10730 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10731 '("OrgTbl"
10732 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10733 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10734 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10735 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10736 "--"
10737 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10738 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10739 ["Copy Field from Above"
10740 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10741 "--"
10742 ("Column"
10743 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10744 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10745 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10746 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10747 "--"
10748 ["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])
10749 ("Row"
10750 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10751 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10752 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10753 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10754 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10755 "--"
10756 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10757 ("Rectangle"
10758 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10759 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10760 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10761 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10762 "--"
10763 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10764 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10765 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10766 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10767 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10768 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10769 ["Sum Column/Rectangle" org-table-sum
10770 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10771 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10772 ["Debug Formulas"
10773 (setq org-table-formula-debug (not org-table-formula-debug))
10774 :style toggle :selected org-table-formula-debug]
10778 (defun orgtbl-tab (arg)
10779 "Justification and field motion for `orgtbl-mode'."
10780 (interactive "P")
10781 (if arg (org-table-edit-field t)
10782 (org-table-justify-field-maybe)
10783 (org-table-next-field)))
10785 (defun orgtbl-ret ()
10786 "Justification and field motion for `orgtbl-mode'."
10787 (interactive)
10788 (org-table-justify-field-maybe)
10789 (org-table-next-row))
10791 (defun orgtbl-self-insert-command (N)
10792 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10793 If the cursor is in a table looking at whitespace, the whitespace is
10794 overwritten, and the table is not marked as requiring realignment."
10795 (interactive "p")
10796 (if (and (org-at-table-p)
10798 (and org-table-auto-blank-field
10799 (member last-command
10800 '(orgtbl-hijacker-command-100
10801 orgtbl-hijacker-command-101
10802 orgtbl-hijacker-command-102
10803 orgtbl-hijacker-command-103
10804 orgtbl-hijacker-command-104
10805 orgtbl-hijacker-command-105))
10806 (org-table-blank-field))
10808 (eq N 1)
10809 (looking-at "[^|\n]* +|"))
10810 (let (org-table-may-need-update)
10811 (goto-char (1- (match-end 0)))
10812 (delete-backward-char 1)
10813 (goto-char (match-beginning 0))
10814 (self-insert-command N))
10815 (setq org-table-may-need-update t)
10816 (let (orgtbl-mode)
10817 (call-interactively (key-binding (vector last-input-event))))))
10819 (defun org-force-self-insert (N)
10820 "Needed to enforce self-insert under remapping."
10821 (interactive "p")
10822 (self-insert-command N))
10824 ;;; Exporting
10826 (defconst org-level-max 20)
10828 (defun org-export-find-first-heading-line (list)
10829 "Remove all lines from LIST which are before the first headline."
10830 (let ((orig-list list)
10831 (re (concat "^" outline-regexp)))
10832 (while (and list
10833 (not (string-match re (car list))))
10834 (pop list))
10835 (or list orig-list)))
10837 (defun org-skip-comments (lines)
10838 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10839 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10840 (re2 "^\\(\\*+\\)[ \t\n\r]")
10841 rtn line level)
10842 (while (setq line (pop lines))
10843 (cond
10844 ((and (string-match re1 line)
10845 (setq level (- (match-end 1) (match-beginning 1))))
10846 ;; Beginning of a COMMENT subtree. Skip it.
10847 (while (and (setq line (pop lines))
10848 (or (not (string-match re2 line))
10849 (> (- (match-end 1) (match-beginning 1)) level))))
10850 (setq lines (cons line lines)))
10851 ((string-match "^#" line)
10852 ;; an ordinary comment line
10854 ((and org-export-table-remove-special-lines
10855 (string-match "^[ \t]*| *[!_^] *|" line))
10856 ;; a special table line that should be removed
10858 (t (setq rtn (cons line rtn)))))
10859 (nreverse rtn)))
10861 ;; ASCII
10863 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10864 "Characters for underlining headings in ASCII export.")
10866 (defconst org-html-entities
10867 '(("nbsp")
10868 ("iexcl")
10869 ("cent")
10870 ("pound")
10871 ("curren")
10872 ("yen")
10873 ("brvbar")
10874 ("sect")
10875 ("uml")
10876 ("copy")
10877 ("ordf")
10878 ("laquo")
10879 ("not")
10880 ("shy")
10881 ("reg")
10882 ("macr")
10883 ("deg")
10884 ("plusmn")
10885 ("sup2")
10886 ("sup3")
10887 ("acute")
10888 ("micro")
10889 ("para")
10890 ("middot")
10891 ("odot"."o")
10892 ("star"."*")
10893 ("cedil")
10894 ("sup1")
10895 ("ordm")
10896 ("raquo")
10897 ("frac14")
10898 ("frac12")
10899 ("frac34")
10900 ("iquest")
10901 ("Agrave")
10902 ("Aacute")
10903 ("Acirc")
10904 ("Atilde")
10905 ("Auml")
10906 ("Aring") ("AA"."&Aring;")
10907 ("AElig")
10908 ("Ccedil")
10909 ("Egrave")
10910 ("Eacute")
10911 ("Ecirc")
10912 ("Euml")
10913 ("Igrave")
10914 ("Iacute")
10915 ("Icirc")
10916 ("Iuml")
10917 ("ETH")
10918 ("Ntilde")
10919 ("Ograve")
10920 ("Oacute")
10921 ("Ocirc")
10922 ("Otilde")
10923 ("Ouml")
10924 ("times")
10925 ("Oslash")
10926 ("Ugrave")
10927 ("Uacute")
10928 ("Ucirc")
10929 ("Uuml")
10930 ("Yacute")
10931 ("THORN")
10932 ("szlig")
10933 ("agrave")
10934 ("aacute")
10935 ("acirc")
10936 ("atilde")
10937 ("auml")
10938 ("aring")
10939 ("aelig")
10940 ("ccedil")
10941 ("egrave")
10942 ("eacute")
10943 ("ecirc")
10944 ("euml")
10945 ("igrave")
10946 ("iacute")
10947 ("icirc")
10948 ("iuml")
10949 ("eth")
10950 ("ntilde")
10951 ("ograve")
10952 ("oacute")
10953 ("ocirc")
10954 ("otilde")
10955 ("ouml")
10956 ("divide")
10957 ("oslash")
10958 ("ugrave")
10959 ("uacute")
10960 ("ucirc")
10961 ("uuml")
10962 ("yacute")
10963 ("thorn")
10964 ("yuml")
10965 ("fnof")
10966 ("Alpha")
10967 ("Beta")
10968 ("Gamma")
10969 ("Delta")
10970 ("Epsilon")
10971 ("Zeta")
10972 ("Eta")
10973 ("Theta")
10974 ("Iota")
10975 ("Kappa")
10976 ("Lambda")
10977 ("Mu")
10978 ("Nu")
10979 ("Xi")
10980 ("Omicron")
10981 ("Pi")
10982 ("Rho")
10983 ("Sigma")
10984 ("Tau")
10985 ("Upsilon")
10986 ("Phi")
10987 ("Chi")
10988 ("Psi")
10989 ("Omega")
10990 ("alpha")
10991 ("beta")
10992 ("gamma")
10993 ("delta")
10994 ("epsilon")
10995 ("varepsilon"."&epsilon;")
10996 ("zeta")
10997 ("eta")
10998 ("theta")
10999 ("iota")
11000 ("kappa")
11001 ("lambda")
11002 ("mu")
11003 ("nu")
11004 ("xi")
11005 ("omicron")
11006 ("pi")
11007 ("rho")
11008 ("sigmaf") ("varsigma"."&sigmaf;")
11009 ("sigma")
11010 ("tau")
11011 ("upsilon")
11012 ("phi")
11013 ("chi")
11014 ("psi")
11015 ("omega")
11016 ("thetasym") ("vartheta"."&thetasym;")
11017 ("upsih")
11018 ("piv")
11019 ("bull") ("bullet"."&bull;")
11020 ("hellip") ("dots"."&hellip;")
11021 ("prime")
11022 ("Prime")
11023 ("oline")
11024 ("frasl")
11025 ("weierp")
11026 ("image")
11027 ("real")
11028 ("trade")
11029 ("alefsym")
11030 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
11031 ("uarr") ("uparrow"."&uarr;")
11032 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
11033 ("darr")("downarrow"."&darr;")
11034 ("harr") ("leftrightarrow"."&harr;")
11035 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
11036 ("lArr") ("Leftarrow"."&lArr;")
11037 ("uArr") ("Uparrow"."&uArr;")
11038 ("rArr") ("Rightarrow"."&rArr;")
11039 ("dArr") ("Downarrow"."&dArr;")
11040 ("hArr") ("Leftrightarrow"."&hArr;")
11041 ("forall")
11042 ("part") ("partial"."&part;")
11043 ("exist") ("exists"."&exist;")
11044 ("empty") ("emptyset"."&empty;")
11045 ("nabla")
11046 ("isin") ("in"."&isin;")
11047 ("notin")
11048 ("ni")
11049 ("prod")
11050 ("sum")
11051 ("minus")
11052 ("lowast") ("ast"."&lowast;")
11053 ("radic")
11054 ("prop") ("proptp"."&prop;")
11055 ("infin") ("infty"."&infin;")
11056 ("ang") ("angle"."&ang;")
11057 ("and") ("vee"."&and;")
11058 ("or") ("wedge"."&or;")
11059 ("cap")
11060 ("cup")
11061 ("int")
11062 ("there4")
11063 ("sim")
11064 ("cong") ("simeq"."&cong;")
11065 ("asymp")("approx"."&asymp;")
11066 ("ne") ("neq"."&ne;")
11067 ("equiv")
11068 ("le")
11069 ("ge")
11070 ("sub") ("subset"."&sub;")
11071 ("sup") ("supset"."&sup;")
11072 ("nsub")
11073 ("sube")
11074 ("supe")
11075 ("oplus")
11076 ("otimes")
11077 ("perp")
11078 ("sdot") ("cdot"."&sdot;")
11079 ("lceil")
11080 ("rceil")
11081 ("lfloor")
11082 ("rfloor")
11083 ("lang")
11084 ("rang")
11085 ("loz") ("Diamond"."&loz;")
11086 ("spades") ("spadesuit"."&spades;")
11087 ("clubs") ("clubsuit"."&clubs;")
11088 ("hearts") ("diamondsuit"."&hearts;")
11089 ("diams") ("diamondsuit"."&diams;")
11090 ("quot")
11091 ("amp")
11092 ("lt")
11093 ("gt")
11094 ("OElig")
11095 ("oelig")
11096 ("Scaron")
11097 ("scaron")
11098 ("Yuml")
11099 ("circ")
11100 ("tilde")
11101 ("ensp")
11102 ("emsp")
11103 ("thinsp")
11104 ("zwnj")
11105 ("zwj")
11106 ("lrm")
11107 ("rlm")
11108 ("ndash")
11109 ("mdash")
11110 ("lsquo")
11111 ("rsquo")
11112 ("sbquo")
11113 ("ldquo")
11114 ("rdquo")
11115 ("bdquo")
11116 ("dagger")
11117 ("Dagger")
11118 ("permil")
11119 ("lsaquo")
11120 ("rsaquo")
11121 ("euro")
11123 ("arccos"."arccos")
11124 ("arcsin"."arcsin")
11125 ("arctan"."arctan")
11126 ("arg"."arg")
11127 ("cos"."cos")
11128 ("cosh"."cosh")
11129 ("cot"."cot")
11130 ("coth"."coth")
11131 ("csc"."csc")
11132 ("deg"."deg")
11133 ("det"."det")
11134 ("dim"."dim")
11135 ("exp"."exp")
11136 ("gcd"."gcd")
11137 ("hom"."hom")
11138 ("inf"."inf")
11139 ("ker"."ker")
11140 ("lg"."lg")
11141 ("lim"."lim")
11142 ("liminf"."liminf")
11143 ("limsup"."limsup")
11144 ("ln"."ln")
11145 ("log"."log")
11146 ("max"."max")
11147 ("min"."min")
11148 ("Pr"."Pr")
11149 ("sec"."sec")
11150 ("sin"."sin")
11151 ("sinh"."sinh")
11152 ("sup"."sup")
11153 ("tan"."tan")
11154 ("tanh"."tanh")
11156 "Entities for TeX->HTML translation.
11157 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11158 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11159 In that case, \"\\ent\" will be translated to \"&other;\".
11160 The list contains HTML entities for Latin-1, Greek and other symbols.
11161 It is supplemented by a number of commonly used TeX macros with appropriate
11162 translations. There is currently no way for users to extend this.")
11164 (defun org-cleaned-string-for-export (string)
11165 "Cleanup a buffer substring so that links can be created safely."
11166 (interactive)
11167 (let* ((cb (current-buffer))
11168 (re-radio (and org-target-link-regexp
11169 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11170 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11171 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11172 rtn)
11173 (save-excursion
11174 (set-buffer (get-buffer-create " org-mode-tmp"))
11175 (erase-buffer)
11176 (insert string)
11177 (org-mode)
11178 ;; Find targets in comments and move them out of comments,
11179 ;; but mark them as targets that should be invisible
11180 (goto-char (point-min))
11181 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11182 (replace-match "\\1(INVISIBLE)"))
11183 ;; Find matches for radio targets and turn them into internal links
11184 (goto-char (point-min))
11185 (when re-radio
11186 (while (re-search-forward re-radio nil t)
11187 (replace-match "\\1[[\\2]]")))
11188 ;; Find all links that contain a newline and put them into a single line
11189 (goto-char (point-min))
11190 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11191 (replace-match "\\1 \\3")
11192 (goto-char (match-beginning 0)))
11193 ;; Normalize links: Convert angle and plain links into bracket links
11194 (goto-char (point-min))
11195 (while (re-search-forward re-plain-link nil t)
11196 (replace-match
11197 (concat
11198 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11199 t t))
11200 (goto-char (point-min))
11201 (while (re-search-forward re-angle-link nil t)
11202 (replace-match
11203 (concat
11204 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11205 t t))
11207 ;; Remove comments
11208 (goto-char (point-min))
11209 (while (re-search-forward "^#.*\n?" nil t)
11210 (replace-match ""))
11211 (setq rtn (buffer-string)))
11212 (kill-buffer " org-mode-tmp")
11213 rtn))
11215 (defun org-solidify-link-text (s &optional alist)
11216 "Take link text and make a safe target out of it."
11217 (save-match-data
11218 (let* ((rtn
11219 (mapconcat
11220 'identity
11221 (org-split-string s "[ \t\r\n]+") "--"))
11222 (a (assoc rtn alist)))
11223 (or (cdr a) rtn))))
11225 (defun org-convert-to-odd-levels ()
11226 "Convert an org-mode file with all levels allowed to one with odd levels.
11227 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11228 level 5 etc."
11229 (interactive)
11230 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11231 (let ((org-odd-levels-only nil) n)
11232 (save-excursion
11233 (goto-char (point-min))
11234 (while (re-search-forward "^\\*\\*+" nil t)
11235 (setq n (1- (length (match-string 0))))
11236 (while (>= (setq n (1- n)) 0)
11237 (org-demote))
11238 (end-of-line 1))))))
11241 (defun org-convert-to-oddeven-levels ()
11242 "Convert an org-mode file with only odd levels to one with odd and even levels.
11243 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11244 section with an even level, conversion would destroy the structure of the file. An error
11245 is signaled in this case."
11246 (interactive)
11247 (goto-char (point-min))
11248 ;; First check if there are no even levels
11249 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11250 (org-show-hierarchy-above)
11251 (error "Not all levels are odd in this file. Conversion not possible."))
11252 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11253 (let ((org-odd-levels-only nil) n)
11254 (save-excursion
11255 (goto-char (point-min))
11256 (while (re-search-forward "^\\*\\*+" nil t)
11257 (setq n (/ (length (match-string 0)) 2))
11258 (while (>= (setq n (1- n)) 0)
11259 (org-promote))
11260 (end-of-line 1))))))
11262 (defun org-tr-level (n)
11263 "Make N odd if required."
11264 (if org-odd-levels-only (1+ (/ n 2)) n))
11266 (defvar org-last-level nil) ; dynamically scoped variable
11268 (defun org-export-as-ascii (arg)
11269 "Export the outline as a pretty ASCII file.
11270 If there is an active region, export only the region.
11271 The prefix ARG specifies how many levels of the outline should become
11272 underlined headlines. The default is 3."
11273 (interactive "P")
11274 (setq-default org-todo-line-regexp org-todo-line-regexp)
11275 (let* ((region
11276 (buffer-substring
11277 (if (org-region-active-p) (region-beginning) (point-min))
11278 (if (org-region-active-p) (region-end) (point-max))))
11279 (lines (org-export-find-first-heading-line
11280 (org-skip-comments
11281 (org-split-string
11282 (org-cleaned-string-for-export region)
11283 "[\r\n]"))))
11284 (org-startup-with-deadline-check nil)
11285 (level 0) line txt
11286 (umax nil)
11287 (case-fold-search nil)
11288 (filename (concat (file-name-sans-extension buffer-file-name)
11289 ".txt"))
11290 (buffer (find-file-noselect filename))
11291 (levels-open (make-vector org-level-max nil))
11292 (date (format-time-string "%Y/%m/%d" (current-time)))
11293 (time (format-time-string "%X" (org-current-time)))
11294 (author user-full-name)
11295 (title (buffer-name))
11296 (options nil)
11297 (email user-mail-address)
11298 (language org-export-default-language)
11299 (text nil)
11300 (todo nil)
11301 (lang-words nil))
11303 (setq org-last-level 1)
11304 (org-init-section-numbers)
11306 (find-file-noselect filename)
11308 ;; Search for the export key lines
11309 (org-parse-key-lines)
11311 (setq lang-words (or (assoc language org-export-language-setup)
11312 (assoc "en" org-export-language-setup)))
11313 (if org-export-ascii-show-new-buffer
11314 (switch-to-buffer-other-window buffer)
11315 (set-buffer buffer))
11316 (erase-buffer)
11317 (fundamental-mode)
11318 (if options (org-parse-export-options options))
11319 (setq umax (if arg (prefix-numeric-value arg)
11320 org-export-headline-levels))
11322 ;; File header
11323 (if title (org-insert-centered title ?=))
11324 (insert "\n")
11325 (if (or author email)
11326 (insert (concat (nth 1 lang-words) ": " (or author "")
11327 (if email (concat " <" email ">") "")
11328 "\n")))
11329 (if (and date time)
11330 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11331 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11333 (insert "\n\n")
11335 (if org-export-with-toc
11336 (progn
11337 (insert (nth 3 lang-words) "\n"
11338 (make-string (length (nth 3 lang-words)) ?=) "\n")
11339 (mapcar '(lambda (line)
11340 (if (string-match org-todo-line-regexp
11341 line)
11342 ;; This is a headline
11343 (progn
11344 (setq level (- (match-end 1) (match-beginning 1))
11345 level (org-tr-level level)
11346 txt (match-string 3 line)
11347 todo
11348 (or (and (match-beginning 2)
11349 (not (equal (match-string 2 line)
11350 org-done-string)))
11351 ; TODO, not DONE
11352 (and org-export-mark-todo-in-toc
11353 (= level umax)
11354 (org-search-todo-below
11355 line lines level))))
11356 (setq txt (org-html-expand-for-ascii txt))
11358 (if org-export-with-section-numbers
11359 (setq txt (concat (org-section-number level)
11360 " " txt)))
11361 (if (<= level umax)
11362 (progn
11363 (insert
11364 (make-string (* (1- level) 4) ?\ )
11365 (format (if todo "%s (*)\n" "%s\n") txt))
11366 (setq org-last-level level))
11367 ))))
11368 lines)))
11370 (org-init-section-numbers)
11371 (while (setq line (pop lines))
11372 ;; Remove the quoted HTML tags.
11373 (setq line (org-html-expand-for-ascii line))
11374 ;; Remove targets
11375 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11376 (setq line (replace-match "" t t line)))
11377 ;; Replace internal links
11378 (while (string-match org-bracket-link-regexp line)
11379 (setq line (replace-match
11380 (if (match-end 3) "[\\3]" "[\\1]")
11381 t nil line)))
11382 (cond
11383 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11384 ;; a Headline
11385 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11386 txt (match-string 2 line))
11387 (org-ascii-level-start level txt umax))
11388 (t (insert line "\n"))))
11389 (normal-mode)
11390 (save-buffer)
11391 (goto-char (point-min))))
11393 (defun org-search-todo-below (line lines level)
11394 "Search the subtree below LINE for any TODO entries."
11395 (let ((rest (cdr (memq line lines)))
11396 (re org-todo-line-regexp)
11397 line lv todo)
11398 (catch 'exit
11399 (while (setq line (pop rest))
11400 (if (string-match re line)
11401 (progn
11402 (setq lv (- (match-end 1) (match-beginning 1))
11403 todo (and (match-beginning 2)
11404 (not (equal (match-string 2 line)
11405 org-done-string))))
11406 ; TODO, not DONE
11407 (if (<= lv level) (throw 'exit nil))
11408 (if todo (throw 'exit t))))))))
11410 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11411 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11412 (defun org-html-expand-for-ascii (line)
11413 "Handle quoted HTML for ASCII export."
11414 (if org-export-html-expand
11415 (while (string-match "@<[^<>\n]*>" line)
11416 ;; We just remove the tags for now.
11417 (setq line (replace-match "" nil nil line))))
11418 line)
11420 (defun org-insert-centered (s &optional underline)
11421 "Insert the string S centered and underline it with character UNDERLINE."
11422 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11423 (insert (make-string ind ?\ ) s "\n")
11424 (if underline
11425 (insert (make-string ind ?\ )
11426 (make-string (string-width s) underline)
11427 "\n"))))
11429 (defun org-ascii-level-start (level title umax)
11430 "Insert a new level in ASCII export."
11431 (let (char)
11432 (if (> level umax)
11433 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11434 (if (or (not (equal (char-before) ?\n))
11435 (not (equal (char-before (1- (point))) ?\n)))
11436 (insert "\n"))
11437 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11438 (if org-export-with-section-numbers
11439 (setq title (concat (org-section-number level) " " title)))
11440 (insert title "\n" (make-string (string-width title) char) "\n"))))
11442 (defun org-export-copy-visible ()
11443 "Copy the visible part of the buffer to another buffer, for printing.
11444 Also removes the first line of the buffer if it specifies a mode,
11445 and all options lines."
11446 (interactive)
11447 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11448 ".txt"))
11449 (buffer (find-file-noselect filename))
11450 (ore (concat
11451 (org-make-options-regexp
11452 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11453 "STARTUP" "ARCHIVE"
11454 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11455 (if org-noutline-p "\\(\n\\|$\\)" "")))
11456 s e)
11457 (with-current-buffer buffer
11458 (erase-buffer)
11459 (text-mode))
11460 (save-excursion
11461 (setq s (goto-char (point-min)))
11462 (while (not (= (point) (point-max)))
11463 (goto-char (org-find-invisible))
11464 (append-to-buffer buffer s (point))
11465 (setq s (goto-char (org-find-visible)))))
11466 (switch-to-buffer-other-window buffer)
11467 (newline)
11468 (goto-char (point-min))
11469 (if (looking-at ".*-\\*- mode:.*\n")
11470 (replace-match ""))
11471 (while (re-search-forward ore nil t)
11472 (replace-match ""))
11473 (goto-char (point-min))))
11475 (defun org-find-visible ()
11476 (if (featurep 'noutline)
11477 (let ((s (point)))
11478 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11479 (get-char-property s 'invisible)))
11481 (skip-chars-forward "^\n")
11482 (point)))
11483 (defun org-find-invisible ()
11484 (if (featurep 'noutline)
11485 (let ((s (point)))
11486 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11487 (not (get-char-property s 'invisible))))
11489 (skip-chars-forward "^\r")
11490 (point)))
11492 ;; HTML
11494 (defun org-get-current-options ()
11495 "Return a string with current options as keyword options.
11496 Does include HTML export options as well as TODO and CATEGORY stuff."
11497 (format
11498 "#+TITLE: %s
11499 #+AUTHOR: %s
11500 #+EMAIL: %s
11501 #+LANGUAGE: %s
11502 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11503 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11504 #+CATEGORY: %s
11505 #+SEQ_TODO: %s
11506 #+TYP_TODO: %s
11507 #+STARTUP: %s %s %s %s %s
11508 #+ARCHIVE: %s
11510 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11511 org-export-headline-levels
11512 org-export-with-section-numbers
11513 org-export-with-toc
11514 org-export-preserve-breaks
11515 org-export-html-expand
11516 org-export-with-fixed-width
11517 org-export-with-tables
11518 org-export-with-sub-superscripts
11519 org-export-with-emphasize
11520 org-export-with-TeX-macros
11521 (file-name-nondirectory buffer-file-name)
11522 (if (equal org-todo-interpretation 'sequence)
11523 (mapconcat 'identity org-todo-keywords " ")
11524 "TODO FEEDBACK VERIFY DONE")
11525 (if (equal org-todo-interpretation 'type)
11526 (mapconcat 'identity org-todo-keywords " ")
11527 "Me Jason Marie DONE")
11528 (cdr (assoc org-startup-folded
11529 '((nil . "showall") (t . "overview") (content . "content"))))
11530 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11531 (if org-odd-levels-only "odd" "oddeven")
11532 (if org-hide-leading-stars "hidestars" "showstars")
11533 (if org-startup-align-all-tables "align" "noalign")
11534 org-archive-location
11537 (defun org-insert-export-options-template ()
11538 "Insert into the buffer a template with information for exporting."
11539 (interactive)
11540 (if (not (bolp)) (newline))
11541 (let ((s (org-get-current-options)))
11542 (and (string-match "#\\+CATEGORY" s)
11543 (setq s (substring s 0 (match-beginning 0))))
11544 (insert s)))
11546 (defun org-toggle-fixed-width-section (arg)
11547 "Toggle the fixed-width export.
11548 If there is no active region, the QUOTE keyword at the current headline is
11549 inserted or removed. When present, it causes the text between this headline
11550 and the next to be exported as fixed-width text, and unmodified.
11551 If there is an active region, this command adds or removes a colon as the
11552 first character of this line. If the first character of a line is a colon,
11553 this line is also exported in fixed-width font."
11554 (interactive "P")
11555 (let* ((cc 0)
11556 (regionp (org-region-active-p))
11557 (beg (if regionp (region-beginning) (point)))
11558 (end (if regionp (region-end)))
11559 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11560 (re "[ \t]*\\(:\\)")
11561 off)
11562 (if regionp
11563 (save-excursion
11564 (goto-char beg)
11565 (setq cc (current-column))
11566 (beginning-of-line 1)
11567 (setq off (looking-at re))
11568 (while (> nlines 0)
11569 (setq nlines (1- nlines))
11570 (beginning-of-line 1)
11571 (cond
11572 (arg
11573 (move-to-column cc t)
11574 (insert ":\n")
11575 (forward-line -1))
11576 ((and off (looking-at re))
11577 (replace-match "" t t nil 1))
11578 ((not off) (move-to-column cc t) (insert ":")))
11579 (forward-line 1)))
11580 (save-excursion
11581 (org-back-to-heading)
11582 (if (looking-at (concat outline-regexp
11583 "\\( +\\<" org-quote-string "\\>\\)"))
11584 (replace-match "" t t nil 1)
11585 (if (looking-at outline-regexp)
11586 (progn
11587 (goto-char (match-end 0))
11588 (insert " " org-quote-string))))))))
11590 (defun org-export-as-html-and-open (arg)
11591 "Export the outline as HTML and immediately open it with a browser.
11592 If there is an active region, export only the region.
11593 The prefix ARG specifies how many levels of the outline should become
11594 headlines. The default is 3. Lower levels will become bulleted lists."
11595 (interactive "P")
11596 (org-export-as-html arg 'hidden)
11597 (org-open-file buffer-file-name))
11599 (defun org-export-as-html-batch ()
11600 "Call `org-export-as-html', may be used in batch processing as
11601 emacs --batch
11602 --load=$HOME/lib/emacs/org.el
11603 --eval \"(setq org-export-headline-levels 2)\"
11604 --visit=MyFile --funcall org-export-as-html-batch"
11605 (org-export-as-html org-export-headline-levels 'hidden))
11607 (defun org-export-as-html (arg &optional hidden)
11608 "Export the outline as a pretty HTML file.
11609 If there is an active region, export only the region.
11610 The prefix ARG specifies how many levels of the outline should become
11611 headlines. The default is 3. Lower levels will become bulleted lists."
11612 (interactive "P")
11613 (setq-default org-todo-line-regexp org-todo-line-regexp)
11614 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11615 (setq-default org-done-string org-done-string)
11616 (let* ((style org-export-html-style)
11617 (odd org-odd-levels-only)
11618 (region-p (org-region-active-p))
11619 (region
11620 (buffer-substring
11621 (if region-p (region-beginning) (point-min))
11622 (if region-p (region-end) (point-max))))
11623 (all_lines
11624 (org-skip-comments (org-split-string
11625 (org-cleaned-string-for-export region)
11626 "[\r\n]")))
11627 (lines (org-export-find-first-heading-line all_lines))
11628 (level 0) (line "") (origline "") txt todo
11629 (umax nil)
11630 (filename (concat (file-name-sans-extension buffer-file-name)
11631 ".html"))
11632 (buffer (find-file-noselect filename))
11633 (levels-open (make-vector org-level-max nil))
11634 (date (format-time-string "%Y/%m/%d" (current-time)))
11635 (time (format-time-string "%X" (org-current-time)))
11636 (author user-full-name)
11637 (title (buffer-name))
11638 (options nil)
11639 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11640 (inquote nil)
11641 (infixed nil)
11642 (in-local-list nil)
11643 (local-list-num nil)
11644 (local-list-indent nil)
11645 (llt org-plain-list-ordered-item-terminator)
11646 (email user-mail-address)
11647 (language org-export-default-language)
11648 (text nil)
11649 (lang-words nil)
11650 (target-alist nil) tg
11651 (head-count 0) cnt
11652 (start 0)
11653 ;; FIXME: The following returns always nil under XEmacs
11654 (coding-system (and (fboundp 'coding-system-get)
11655 (boundp 'buffer-file-coding-system)
11656 buffer-file-coding-system))
11657 (coding-system-for-write (or coding-system coding-system-for-write))
11658 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11659 (charset (and coding-system
11660 (coding-system-get coding-system 'mime-charset)))
11661 table-open type
11662 table-buffer table-orig-buffer
11663 ind start-is-num starter
11664 rpl path desc desc1 desc2 link
11666 (message "Exporting...")
11668 (setq org-last-level 1)
11669 (org-init-section-numbers)
11671 ;; Search for the export key lines
11672 (org-parse-key-lines)
11673 (setq lang-words (or (assoc language org-export-language-setup)
11674 (assoc "en" org-export-language-setup)))
11676 ;; Switch to the output buffer
11677 (if (or hidden (not org-export-html-show-new-buffer))
11678 (set-buffer buffer)
11679 (switch-to-buffer-other-window buffer))
11680 (erase-buffer)
11681 (fundamental-mode)
11682 (let ((case-fold-search nil)
11683 (org-odd-levels-only odd))
11684 (if options (org-parse-export-options options))
11685 (setq umax (if arg (prefix-numeric-value arg)
11686 org-export-headline-levels))
11688 ;; File header
11689 (insert (format
11690 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11691 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11692 <html lang=\"%s\"><head>
11693 <title>%s</title>
11694 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11695 <meta name=generator content=\"Org-mode\">
11696 <meta name=generated content=\"%s %s\">
11697 <meta name=author content=\"%s\">
11699 </head><body>
11701 language (org-html-expand title) (or charset "iso-8859-1")
11702 date time author style))
11703 (if title (insert (concat "<H1 class=\"title\">"
11704 (org-html-expand title) "</H1>\n")))
11705 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11706 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11707 email "&gt;</a>\n")))
11708 (if (or author email) (insert "<br>\n"))
11709 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11710 date " " time "<br>\n")))
11711 (if text (insert (concat "<p>\n" (org-html-expand text))))
11712 (if org-export-with-toc
11713 (progn
11714 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11715 (insert "<ul>\n")
11716 (setq lines
11717 (mapcar '(lambda (line)
11718 (if (string-match org-todo-line-regexp line)
11719 ;; This is a headline
11720 (progn
11721 (setq level (- (match-end 1) (match-beginning 1))
11722 level (org-tr-level level)
11723 txt (save-match-data
11724 (org-html-expand
11725 (match-string 3 line)))
11726 todo
11727 (or (and (match-beginning 2)
11728 (not (equal (match-string 2 line)
11729 org-done-string)))
11730 ; TODO, not DONE
11731 (and org-export-mark-todo-in-toc
11732 (= level umax)
11733 (org-search-todo-below
11734 line lines level))))
11735 (if org-export-with-section-numbers
11736 (setq txt (concat (org-section-number level)
11737 " " txt)))
11738 (if (<= level umax)
11739 (progn
11740 (setq head-count (+ head-count 1))
11741 (if (> level org-last-level)
11742 (progn
11743 (setq cnt (- level org-last-level))
11744 (while (>= (setq cnt (1- cnt)) 0)
11745 (insert "<ul>"))
11746 (insert "\n")))
11747 (if (< level org-last-level)
11748 (progn
11749 (setq cnt (- org-last-level level))
11750 (while (>= (setq cnt (1- cnt)) 0)
11751 (insert "</ul>"))
11752 (insert "\n")))
11753 ;; Check for targets
11754 (while (string-match org-target-regexp line)
11755 (setq tg (match-string 1 line)
11756 line (replace-match
11757 (concat "@<span class=\"target\">" tg "@</span> ")
11758 t t line))
11759 (push (cons (org-solidify-link-text tg)
11760 (format "sec-%d" head-count))
11761 target-alist))
11762 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11763 (setq txt (replace-match "" t t txt)))
11764 (insert
11765 (format
11766 (if todo
11767 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11768 "<li><a href=\"#sec-%d\">%s</a>\n")
11769 head-count txt))
11771 (setq org-last-level level))
11773 line)
11774 lines))
11775 (while (> org-last-level 0)
11776 (setq org-last-level (1- org-last-level))
11777 (insert "</ul>\n"))
11779 (setq head-count 0)
11780 (org-init-section-numbers)
11782 (while (setq line (pop lines) origline line)
11783 (catch 'nextline
11785 ;; end of quote section?
11786 (when (and inquote (string-match "^\\*+" line))
11787 (insert "</pre>\n")
11788 (setq inquote nil))
11789 ;; inside a quote section?
11790 (when inquote
11791 (insert (org-html-protect line) "\n")
11792 (throw 'nextline nil))
11794 ;; verbatim lines
11795 (when (and org-export-with-fixed-width
11796 (string-match "^[ \t]*:\\(.*\\)" line))
11797 (when (not infixed)
11798 (setq infixed t)
11799 (insert "<pre>\n"))
11800 (insert (org-html-protect (match-string 1 line)) "\n")
11801 (when (and lines
11802 (not (string-match "^[ \t]*\\(:.*\\)"
11803 (car lines))))
11804 (setq infixed nil)
11805 (insert "</pre>\n"))
11806 (throw 'nextline nil))
11809 ;; make targets to anchors
11810 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11811 (cond
11812 ((match-end 2)
11813 (setq line (replace-match
11814 (concat "@<a name=\""
11815 (org-solidify-link-text (match-string 1 line))
11816 "\">\\nbsp@</a>")
11817 t t line)))
11818 ((and org-export-with-toc (equal (string-to-char line) ?*))
11819 (setq line (replace-match
11820 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11821 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11822 t t line)))
11824 (setq line (replace-match
11825 (concat "@<a name=\""
11826 (org-solidify-link-text (match-string 1 line))
11827 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11828 t t line)))))
11830 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11831 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11832 (setq line (org-html-expand line))
11834 ;; Format the links
11835 (setq start 0)
11836 (while (string-match org-bracket-link-analytic-regexp line start)
11837 (setq start (match-beginning 0))
11838 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11839 (setq path (match-string 3 line))
11840 (setq desc1 (if (match-end 5) (match-string 5 line))
11841 desc2 (if (match-end 2) (concat type ":" path) path)
11842 desc (or desc1 desc2))
11843 (cond
11844 ((equal type "internal")
11845 (setq rpl
11846 (concat
11847 "<a href=\"#"
11848 (org-solidify-link-text path target-alist)
11849 "\">" desc "</a>")))
11850 ((member type '("http" "https" "ftp" "mailto" "news"))
11851 ;; standard URL
11852 (setq link (concat type ":" path))
11853 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11854 ((string= type "file")
11855 ;; FILE link
11856 (let* ((filename path)
11857 (abs-p (file-name-absolute-p filename))
11858 thefile file-is-image-p search)
11859 (save-match-data
11860 (if (string-match "::\\(.*\\)" filename)
11861 (setq search (match-string 1 filename)
11862 filename (replace-match "" nil nil filename)))
11863 (setq file-is-image-p
11864 (string-match (org-image-file-name-regexp) filename))
11865 (setq thefile (if abs-p (expand-file-name filename) filename))
11866 (when (and org-export-html-link-org-files-as-html
11867 (string-match "\\.org$" thefile))
11868 (setq thefile (concat (substring thefile 0
11869 (match-beginning 0))
11870 ".html"))
11871 (if (and search
11872 ;; make sure this is can be used as target search
11873 (not (string-match "^[0-9]*$" search))
11874 (not (string-match "^\\*" search))
11875 (not (string-match "^/.*/$" search)))
11876 (setq thefile (concat thefile "#"
11877 (org-solidify-link-text
11878 (org-link-unescape search)))))))
11879 (setq rpl (if (and org-export-html-inline-images
11880 file-is-image-p)
11881 (concat "<img src=\"" thefile "\"/>")
11882 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11883 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11884 (setq rpl (concat "<i>&lt;" type ":"
11885 (save-match-data (org-link-unescape path))
11886 "&gt;</i>"))))
11887 (setq line (replace-match rpl t t line)
11888 start (+ start (length rpl))))
11889 ;; TODO items
11890 (if (and (string-match org-todo-line-regexp line)
11891 (match-beginning 2))
11892 (if (equal (match-string 2 line) org-done-string)
11893 (setq line (replace-match
11894 "<span class=\"done\">\\2</span>"
11895 nil nil line 2))
11896 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11897 nil nil line 2))))
11899 ;; DEADLINES
11900 (if (string-match org-deadline-line-regexp line)
11901 (progn
11902 (if (save-match-data
11903 (string-match "<a href"
11904 (substring line 0 (match-beginning 0))))
11905 nil ; Don't do the replacement - it is inside a link
11906 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11907 nil nil line 1)))))
11908 (cond
11909 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11910 ;; This is a headline
11911 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11912 txt (match-string 2 line))
11913 (if (<= level umax) (setq head-count (+ head-count 1)))
11914 (when in-local-list
11915 ;; Close any local lists before inserting a new header line
11916 (while local-list-num
11917 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11918 (pop local-list-num))
11919 (setq local-list-indent nil
11920 in-local-list nil))
11921 (org-html-level-start level txt umax
11922 (and org-export-with-toc (<= level umax))
11923 head-count)
11924 ;; QUOTES
11925 (when (string-match quote-re line)
11926 (insert "<pre>")
11927 (setq inquote t)))
11929 ((and org-export-with-tables
11930 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11931 (if (not table-open)
11932 ;; New table starts
11933 (setq table-open t table-buffer nil table-orig-buffer nil))
11934 ;; Accumulate lines
11935 (setq table-buffer (cons line table-buffer)
11936 table-orig-buffer (cons origline table-orig-buffer))
11937 (when (or (not lines)
11938 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11939 (car lines))))
11940 (setq table-open nil
11941 table-buffer (nreverse table-buffer)
11942 table-orig-buffer (nreverse table-orig-buffer))
11943 (insert (org-format-table-html table-buffer table-orig-buffer))))
11945 ;; Normal lines
11946 (when (and (string-match
11947 (cond
11948 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11949 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11950 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11951 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11952 line))
11953 (setq ind (org-get-string-indentation line)
11954 start-is-num (match-beginning 4)
11955 starter (if (match-beginning 2) (match-string 2 line))
11956 line (substring line (match-beginning 5)))
11957 (unless (string-match "[^ \t]" line)
11958 ;; empty line. Pretend indentation is large.
11959 (setq ind (1+ (or (car local-list-indent) 1))))
11960 (while (and in-local-list
11961 (or (and (= ind (car local-list-indent))
11962 (not starter))
11963 (< ind (car local-list-indent))))
11964 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11965 (pop local-list-num) (pop local-list-indent)
11966 (setq in-local-list local-list-indent))
11967 (cond
11968 ((and starter
11969 (or (not in-local-list)
11970 (> ind (car local-list-indent))))
11971 ;; Start new (level of ) list
11972 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11973 (push start-is-num local-list-num)
11974 (push ind local-list-indent)
11975 (setq in-local-list t))
11976 (starter
11977 ;; continue current list
11978 (insert "<li>\n"))))
11979 ;; Empty lines start a new paragraph. If hand-formatted lists
11980 ;; are not fully interpreted, lines starting with "-", "+", "*"
11981 ;; also start a new paragraph.
11982 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11983 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11985 (if org-export-html-with-timestamp
11986 (insert org-export-html-html-helper-timestamp))
11987 (insert "</body>\n</html>\n")
11988 (normal-mode)
11989 (save-buffer)
11990 (goto-char (point-min)))))
11992 (defun org-format-table-html (lines olines)
11993 "Find out which HTML converter to use and return the HTML code."
11994 (if (string-match "^[ \t]*|" (car lines))
11995 ;; A normal org table
11996 (org-format-org-table-html lines)
11997 ;; Table made by table.el - test for spanning
11998 (let* ((hlines (delq nil (mapcar
11999 (lambda (x)
12000 (if (string-match "^[ \t]*\\+-" x) x
12001 nil))
12002 lines)))
12003 (first (car hlines))
12004 (ll (and (string-match "\\S-+" first)
12005 (match-string 0 first)))
12006 (re (concat "^[ \t]*" (regexp-quote ll)))
12007 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12008 hlines))))
12009 (if (and (not spanning)
12010 (not org-export-prefer-native-exporter-for-tables))
12011 ;; We can use my own converter with HTML conversions
12012 (org-format-table-table-html lines)
12013 ;; Need to use the code generator in table.el, with the original text.
12014 (org-format-table-table-html-using-table-generate-source olines)))))
12016 (defun org-format-org-table-html (lines)
12017 "Format a table into HTML."
12018 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12019 (setq lines (nreverse lines))
12020 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12021 (setq lines (nreverse lines))
12022 (when org-export-table-remove-special-lines
12023 ;; Check if the table has a marking column. If yes remove the
12024 ;; column and the special lines
12025 (let* ((special
12026 (not
12027 (memq nil
12028 (mapcar
12029 (lambda (x)
12030 (or (string-match "^[ \t]*|-" x)
12031 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12032 lines)))))
12033 (if special
12034 (setq lines
12035 (delq nil
12036 (mapcar
12037 (lambda (x)
12038 (if (string-match "^[ \t]*| *[!_^] *|" x)
12039 nil ; ignore this line
12040 (and (or (string-match "^[ \t]*|-+\\+" x)
12041 (string-match "^[ \t]*|[^|]*|" x))
12042 (replace-match "|" t t x))))
12043 lines))))))
12045 (let ((head (and org-export-highlight-first-table-line
12046 (delq nil (mapcar
12047 (lambda (x) (string-match "^[ \t]*|-" x))
12048 (cdr lines)))))
12049 line fields html)
12050 (setq html (concat org-export-html-table-tag "\n"))
12051 (while (setq line (pop lines))
12052 (catch 'next-line
12053 (if (string-match "^[ \t]*|-" line)
12054 (progn
12055 (setq head nil) ;; head ends here, first time around
12056 ;; ignore this line
12057 (throw 'next-line t)))
12058 ;; Break the line into fields
12059 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12060 (setq html (concat
12061 html
12062 "<tr>"
12063 (mapconcat (lambda (x)
12064 (if head
12065 (concat "<th>" x "</th>")
12066 (concat "<td>" x "</td>")))
12067 fields "")
12068 "</tr>\n"))))
12069 (setq html (concat html "</table>\n"))
12070 html))
12072 (defun org-fake-empty-table-line (line)
12073 "Replace everything except \"|\" with spaces."
12074 (let ((i (length line))
12075 (newstr (copy-sequence line)))
12076 (while (> i 0)
12077 (setq i (1- i))
12078 (if (not (eq (aref newstr i) ?|))
12079 (aset newstr i ?\ )))
12080 newstr))
12082 (defun org-format-table-table-html (lines)
12083 "Format a table generated by table.el into HTML.
12084 This conversion does *not* use `table-generate-source' from table.el.
12085 This has the advantage that Org-mode's HTML conversions can be used.
12086 But it has the disadvantage, that no cell- or row-spanning is allowed."
12087 (let (line field-buffer
12088 (head org-export-highlight-first-table-line)
12089 fields html empty)
12090 (setq html (concat org-export-html-table-tag "\n"))
12091 (while (setq line (pop lines))
12092 (setq empty "&nbsp")
12093 (catch 'next-line
12094 (if (string-match "^[ \t]*\\+-" line)
12095 (progn
12096 (if field-buffer
12097 (progn
12098 (setq html (concat
12099 html
12100 "<tr>"
12101 (mapconcat
12102 (lambda (x)
12103 (if (equal x "") (setq x empty))
12104 (if head
12105 (concat "<th>" x "</th>\n")
12106 (concat "<td>" x "</td>\n")))
12107 field-buffer "\n")
12108 "</tr>\n"))
12109 (setq head nil)
12110 (setq field-buffer nil)))
12111 ;; Ignore this line
12112 (throw 'next-line t)))
12113 ;; Break the line into fields and store the fields
12114 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12115 (if field-buffer
12116 (setq field-buffer (mapcar
12117 (lambda (x)
12118 (concat x "<br>" (pop fields)))
12119 field-buffer))
12120 (setq field-buffer fields))))
12121 (setq html (concat html "</table>\n"))
12122 html))
12124 (defun org-format-table-table-html-using-table-generate-source (lines)
12125 "Format a table into html, using `table-generate-source' from table.el.
12126 This has the advantage that cell- or row-spanning is allowed.
12127 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12128 (require 'table)
12129 (with-current-buffer (get-buffer-create " org-tmp1 ")
12130 (erase-buffer)
12131 (insert (mapconcat 'identity lines "\n"))
12132 (goto-char (point-min))
12133 (if (not (re-search-forward "|[^+]" nil t))
12134 (error "Error processing table"))
12135 (table-recognize-table)
12136 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12137 (table-generate-source 'html " org-tmp2 ")
12138 (set-buffer " org-tmp2 ")
12139 (buffer-substring (point-min) (point-max))))
12141 (defun org-html-protect (s)
12142 ;; convert & to &amp;, < to &lt; and > to &gt;
12143 (let ((start 0))
12144 (while (string-match "&" s start)
12145 (setq s (replace-match "&amp;" t t s)
12146 start (1+ (match-beginning 0))))
12147 (while (string-match "<" s)
12148 (setq s (replace-match "&lt;" t t s)))
12149 (while (string-match ">" s)
12150 (setq s (replace-match "&gt;" t t s))))
12153 (defun org-html-expand (string)
12154 "Prepare STRING for HTML export. Applies all active conversions.
12155 If there are links in the string, don't modify these."
12156 (let* (m s l res)
12157 (while (setq m (string-match org-bracket-link-regexp string))
12158 (setq s (substring string 0 m)
12159 l (match-string 0 string)
12160 string (substring string (match-end 0)))
12161 (push (org-html-do-expand s) res)
12162 (push l res))
12163 (push (org-html-do-expand string) res)
12164 (apply 'concat (nreverse res))))
12166 (defun org-html-do-expand (s)
12167 "Apply all active conversions to translate special ASCII to HTML."
12168 (setq s (org-html-protect s))
12169 (if org-export-html-expand
12170 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12171 (setq s (replace-match "<\\1>" nil nil s))))
12172 (if org-export-with-emphasize
12173 (setq s (org-export-html-convert-emphasize s)))
12174 (if org-export-with-sub-superscripts
12175 (setq s (org-export-html-convert-sub-super s)))
12176 (if org-export-with-TeX-macros
12177 (let ((start 0) wd ass)
12178 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12179 (setq wd (match-string 1 s))
12180 (if (setq ass (assoc wd org-html-entities))
12181 (setq s (replace-match (or (cdr ass)
12182 (concat "&" (car ass) ";"))
12183 t t s))
12184 (setq start (+ start (length wd)))))))
12187 (defun org-create-multibrace-regexp (left right n)
12188 "Create a regular expression which will match a balanced sexp.
12189 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12190 as single character strings.
12191 The regexp returned will match the entire expression including the
12192 delimiters. It will also define a single group which contains the
12193 match except for the outermost delimiters. The maximum depth of
12194 stacked delimiters is N. Escaping delimiters is not possible."
12195 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12196 (or "\\|")
12197 (re nothing)
12198 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12199 (while (> n 1)
12200 (setq n (1- n)
12201 re (concat re or next)
12202 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12203 (concat left "\\(" re "\\)" right)))
12205 (defvar org-match-substring-regexp
12206 (concat
12207 "\\([^\\]\\)\\([_^]\\)\\("
12208 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12209 "\\|"
12210 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12211 "\\|"
12212 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12213 "The regular expression matching a sub- or superscript.")
12215 (defun org-export-html-convert-sub-super (string)
12216 "Convert sub- and superscripts in STRING to HTML."
12217 (let (key c)
12218 (while (string-match org-match-substring-regexp string)
12219 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12220 (setq c (or (match-string 8 string)
12221 (match-string 6 string)
12222 (match-string 5 string)))
12223 (setq string (replace-match
12224 (concat (match-string 1 string)
12225 "<" key ">" c "</" key ">")
12226 t t string)))
12227 (while (string-match "\\\\\\([_^]\\)" string)
12228 (setq string (replace-match (match-string 1 string) t t string))))
12229 string)
12231 (defun org-export-html-convert-emphasize (string)
12232 (while (string-match org-italic-re string)
12233 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
12234 (while (string-match org-bold-re string)
12235 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
12236 (while (string-match org-underline-re string)
12237 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
12238 string)
12240 (defun org-parse-key-lines ()
12241 "Find the special key lines with the information for exporters."
12242 (save-excursion
12243 (goto-char 0)
12244 (let ((re (org-make-options-regexp
12245 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12246 key)
12247 (while (re-search-forward re nil t)
12248 (setq key (match-string 1))
12249 (cond ((string-equal key "TITLE")
12250 (setq title (match-string 2)))
12251 ((string-equal key "AUTHOR")
12252 (setq author (match-string 2)))
12253 ((string-equal key "EMAIL")
12254 (setq email (match-string 2)))
12255 ((string-equal key "LANGUAGE")
12256 (setq language (match-string 2)))
12257 ((string-equal key "TEXT")
12258 (setq text (concat text "\n" (match-string 2))))
12259 ((string-equal key "OPTIONS")
12260 (setq options (match-string 2))))))))
12262 (defun org-parse-export-options (s)
12263 "Parse the export options line."
12264 (let ((op '(("H" . org-export-headline-levels)
12265 ("num" . org-export-with-section-numbers)
12266 ("toc" . org-export-with-toc)
12267 ("\\n" . org-export-preserve-breaks)
12268 ("@" . org-export-html-expand)
12269 (":" . org-export-with-fixed-width)
12270 ("|" . org-export-with-tables)
12271 ("^" . org-export-with-sub-superscripts)
12272 ("*" . org-export-with-emphasize)
12273 ("TeX" . org-export-with-TeX-macros)))
12275 (while (setq o (pop op))
12276 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12278 (set (make-local-variable (cdr o))
12279 (car (read-from-string (match-string 1 s))))))))
12281 (defun org-html-level-start (level title umax with-toc head-count)
12282 "Insert a new level in HTML export."
12283 (let ((l (1+ (max level umax))))
12284 (while (<= l org-level-max)
12285 (if (aref levels-open (1- l))
12286 (progn
12287 (org-html-level-close l)
12288 (aset levels-open (1- l) nil)))
12289 (setq l (1+ l)))
12290 (if (> level umax)
12291 (progn
12292 (if (aref levels-open (1- level))
12293 (insert "<li>" title "<p>\n")
12294 (aset levels-open (1- level) t)
12295 (insert "<ul><li>" title "<p>\n")))
12296 (if org-export-with-section-numbers
12297 (setq title (concat (org-section-number level) " " title)))
12298 (setq level (+ level 1))
12299 (if with-toc
12300 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12301 level head-count title level))
12302 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12304 (defun org-html-level-close (&rest args)
12305 "Terminate one level in HTML export."
12306 (insert "</ul>"))
12308 ;; Variable holding the vector with section numbers
12309 (defvar org-section-numbers (make-vector org-level-max 0))
12311 (defun org-init-section-numbers ()
12312 "Initialize the vector for the section numbers."
12313 (let* ((level -1)
12314 (numbers (nreverse (org-split-string "" "\\.")))
12315 (depth (1- (length org-section-numbers)))
12316 (i depth) number-string)
12317 (while (>= i 0)
12318 (if (> i level)
12319 (aset org-section-numbers i 0)
12320 (setq number-string (or (car numbers) "0"))
12321 (if (string-match "\\`[A-Z]\\'" number-string)
12322 (aset org-section-numbers i
12323 (- (string-to-char number-string) ?A -1))
12324 (aset org-section-numbers i (string-to-number number-string)))
12325 (pop numbers))
12326 (setq i (1- i)))))
12328 (defun org-section-number (&optional level)
12329 "Return a string with the current section number.
12330 When LEVEL is non-nil, increase section numbers on that level."
12331 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12332 (when level
12333 (when (> level -1)
12334 (aset org-section-numbers
12335 level (1+ (aref org-section-numbers level))))
12336 (setq idx (1+ level))
12337 (while (<= idx depth)
12338 (if (not (= idx 1))
12339 (aset org-section-numbers idx 0))
12340 (setq idx (1+ idx))))
12341 (setq idx 0)
12342 (while (<= idx depth)
12343 (setq n (aref org-section-numbers idx))
12344 (setq string (concat string (if (not (string= string "")) "." "")
12345 (int-to-string n)))
12346 (setq idx (1+ idx)))
12347 (save-match-data
12348 (if (string-match "\\`\\([@0]\\.\\)+" string)
12349 (setq string (replace-match "" nil nil string)))
12350 (if (string-match "\\(\\.0\\)+\\'" string)
12351 (setq string (replace-match "" nil nil string))))
12352 string))
12355 (defun org-export-icalendar-this-file ()
12356 "Export current file as an iCalendar file.
12357 The iCalendar file will be located in the same directory as the Org-mode
12358 file, but with extension `.ics'."
12359 (interactive)
12360 (org-export-icalendar nil buffer-file-name))
12362 (defun org-export-as-xml ()
12363 "Export current buffer as XOXO XML buffer."
12364 (interactive)
12365 (cond ((eq org-export-xml-type 'xoxo)
12366 (org-export-as-xoxo (current-buffer)))))
12368 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12369 (with-current-buffer buffer
12370 (apply 'insert output)))
12372 (defun org-export-as-xoxo (&optional buffer)
12373 "Export the org buffer as XOXO.
12374 The XOXO buffer is named *xoxo-<source buffer name>*"
12375 (interactive (list (current-buffer)))
12376 ;; A quickie abstraction
12378 ;; Output everything as XOXO
12379 (with-current-buffer (get-buffer buffer)
12380 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12381 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
12382 ".xml"))
12383 (out (find-file-noselect filename))
12384 (last-level 1)
12385 (hanging-li nil))
12386 ;; Check the output buffer is empty.
12387 (with-current-buffer out (erase-buffer))
12388 ;; Kick off the output
12389 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12390 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12391 (let* ((hd (match-string-no-properties 1))
12392 (level (length hd))
12393 (text (concat
12394 (match-string-no-properties 2)
12395 (save-excursion
12396 (goto-char (match-end 0))
12397 (let ((str ""))
12398 (catch 'loop
12399 (while 't
12400 (forward-line)
12401 (if (looking-at "^[ \t]\\(.*\\)")
12402 (setq str (concat str (match-string-no-properties 1)))
12403 (throw 'loop str)))))))))
12405 ;; Handle level rendering
12406 (cond
12407 ((> level last-level)
12408 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12410 ((< level last-level)
12411 (dotimes (- (- last-level level) 1)
12412 (if hanging-li
12413 (org-export-as-xoxo-insert-into out "</li>\n"))
12414 (org-export-as-xoxo-insert-into out "</ol>\n"))
12415 (when hanging-li
12416 (org-export-as-xoxo-insert-into out "</li>\n")
12417 (setq hanging-li nil)))
12419 ((equal level last-level)
12420 (if hanging-li
12421 (org-export-as-xoxo-insert-into out "</li>\n")))
12424 (setq last-level level)
12426 ;; And output the new li
12427 (setq hanging-li 't)
12428 (if (equal ?+ (elt text 0))
12429 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12430 (org-export-as-xoxo-insert-into out "<li>" text))))
12432 ;; Finally finish off the ol
12433 (dotimes (- last-level 1)
12434 (if hanging-li
12435 (org-export-as-xoxo-insert-into out "</li>\n"))
12436 (org-export-as-xoxo-insert-into out "</ol>\n"))
12438 ;; Finish the buffer off and clean it up.
12439 (switch-to-buffer-other-window out)
12440 (indent-region (point-min) (point-max))
12441 (save-buffer)
12442 (goto-char (point-min))
12445 ;;;###autoload
12446 (defun org-export-icalendar-all-agenda-files ()
12447 "Export all files in `org-agenda-files' to iCalendar .ics files.
12448 Each iCalendar file will be located in the same directory as the Org-mode
12449 file, but with extension `.ics'."
12450 (interactive)
12451 (apply 'org-export-icalendar nil (org-agenda-files t)))
12453 ;;;###autoload
12454 (defun org-export-icalendar-combine-agenda-files ()
12455 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12456 The file is stored under the name `org-combined-agenda-icalendar-file'."
12457 (interactive)
12458 (apply 'org-export-icalendar t (org-agenda-files t)))
12460 (defun org-export-icalendar (combine &rest files)
12461 "Create iCalendar files for all elements of FILES.
12462 If COMBINE is non-nil, combine all calendar entries into a single large
12463 file and store it under the name `org-combined-agenda-icalendar-file'."
12464 (save-excursion
12465 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12466 (when combine
12467 (setq ical-file org-combined-agenda-icalendar-file
12468 ical-buffer (org-get-agenda-file-buffer ical-file))
12469 (set-buffer ical-buffer) (erase-buffer))
12470 (while (setq file (pop files))
12471 (catch 'nextfile
12472 (org-check-agenda-file file)
12473 (unless combine
12474 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12475 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12476 (set-buffer ical-buffer) (erase-buffer))
12477 (set-buffer (org-get-agenda-file-buffer file))
12478 (setq category (or org-category
12479 (file-name-sans-extension
12480 (file-name-nondirectory buffer-file-name))))
12481 (if (symbolp category) (setq category (symbol-name category)))
12482 (let ((standard-output ical-buffer))
12483 (if combine
12484 (and (not started) (setq started t)
12485 (org-start-icalendar-file org-icalendar-combined-name))
12486 (org-start-icalendar-file category))
12487 (org-print-icalendar-entries combine category)
12488 (when (or (and combine (not files)) (not combine))
12489 (org-finish-icalendar-file)
12490 (set-buffer ical-buffer)
12491 (save-buffer)
12492 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12493 (org-release-buffers org-agenda-new-buffers))))
12495 (defvar org-after-save-iCalendar-file-hook nil
12496 "Hook run after an iCalendar file has been saved.
12497 The iCalendar buffer is still current when this hook is run.
12498 A good way to use this is to tell a desktop calenndar application to re-read
12499 the iCalendar file.")
12501 (defun org-print-icalendar-entries (&optional combine category)
12502 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12503 When COMBINE is non nil, add the category to each line."
12504 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12505 (dts (org-ical-ts-to-string
12506 (format-time-string (cdr org-time-stamp-formats) (current-time))
12507 "DTSTART"))
12508 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12509 (save-excursion
12510 (goto-char (point-min))
12511 (while (re-search-forward org-ts-regexp nil t)
12512 (setq pos (match-beginning 0)
12513 ts (match-string 0)
12514 inc t
12515 hd (org-get-heading))
12516 (if (looking-at re2)
12517 (progn
12518 (goto-char (match-end 0))
12519 (setq ts2 (match-string 1) inc nil))
12520 (setq ts2 ts
12521 tmp (buffer-substring (max (point-min)
12522 (- pos org-ds-keyword-length))
12523 pos)
12524 deadlinep (string-match org-deadline-regexp tmp)
12525 scheduledp (string-match org-scheduled-regexp tmp)
12526 ;; donep (org-entry-is-done-p)
12528 (if (or (string-match org-tr-regexp hd)
12529 (string-match org-ts-regexp hd))
12530 (setq hd (replace-match "" t t hd)))
12531 (if combine
12532 (setq hd (concat hd " (category " category ")")))
12533 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12534 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12535 (princ (format "BEGIN:VEVENT
12538 SUMMARY:%s
12539 END:VEVENT\n"
12540 (org-ical-ts-to-string ts "DTSTART")
12541 (org-ical-ts-to-string ts2 "DTEND" inc)
12542 hd)))
12543 (when org-icalendar-include-todo
12544 (goto-char (point-min))
12545 (while (re-search-forward org-todo-line-regexp nil t)
12546 (setq state (match-string 1))
12547 (unless (equal state org-done-string)
12548 (setq hd (match-string 3))
12549 (if (string-match org-priority-regexp hd)
12550 (setq pri (string-to-char (match-string 2 hd))
12551 hd (concat (substring hd 0 (match-beginning 1))
12552 (substring hd (- (match-end 1)))))
12553 (setq pri org-default-priority))
12554 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12555 (- org-lowest-priority ?A))))))
12557 (princ (format "BEGIN:VTODO
12559 SUMMARY:%s
12560 SEQUENCE:1
12561 PRIORITY:%d
12562 END:VTODO\n"
12563 dts hd pri))))))))
12565 (defun org-start-icalendar-file (name)
12566 "Start an iCalendar file by inserting the header."
12567 (let ((user user-full-name)
12568 (name (or name "unknown"))
12569 (timezone (cadr (current-time-zone))))
12570 (princ
12571 (format "BEGIN:VCALENDAR
12572 VERSION:2.0
12573 X-WR-CALNAME:%s
12574 PRODID:-//%s//Emacs with Org-mode//EN
12575 X-WR-TIMEZONE:%s
12576 CALSCALE:GREGORIAN\n" name user timezone))))
12578 (defun org-finish-icalendar-file ()
12579 "Finish an iCalendar file by inserting the END statement."
12580 (princ "END:VCALENDAR\n"))
12582 (defun org-ical-ts-to-string (s keyword &optional inc)
12583 "Take a time string S and convert it to iCalendar format.
12584 KEYWORD is added in front, to make a complete line like DTSTART....
12585 When INC is non-nil, increase the hour by two (if time string contains
12586 a time), or the day by one (if it does not contain a time)."
12587 (let ((t1 (org-parse-time-string s 'nodefault))
12588 t2 fmt have-time time)
12589 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12590 (setq t2 t1 have-time t)
12591 (setq t2 (org-parse-time-string s)))
12592 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12593 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12594 (when inc
12595 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12596 (setq time (encode-time s mi h d m y)))
12597 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12598 (concat keyword (format-time-string fmt time))))
12601 ;;; Key bindings
12603 ;; - Bindings in Org-mode map are currently
12604 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12605 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12606 ;; e (?) useful from outline-mode
12607 ;; i k @ expendable from outline-mode
12608 ;; 0123456789 % & ()_{} " ` free
12610 ;; Make `C-c C-x' a prefix key
12611 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12613 ;; TAB key with modifiers
12614 (define-key org-mode-map "\C-i" 'org-cycle)
12615 (define-key org-mode-map [(tab)] 'org-cycle)
12616 (define-key org-mode-map [(meta tab)] 'org-complete)
12617 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12618 ;; The following line is necessary under Suse GNU/Linux
12619 (unless (featurep 'xemacs)
12620 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12621 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12623 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12624 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12625 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12626 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12627 (define-key org-mode-map [(meta return)] 'org-meta-return)
12628 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12629 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12631 ;; Cursor keys with modifiers
12632 (define-key org-mode-map [(meta left)] 'org-metaleft)
12633 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12634 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12635 (define-key org-mode-map [(meta right)] 'org-metaright)
12636 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12637 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12638 (define-key org-mode-map [(meta up)] 'org-metaup)
12639 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12640 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12641 (define-key org-mode-map [(meta down)] 'org-metadown)
12642 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12643 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12645 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12646 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12647 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12648 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12649 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12650 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12651 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12652 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12653 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12654 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12655 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12656 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12657 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12658 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12659 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12660 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12662 ;; All the other keys
12664 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12665 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12666 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12667 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12668 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12669 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12670 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12671 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12672 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12673 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12674 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12675 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12676 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12677 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12678 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12679 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12680 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12681 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12682 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12683 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12684 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12685 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12686 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12687 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12688 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12689 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12690 (define-key org-mode-map "\C-c]" 'org-remove-file)
12691 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12692 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12693 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12694 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12695 (define-key org-mode-map "\C-m" 'org-return)
12696 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12697 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12698 (define-key org-mode-map "\C-c+" 'org-table-sum)
12699 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12700 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12701 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12702 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12703 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12704 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12705 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12706 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12707 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12708 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12709 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12710 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12711 ;; OPML support is only an option for the future
12712 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12713 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12714 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12715 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12716 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12717 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12718 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12719 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12720 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12721 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12722 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12723 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12724 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12726 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12727 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12728 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12729 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12731 (defsubst org-table-p () (org-at-table-p))
12733 (defun org-self-insert-command (N)
12734 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12735 If the cursor is in a table looking at whitespace, the whitespace is
12736 overwritten, and the table is not marked as requiring realignment."
12737 (interactive "p")
12738 (if (and (org-table-p)
12739 (progn
12740 ;; check if we blank the field, and if that triggers align
12741 (and org-table-auto-blank-field
12742 (member last-command
12743 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12744 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12745 ;; got extra space, this field does not determine column width
12746 (let (org-table-may-need-update) (org-table-blank-field))
12747 ;; no extra space, this field may determine column width
12748 (org-table-blank-field)))
12750 (eq N 1)
12751 (looking-at "[^|\n]* |"))
12752 (let (org-table-may-need-update)
12753 (goto-char (1- (match-end 0)))
12754 (delete-backward-char 1)
12755 (goto-char (match-beginning 0))
12756 (self-insert-command N))
12757 (setq org-table-may-need-update t)
12758 (self-insert-command N)))
12760 (defun org-delete-backward-char (N)
12761 "Like `delete-backward-char', insert whitespace at field end in tables.
12762 When deleting backwards, in tables this function will insert whitespace in
12763 front of the next \"|\" separator, to keep the table aligned. The table will
12764 still be marked for re-alignment if the field did fill the entire column,
12765 because, in this case the deletion might narrow the column."
12766 (interactive "p")
12767 (if (and (org-table-p)
12768 (eq N 1)
12769 (string-match "|" (buffer-substring (point-at-bol) (point)))
12770 (looking-at ".*?|"))
12771 (let ((pos (point))
12772 (noalign (looking-at "[^|\n\r]* |"))
12773 (c org-table-may-need-update))
12774 (backward-delete-char N)
12775 (skip-chars-forward "^|")
12776 (insert " ")
12777 (goto-char (1- pos))
12778 ;; noalign: if there were two spaces at the end, this field
12779 ;; does not determine the width of the column.
12780 (if noalign (setq org-table-may-need-update c)))
12781 (backward-delete-char N)))
12783 (defun org-delete-char (N)
12784 "Like `delete-char', but insert whitespace at field end in tables.
12785 When deleting characters, in tables this function will insert whitespace in
12786 front of the next \"|\" separator, to keep the table aligned. The table will
12787 still be marked for re-alignment if the field did fill the entire column,
12788 because, in this case the deletion might narrow the column."
12789 (interactive "p")
12790 (if (and (org-table-p)
12791 (not (bolp))
12792 (not (= (char-after) ?|))
12793 (eq N 1))
12794 (if (looking-at ".*?|")
12795 (let ((pos (point))
12796 (noalign (looking-at "[^|\n\r]* |"))
12797 (c org-table-may-need-update))
12798 (replace-match (concat
12799 (substring (match-string 0) 1 -1)
12800 " |"))
12801 (goto-char pos)
12802 ;; noalign: if there were two spaces at the end, this field
12803 ;; does not determine the width of the column.
12804 (if noalign (setq org-table-may-need-update c))))
12805 (delete-char N)))
12807 ;; How to do this: Measure non-white length of current string
12808 ;; If equal to column width, we should realign.
12810 (defun org-remap (map &rest commands)
12811 "In MAP, remap the functions given in COMMANDS.
12812 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12813 (let (new old)
12814 (while commands
12815 (setq old (pop commands) new (pop commands))
12816 (if (fboundp 'command-remapping)
12817 (define-key map (vector 'remap old) new)
12818 (substitute-key-definition old new map global-map)))))
12820 (when (eq org-enable-table-editor 'optimized)
12821 ;; If the user wants maximum table support, we need to hijack
12822 ;; some standard editing functions
12823 (org-remap org-mode-map
12824 'self-insert-command 'org-self-insert-command
12825 'delete-char 'org-delete-char
12826 'delete-backward-char 'org-delete-backward-char)
12827 (define-key org-mode-map "|" 'org-force-self-insert))
12829 (defun org-shiftcursor-error ()
12830 "Throw an error because Shift-Cursor command was applied in wrong context."
12831 (error "This command is active in special context like tables, headlines or timestamps"))
12833 (defun org-shifttab ()
12834 "Global visibility cycling or move to previous table field.
12835 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12836 See the individual commands for more information."
12837 (interactive)
12838 (cond
12839 ((org-at-table-p) (org-table-previous-field))
12840 (t (org-cycle '(4)))))
12842 (defun org-shiftmetaleft ()
12843 "Promote subtree or delete table column.
12844 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12845 See the individual commands for more information."
12846 (interactive)
12847 (cond
12848 ((org-at-table-p) (org-table-delete-column))
12849 ((org-on-heading-p) (org-promote-subtree))
12850 ((org-at-item-p) (call-interactively 'org-outdent-item))
12851 (t (org-shiftcursor-error))))
12853 (defun org-shiftmetaright ()
12854 "Demote subtree or insert table column.
12855 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12856 See the individual commands for more information."
12857 (interactive)
12858 (cond
12859 ((org-at-table-p) (org-table-insert-column))
12860 ((org-on-heading-p) (org-demote-subtree))
12861 ((org-at-item-p) (call-interactively 'org-indent-item))
12862 (t (org-shiftcursor-error))))
12864 (defun org-shiftmetaup (&optional arg)
12865 "Move subtree up or kill table row.
12866 Calls `org-move-subtree-up' or `org-table-kill-row' or
12867 `org-move-item-up' depending on context. See the individual commands
12868 for more information."
12869 (interactive "P")
12870 (cond
12871 ((org-at-table-p) (org-table-kill-row))
12872 ((org-on-heading-p) (org-move-subtree-up arg))
12873 ((org-at-item-p) (org-move-item-up arg))
12874 (t (org-shiftcursor-error))))
12875 (defun org-shiftmetadown (&optional arg)
12876 "Move subtree down or insert table row.
12877 Calls `org-move-subtree-down' or `org-table-insert-row' or
12878 `org-move-item-down', depending on context. See the individual
12879 commands for more information."
12880 (interactive "P")
12881 (cond
12882 ((org-at-table-p) (org-table-insert-row arg))
12883 ((org-on-heading-p) (org-move-subtree-down arg))
12884 ((org-at-item-p) (org-move-item-down arg))
12885 (t (org-shiftcursor-error))))
12887 (defun org-metaleft (&optional arg)
12888 "Promote heading or move table column to left.
12889 Calls `org-do-promote' or `org-table-move-column', depending on context.
12890 With no specific context, calls the Emacs default `backward-word'.
12891 See the individual commands for more information."
12892 (interactive "P")
12893 (cond
12894 ((org-at-table-p) (org-table-move-column 'left))
12895 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12896 (t (backward-word (prefix-numeric-value arg)))))
12898 (defun org-metaright (&optional arg)
12899 "Demote subtree or move table column to right.
12900 Calls `org-do-demote' or `org-table-move-column', depending on context.
12901 With no specific context, calls the Emacs default `forward-word'.
12902 See the individual commands for more information."
12903 (interactive "P")
12904 (cond
12905 ((org-at-table-p) (org-table-move-column nil))
12906 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12907 (t (forward-word (prefix-numeric-value arg)))))
12909 (defun org-metaup (&optional arg)
12910 "Move subtree up or move table row up.
12911 Calls `org-move-subtree-up' or `org-table-move-row' or
12912 `org-move-item-up', depending on context. See the individual commands
12913 for more information."
12914 (interactive "P")
12915 (cond
12916 ((org-at-table-p) (org-table-move-row 'up))
12917 ((org-on-heading-p) (org-move-subtree-up arg))
12918 ((org-at-item-p) (org-move-item-up arg))
12919 (t (org-shiftcursor-error))))
12921 (defun org-metadown (&optional arg)
12922 "Move subtree down or move table row down.
12923 Calls `org-move-subtree-down' or `org-table-move-row' or
12924 `org-move-item-down', depending on context. See the individual
12925 commands for more information."
12926 (interactive "P")
12927 (cond
12928 ((org-at-table-p) (org-table-move-row nil))
12929 ((org-on-heading-p) (org-move-subtree-down arg))
12930 ((org-at-item-p) (org-move-item-down arg))
12931 (t (org-shiftcursor-error))))
12933 (defun org-shiftup (&optional arg)
12934 "Increase item in timestamp or increase priority of current item.
12935 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12936 See the individual commands for more information."
12937 (interactive "P")
12938 (cond
12939 ((org-at-timestamp-p) (org-timestamp-up arg))
12940 (t (org-priority-up))))
12942 (defun org-shiftdown (&optional arg)
12943 "Decrease item in timestamp or decrease priority of current item.
12944 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12945 See the individual commands for more information."
12946 (interactive "P")
12947 (cond
12948 ((org-at-timestamp-p) (org-timestamp-down arg))
12949 (t (org-priority-down))))
12951 (defun org-shiftright ()
12952 "Next TODO keyword or timestamp one day later, depending on context."
12953 (interactive)
12954 (cond
12955 ((org-at-timestamp-p) (org-timestamp-up-day))
12956 ((org-on-heading-p) (org-todo 'right))
12957 (t (org-shiftcursor-error))))
12959 (defun org-shiftleft ()
12960 "Previous TODO keyword or timestamp one day earlier, depending on context."
12961 (interactive)
12962 (cond
12963 ((org-at-timestamp-p) (org-timestamp-down-day))
12964 ((org-on-heading-p) (org-todo 'left))
12965 (t (org-shiftcursor-error))))
12967 (defun org-copy-special ()
12968 "Copy region in table or copy current subtree.
12969 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12970 See the individual commands for more information."
12971 (interactive)
12972 (call-interactively
12973 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12975 (defun org-cut-special ()
12976 "Cut region in table or cut current subtree.
12977 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12978 See the individual commands for more information."
12979 (interactive)
12980 (call-interactively
12981 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12983 (defun org-paste-special (arg)
12984 "Paste rectangular region into table, or past subtree relative to level.
12985 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12986 See the individual commands for more information."
12987 (interactive "P")
12988 (if (org-at-table-p)
12989 (org-table-paste-rectangle)
12990 (org-paste-subtree arg)))
12992 (defun org-ctrl-c-ctrl-c (&optional arg)
12993 "Set tags in headline, or update according to changed information at point.
12995 This command does many different things, depending on context:
12997 - If the cursor is in a headline, prompt for tags and insert them
12998 into the current line, aligned to `org-tags-column'. When called
12999 with prefix arg, realign all tags in the current buffer.
13001 - If the cursor is in one of the special #+KEYWORD lines, this
13002 triggers scanning the buffer for these lines and updating the
13003 information.
13005 - If the cursor is inside a table, realign the table. This command
13006 works even if the automatic table editor has been turned off.
13008 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13009 the entire table.
13011 - If the cursor is inside a table created by the table.el package,
13012 activate that table.
13014 - If the current buffer is a remember buffer, close note and file it.
13015 with a prefix argument, file it without further interaction to the default
13016 location.
13018 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13019 links in this buffer.
13021 - If the cursor is on a numbered item in a plain list, renumber the
13022 ordered list."
13023 (interactive "P")
13024 (let ((org-enable-table-editor t))
13025 (cond
13026 ((and (local-variable-p 'org-finish-function (current-buffer))
13027 (fboundp org-finish-function))
13028 (funcall org-finish-function))
13029 ((org-on-target-p) (org-update-radio-target-regexp))
13030 ((org-on-heading-p) (org-set-tags arg))
13031 ((org-at-table.el-p)
13032 (require 'table)
13033 (beginning-of-line 1)
13034 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13035 (table-recognize-table))
13036 ((org-at-table-p)
13037 (org-table-maybe-eval-formula)
13038 (if arg
13039 (org-table-recalculate t)
13040 (org-table-maybe-recalculate-line))
13041 (org-table-align))
13042 ((org-at-item-p)
13043 (org-renumber-ordered-list (prefix-numeric-value arg)))
13044 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13045 (cond
13046 ((equal (match-string 1) "TBLFM")
13047 ;; Recalculate the table before this line
13048 (save-excursion
13049 (beginning-of-line 1)
13050 (skip-chars-backward " \r\n\t")
13051 (if (org-at-table-p) (org-table-recalculate t))))
13053 (org-mode-restart))))
13054 (t (error "C-c C-c can do nothing useful at this location.")))))
13056 (defun org-mode-restart ()
13057 "Restart Org-mode, to scan again for special lines.
13058 Also updates the keyword regular expressions."
13059 (interactive)
13060 (let ((org-inhibit-startup t)) (org-mode))
13061 (message "Org-mode restarted to refresh keyword and special line setup"))
13063 (defun org-return ()
13064 "Goto next table row or insert a newline.
13065 Calls `org-table-next-row' or `newline', depending on context.
13066 See the individual commands for more information."
13067 (interactive)
13068 (cond
13069 ((org-at-table-p)
13070 (org-table-justify-field-maybe)
13071 (org-table-next-row))
13072 (t (newline))))
13074 (defun org-meta-return (&optional arg)
13075 "Insert a new heading or wrap a region in a table.
13076 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13077 See the individual commands for more information."
13078 (interactive "P")
13079 (cond
13080 ((org-at-table-p)
13081 (org-table-wrap-region arg))
13082 (t (org-insert-heading arg))))
13084 ;;; Menu entries
13086 ;; Define the Org-mode menus
13087 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13088 '("Tbl"
13089 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
13090 ["Next Field" org-cycle (org-at-table-p)]
13091 ["Previous Field" org-shifttab (org-at-table-p)]
13092 ["Next Row" org-return (org-at-table-p)]
13093 "--"
13094 ["Blank Field" org-table-blank-field (org-at-table-p)]
13095 ["Edit Field" org-table-edit-field (org-at-table-p)]
13096 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13097 "--"
13098 ("Column"
13099 ["Move Column Left" org-metaleft (org-at-table-p)]
13100 ["Move Column Right" org-metaright (org-at-table-p)]
13101 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13102 ["Insert Column" org-shiftmetaright (org-at-table-p)]
13103 "--"
13104 ["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])
13105 ("Row"
13106 ["Move Row Up" org-metaup (org-at-table-p)]
13107 ["Move Row Down" org-metadown (org-at-table-p)]
13108 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13109 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13110 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13111 "--"
13112 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
13113 ("Rectangle"
13114 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13115 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13116 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13117 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13118 "--"
13119 ("Calculate"
13120 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13121 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13122 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13123 "--"
13124 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13125 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13126 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13127 "--"
13128 ["Sum Column/Rectangle" org-table-sum
13129 (or (org-at-table-p) (org-region-active-p))]
13130 ["Which Column?" org-table-current-column (org-at-table-p)])
13131 ["Debug Formulas"
13132 (setq org-table-formula-debug (not org-table-formula-debug))
13133 :style toggle :selected org-table-formula-debug]
13134 "--"
13135 ["Create" org-table-create (and (not (org-at-table-p))
13136 org-enable-table-editor)]
13137 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13138 ["Import from File" org-table-import (not (org-at-table-p))]
13139 ["Export to File" org-table-export (org-at-table-p)]
13140 "--"
13141 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13143 (easy-menu-define org-org-menu org-mode-map "Org menu"
13144 '("Org"
13145 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13146 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13147 ["Sparse Tree" org-occur t]
13148 ["Show All" show-all t]
13149 "--"
13150 ["New Heading" org-insert-heading t]
13151 ("Navigate Headings"
13152 ["Up" outline-up-heading t]
13153 ["Next" outline-next-visible-heading t]
13154 ["Previous" outline-previous-visible-heading t]
13155 ["Next Same Level" outline-forward-same-level t]
13156 ["Previous Same Level" outline-backward-same-level t]
13157 "--"
13158 ["Jump" org-goto t])
13159 ("Edit Structure"
13160 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13161 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13162 "--"
13163 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13164 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13165 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13166 "--"
13167 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13168 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13169 ["Demote Heading" org-metaright (not (org-at-table-p))]
13170 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13171 "--"
13172 ["Archive Subtree" org-archive-subtree t]
13173 "--"
13174 ["Convert to odd levels" org-convert-to-odd-levels t]
13175 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13176 "--"
13177 ("TODO Lists"
13178 ["TODO/DONE/-" org-todo t]
13179 ["Show TODO Tree" org-show-todo-tree t]
13180 ["Global TODO list" org-todo-list t]
13181 "--"
13182 ["Set Priority" org-priority t]
13183 ["Priority Up" org-shiftup t]
13184 ["Priority Down" org-shiftdown t])
13185 ("Dates and Scheduling"
13186 ["Timestamp" org-time-stamp t]
13187 ["Timestamp (inactive)" org-time-stamp-inactive t]
13188 ("Change Date"
13189 ["1 Day Later" org-timestamp-up-day t]
13190 ["1 Day Earlier" org-timestamp-down-day t]
13191 ["1 ... Later" org-shiftup t]
13192 ["1 ... Earlier" org-shiftdown t])
13193 ["Compute Time Range" org-evaluate-time-range t]
13194 ["Schedule Item" org-schedule t]
13195 ["Deadline" org-deadline t]
13196 "--"
13197 ["Goto Calendar" org-goto-calendar t]
13198 ["Date from Calendar" org-date-from-calendar t])
13199 "--"
13200 ["Agenda Command" org-agenda t]
13201 ("File List for Agenda")
13202 ("Special views current file"
13203 ["TODO Tree" org-show-todo-tree t]
13204 ["Check Deadlines" org-check-deadlines t]
13205 ["Timeline" org-timeline t]
13206 ["Tags Tree" org-tags-sparse-tree t])
13207 "--"
13208 ("Hyperlinks"
13209 ["Store Link (Global)" org-store-link t]
13210 ["Insert Link" org-insert-link t]
13211 ["Follow Link" org-open-at-point t]
13212 "--"
13213 ["Descriptive Links"
13214 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13215 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13216 ["Literal Links"
13217 (progn
13218 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13219 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13220 "--"
13221 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13222 (save-excursion (goto-char (point-min))
13223 (re-search-forward "<[a-z]+:" nil t))])
13224 "--"
13225 ("Export"
13226 ["ASCII" org-export-as-ascii t]
13227 ["Extract Visible Text" org-export-copy-visible t]
13228 ["HTML" org-export-as-html t]
13229 ["HTML and Open" org-export-as-html-and-open t]
13230 ["XML (XOXO)" org-export-as-xml t]
13231 "--"
13232 ["iCalendar this file" org-export-icalendar-this-file t]
13233 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13234 :active t :keys "C-c C-x C-i"]
13235 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13236 "--"
13237 ["Option Template" org-insert-export-options-template t]
13238 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13239 "--"
13240 ("Documentation"
13241 ["Show Version" org-version t]
13242 ["Info Documentation" org-info t])
13243 ("Customize"
13244 ["Browse Org Group" org-customize t]
13245 "--"
13246 ["Expand This Menu" org-create-customize-menu
13247 (fboundp 'customize-menu-create)])
13248 "--"
13249 ["Refresh setup" org-mode-restart t]
13252 (defun org-info (&optional node)
13253 "Read documentation for Org-mode in the info system.
13254 With optional NODE, go directly to that node."
13255 (interactive)
13256 (require 'info)
13257 (Info-goto-node (format "(org)%s" (or node ""))))
13259 (defun org-install-agenda-files-menu ()
13260 (let ((bl (buffer-list)))
13261 (save-excursion
13262 (while bl
13263 (set-buffer (pop bl))
13264 (if (eq major-mode 'org-mode) (setq bl nil)))
13265 (when (eq major-mode 'org-mode)
13266 (easy-menu-change
13267 '("Org") "File List for Agenda"
13268 (append
13269 (list
13270 ["Edit File List" (org-edit-agenda-file-list) t]
13271 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13272 ["Remove Current File from List" org-remove-file t]
13273 ["Cycle through agenda files" org-cycle-agenda-files t]
13274 "--")
13275 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13277 ;;; Documentation
13279 (defun org-customize ()
13280 "Call the customize function with org as argument."
13281 (interactive)
13282 (customize-browse 'org))
13284 (defun org-create-customize-menu ()
13285 "Create a full customization menu for Org-mode, insert it into the menu."
13286 (interactive)
13287 (if (fboundp 'customize-menu-create)
13288 (progn
13289 (easy-menu-change
13290 '("Org") "Customize"
13291 `(["Browse Org group" org-customize t]
13292 "--"
13293 ,(customize-menu-create 'org)
13294 ["Set" Custom-set t]
13295 ["Save" Custom-save t]
13296 ["Reset to Current" Custom-reset-current t]
13297 ["Reset to Saved" Custom-reset-saved t]
13298 ["Reset to Standard Settings" Custom-reset-standard t]))
13299 (message "\"Org\"-menu now contains full customization menu"))
13300 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13302 ;;; Miscellaneous stuff
13304 (defun org-move-line-down (arg)
13305 "Move the current line down. With prefix argument, move it past ARG lines."
13306 (interactive "p")
13307 (let ((col (current-column))
13308 beg end pos)
13309 (beginning-of-line 1) (setq beg (point))
13310 (beginning-of-line 2) (setq end (point))
13311 (beginning-of-line (+ 1 arg))
13312 (setq pos (move-marker (make-marker) (point)))
13313 (insert (delete-and-extract-region beg end))
13314 (goto-char pos)
13315 (move-to-column col)))
13317 (defun org-move-line-up (arg)
13318 "Move the current line up. With prefix argument, move it past ARG lines."
13319 (interactive "p")
13320 (let ((col (current-column))
13321 beg end pos)
13322 (beginning-of-line 1) (setq beg (point))
13323 (beginning-of-line 2) (setq end (point))
13324 (beginning-of-line (- arg))
13325 (setq pos (move-marker (make-marker) (point)))
13326 (insert (delete-and-extract-region beg end))
13327 (goto-char pos)
13328 (move-to-column col)))
13330 ;; Paragraph filling stuff.
13331 ;; We want this to be just right, so use the full arsenal.
13332 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13333 ;; filladapt package works slightly differently.
13335 (defun org-set-autofill-regexps ()
13336 (interactive)
13337 ;; In the paragraph separator we include headlines, because filling
13338 ;; text in a line directly attached to a headline would otherwise
13339 ;; fill the headline as well.
13340 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13341 ;; The paragraph starter includes hand-formatted lists.
13342 (set (make-local-variable 'paragraph-start)
13343 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13344 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13345 ;; But only if the user has not turned off tables or fixed-width regions
13346 (set (make-local-variable 'auto-fill-inhibit-regexp)
13347 (concat "\\*\\|#"
13348 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13349 (concat
13350 "\\|[ \t]*["
13351 (if org-enable-table-editor "|" "")
13352 (if org-enable-fixed-width-editor ":" "")
13353 "]"))))
13354 ;; We use our own fill-paragraph function, to make sure that tables
13355 ;; and fixed-width regions are not wrapped. That function will pass
13356 ;; through to `fill-paragraph' when appropriate.
13357 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13358 ;; Adaptive filling: To get full control, first make sure that
13359 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13360 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13361 (set (make-local-variable 'adaptive-fill-function)
13362 'org-adaptive-fill-function))
13364 (defun org-fill-paragraph (&optional justify)
13365 "Re-align a table, pass through to fill-paragraph if no table."
13366 (let ((table-p (org-at-table-p))
13367 (table.el-p (org-at-table.el-p)))
13368 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13369 (table.el-p t) ; skip table.el tables
13370 (table-p (org-table-align) t) ; align org-mode tables
13371 (t nil)))) ; call paragraph-fill
13373 ;; For reference, this is the default value of adaptive-fill-regexp
13374 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13376 (defun org-adaptive-fill-function ()
13377 "Return a fill prefix for org-mode files.
13378 In particular, this makes sure hanging paragraphs for hand-formatted lists
13379 work correctly."
13380 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13381 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13383 ;; Functions needed for Emacs/XEmacs region compatibility
13385 (defun org-add-hook (hook function &optional append local)
13386 "Add-hook, compatible with both Emacsen."
13387 (if (and local (featurep 'xemacs))
13388 (add-local-hook hook function append)
13389 (add-hook hook function append local)))
13391 (defun org-region-active-p ()
13392 "Is `transient-mark-mode' on and the region active?
13393 Works on both Emacs and XEmacs."
13394 (if org-ignore-region
13396 (if (featurep 'xemacs)
13397 (and zmacs-regions (region-active-p))
13398 (and transient-mark-mode mark-active))))
13400 (defun org-add-to-invisibility-spec (arg)
13401 "Add elements to `buffer-invisibility-spec'.
13402 See documentation for `buffer-invisibility-spec' for the kind of elements
13403 that can be added."
13404 (cond
13405 ((fboundp 'add-to-invisibility-spec)
13406 (add-to-invisibility-spec arg))
13407 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13408 (setq buffer-invisibility-spec (list arg)))
13410 (setq buffer-invisibility-spec
13411 (cons arg buffer-invisibility-spec)))))
13413 (defun org-remove-from-invisibility-spec (arg)
13414 "Remove elements from `buffer-invisibility-spec'."
13415 (if (fboundp 'remove-from-invisibility-spec)
13416 (remove-from-invisibility-spec arg)
13417 (if (consp buffer-invisibility-spec)
13418 (setq buffer-invisibility-spec
13419 (delete arg buffer-invisibility-spec)))))
13421 (defun org-in-invisibility-spec-p (arg)
13422 "Is ARG a member of `buffer-invisibility-spec'?"
13423 (if (consp buffer-invisibility-spec)
13424 (member arg buffer-invisibility-spec)
13425 nil))
13427 (defun org-image-file-name-regexp ()
13428 "Return regexp matching the file names of images."
13429 (if (fboundp 'image-file-name-regexp)
13430 (image-file-name-regexp)
13431 (let ((image-file-name-extensions
13432 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13433 "xbm" "xpm" "pbm" "pgm" "ppm")))
13434 (concat "\\."
13435 (regexp-opt (nconc (mapcar 'upcase
13436 image-file-name-extensions)
13437 image-file-name-extensions)
13439 "\\'"))))
13441 ;; Functions needed for compatibility with old outline.el.
13443 ;; Programming for the old outline.el (that uses selective display
13444 ;; instead of `invisible' text properties) is a nightmare, mostly
13445 ;; because regular expressions can no longer be anchored at
13446 ;; beginning/end of line. Therefore a number of function need special
13447 ;; treatment when the old outline.el is being used.
13449 ;; The following functions capture almost the entire compatibility code
13450 ;; between the different versions of outline-mode. The only other
13451 ;; places where this is important are the font-lock-keywords, and in
13452 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13454 ;; C-a should go to the beginning of a *visible* line, also in the
13455 ;; new outline.el. I guess this should be patched into Emacs?
13456 (defun org-beginning-of-line ()
13457 "Go to the beginning of the current line. If that is invisible, continue
13458 to a visible line beginning. This makes the function of C-a more intuitive."
13459 (interactive)
13460 (beginning-of-line 1)
13461 (if (bobp)
13463 (backward-char 1)
13464 (if (org-invisible-p)
13465 (while (and (not (bobp)) (org-invisible-p))
13466 (backward-char 1)
13467 (beginning-of-line 1))
13468 (forward-char 1))))
13470 (when org-noutline-p
13471 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13472 ;; FIXME: should I use substitute-key-definition to reach other bindings
13473 ;; of beginning-of-line?
13475 (defun org-invisible-p ()
13476 "Check if point is at a character currently not visible."
13477 (if org-noutline-p
13478 ;; Early versions of noutline don't have `outline-invisible-p'.
13479 (if (fboundp 'outline-invisible-p)
13480 (outline-invisible-p)
13481 (get-char-property (point) 'invisible))
13482 (save-excursion
13483 (skip-chars-backward "^\r\n")
13484 (equal (char-before) ?\r))))
13486 (defun org-invisible-p2 ()
13487 "Check if point is at a character currently not visible."
13488 (save-excursion
13489 (if org-noutline-p
13490 (progn
13491 (if (and (eolp) (not (bobp))) (backward-char 1))
13492 ;; Early versions of noutline don't have `outline-invisible-p'.
13493 (if (fboundp 'outline-invisible-p)
13494 (outline-invisible-p)
13495 (get-char-property (point) 'invisible)))
13496 (skip-chars-backward "^\r\n")
13497 (equal (char-before) ?\r))))
13499 (defun org-back-to-heading (&optional invisible-ok)
13500 "Move to previous heading line, or beg of this line if it's a heading.
13501 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13502 (if org-noutline-p
13503 (outline-back-to-heading invisible-ok)
13504 (if (and (memq (char-before) '(?\n ?\r))
13505 (looking-at outline-regexp))
13507 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13508 outline-regexp)
13509 nil t)
13510 (if invisible-ok
13511 (progn (goto-char (match-end 1))
13512 (looking-at outline-regexp)))
13513 (error "Before first heading")))))
13515 (defun org-on-heading-p (&optional invisible-ok)
13516 "Return t if point is on a (visible) heading line.
13517 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13518 (if org-noutline-p
13519 (outline-on-heading-p 'invisible-ok)
13520 (save-excursion
13521 (skip-chars-backward "^\n\r")
13522 (and (looking-at outline-regexp)
13523 (or invisible-ok
13524 (bobp)
13525 (equal (char-before) ?\n))))))
13527 (defun org-on-target-p ()
13528 (let ((pos (point)))
13529 (save-excursion
13530 (skip-chars-forward "<")
13531 (and (re-search-backward "<<" nil t)
13532 (or (looking-at org-radio-target-regexp)
13533 (looking-at org-target-regexp))
13534 (<= (match-beginning 0) pos)
13535 (>= (1+ (match-end 0)) pos)))))
13537 (defun org-up-heading-all (arg)
13538 "Move to the heading line of which the present line is a subheading.
13539 This function considers both visible and invisible heading lines.
13540 With argument, move up ARG levels."
13541 (if org-noutline-p
13542 (if (fboundp 'outline-up-heading-all)
13543 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13544 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13545 (org-back-to-heading t)
13546 (looking-at outline-regexp)
13547 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13548 (error "Cannot move up %d levels" arg)
13549 (re-search-backward
13550 (concat "[\n\r]" (regexp-quote
13551 (make-string (- (match-end 0) (match-beginning 0) arg)
13552 ?*))
13553 "[^*]"))
13554 (forward-char 1))))
13556 (defun org-show-hidden-entry ()
13557 "Show an entry where even the heading is hidden."
13558 (save-excursion
13559 (if (not org-noutline-p)
13560 (progn
13561 (org-back-to-heading t)
13562 (org-flag-heading nil)))
13563 (org-show-entry)))
13565 (defun org-check-occur-regexp (regexp)
13566 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13567 Of course, only for the old outline mode."
13568 (if org-noutline-p
13569 regexp
13570 (if (string-match "^\\^" regexp)
13571 (concat "[\n\r]" (substring regexp 1))
13572 regexp)))
13574 (defun org-flag-heading (flag &optional entry)
13575 "Flag the current heading. FLAG non-nil means make invisible.
13576 When ENTRY is non-nil, show the entire entry."
13577 (save-excursion
13578 (org-back-to-heading t)
13579 (if (not org-noutline-p)
13580 ;; Make the current headline visible
13581 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13582 ;; Check if we should show the entire entry
13583 (if entry
13584 (progn
13585 (org-show-entry)
13586 (save-excursion ;; FIXME: Is this the fix for points in the -|
13587 ;; middle of text? |
13588 (and (outline-next-heading) ;; |
13589 (org-flag-heading nil)))) ; show the next heading _|
13590 (outline-flag-region (max 1 (1- (point)))
13591 (save-excursion (outline-end-of-heading) (point))
13592 (if org-noutline-p
13593 flag
13594 (if flag ?\r ?\n))))))
13596 (defun org-end-of-subtree (&optional invisible-OK)
13597 ;; This is an exact copy of the original function, but it uses
13598 ;; `org-back-to-heading', to make it work also in invisible
13599 ;; trees. And is uses an invisible-OK argument.
13600 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13601 (org-back-to-heading invisible-OK)
13602 (let ((first t)
13603 (level (funcall outline-level)))
13604 (while (and (not (eobp))
13605 (or first (> (funcall outline-level) level)))
13606 (setq first nil)
13607 (outline-next-heading))
13608 (if (memq (preceding-char) '(?\n ?\^M))
13609 (progn
13610 ;; Go to end of line before heading
13611 (forward-char -1)
13612 (if (memq (preceding-char) '(?\n ?\^M))
13613 ;; leave blank line before heading
13614 (forward-char -1))))))
13616 (defun org-show-subtree ()
13617 "Show everything after this heading at deeper levels."
13618 (outline-flag-region
13619 (point)
13620 (save-excursion
13621 (outline-end-of-subtree) (outline-next-heading) (point))
13622 (if org-noutline-p nil ?\n)))
13624 (defun org-show-entry ()
13625 "Show the body directly following this heading.
13626 Show the heading too, if it is currently invisible."
13627 (interactive)
13628 (save-excursion
13629 (org-back-to-heading t)
13630 (outline-flag-region
13631 (1- (point))
13632 (save-excursion
13633 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13634 (or (match-beginning 1) (point-max)))
13635 (if org-noutline-p nil ?\n))))
13637 (defun org-make-options-regexp (kwds)
13638 "Make a regular expression for keyword lines."
13639 (concat
13640 (if org-noutline-p "^" "[\n\r]")
13641 "#?[ \t]*\\+\\("
13642 (mapconcat 'regexp-quote kwds "\\|")
13643 "\\):[ \t]*"
13644 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13646 ;; Make `bookmark-jump' show the jump location if it was hidden.
13647 (eval-after-load "bookmark"
13648 '(if (boundp 'bookmark-after-jump-hook)
13649 ;; We can use the hook
13650 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13651 ;; Hook not available, use advice
13652 (defadvice bookmark-jump (after org-make-visible activate)
13653 "Make the position visible."
13654 (org-bookmark-jump-unhide))))
13656 (defun org-bookmark-jump-unhide ()
13657 "Unhide the current position, to show the bookmark location."
13658 (and (eq major-mode 'org-mode)
13659 (or (org-invisible-p)
13660 (save-excursion (goto-char (max (point-min) (1- (point))))
13661 (org-invisible-p)))
13662 (org-show-hierarchy-above)))
13664 ;;; Finish up
13666 (provide 'org)
13668 (run-hooks 'org-load-hook)
13670 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13671 ;;; org.el ends here