1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
66 (defvar org-inhibit-highlight-removal nil
) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local
)
71 ;;;; Require other packages
79 (require 'format-spec
)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil
'mustsuffix
))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp
"\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol
"^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp
"^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias
)
105 (unless (boundp 'calendar-view-holidays-initially-flag
)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially
))
108 (unless (boundp 'calendar-view-diary-initially-flag
)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially
))
111 (unless (boundp 'diary-fancy-buffer
)
112 (defvaralias 'diary-fancy-buffer
'fancy-diary-buffer
)))
114 (declare-function org-inlinetask-at-task-p
"org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp
"org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility
"org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window
"org-compat" (&optional buffer-or-name norecord label
))
118 (declare-function org-at-clock-log-p
"org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time
"org-clock" ())
120 (declare-function org-clock-timestamps-up
"org-clock" ())
121 (declare-function org-clock-timestamps-down
"org-clock" ())
122 (declare-function org-clock-sum-current-item
"org-clock" (&optional tstart
))
124 (declare-function orgtbl-mode
"org-table" (&optional arg
))
125 (declare-function org-clock-out
"org-clock" (&optional switch-to-state fail-quietly at-time
))
126 (declare-function org-beamer-mode
"org-beamer" ())
127 (declare-function org-table-edit-field
"org-table" (arg))
128 (declare-function org-table-justify-field-maybe
"org-table" (&optional new
))
129 (declare-function org-id-get-create
"org-id" (&optional force
))
130 (declare-function org-id-find-id-file
"org-id" (id))
131 (declare-function org-tags-view
"org-agenda" (&optional todo-only match
))
132 (declare-function org-agenda-list
"org-agenda" (&optional arg start-day span
))
133 (declare-function org-table-align
"org-table" ())
134 (declare-function org-table-paste-rectangle
"org-table" ())
135 (declare-function org-table-maybe-eval-formula
"org-table" ())
136 (declare-function org-table-maybe-recalculate-line
"org-table" ())
138 (autoload 'org-element-at-point
"org-element")
140 (declare-function org-element-at-point
"org-element" (&optional keep-trail
))
141 (declare-function org-element-type
"org-element" (element))
142 (declare-function org-element-context
"org-element" ())
143 (declare-function org-element-contents
"org-element" (element))
144 (declare-function org-element-property
"org-element" (property element
))
145 (declare-function org-element-paragraph-parser
"org-element" (limit))
146 (declare-function org-element-map
"org-element" (data types fun
&optional info first-match no-recursion
))
147 (declare-function org-element-nested-p
"org-element" (elem-a elem-b
))
148 (declare-function org-element-swap-A-B
"org-element" (elem-a elem-b
))
149 (declare-function org-element--parse-objects
"org-element" (beg end acc restriction
))
150 (declare-function org-element-parse-buffer
"org-element" (&optional granularity visible-only
))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages
)
156 (defun org-babel-do-load-languages (sym value
)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value
)
160 (let ((active (cdr pair
)) (lang (symbol-name (car pair
))))
163 (require (intern (concat "ob-" lang
))))
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang
)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang
)))))))
169 org-babel-load-languages
))
171 (defcustom org-babel-load-languages
'((emacs-lisp . t
))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
183 :set
'org-babel-do-load-languages
185 :type
'(alist :tag
"Babel Languages"
188 (const :tag
"Awk" awk
)
191 (const :tag
"Asymptote" asymptote
)
192 (const :tag
"Calc" calc
)
193 (const :tag
"Clojure" clojure
)
194 (const :tag
"CSS" css
)
195 (const :tag
"Ditaa" ditaa
)
196 (const :tag
"Dot" dot
)
197 (const :tag
"Emacs Lisp" emacs-lisp
)
198 (const :tag
"Fortran" fortran
)
199 (const :tag
"Gnuplot" gnuplot
)
200 (const :tag
"Haskell" haskell
)
202 (const :tag
"Java" java
)
203 (const :tag
"Javascript" js
)
204 (const :tag
"LaTeX" latex
)
205 (const :tag
"Ledger" ledger
)
206 (const :tag
"Lilypond" lilypond
)
207 (const :tag
"Lisp" lisp
)
208 (const :tag
"Maxima" maxima
)
209 (const :tag
"Matlab" matlab
)
210 (const :tag
"Mscgen" mscgen
)
211 (const :tag
"Ocaml" ocaml
)
212 (const :tag
"Octave" octave
)
213 (const :tag
"Org" org
)
214 (const :tag
"Perl" perl
)
215 (const :tag
"Pico Lisp" picolisp
)
216 (const :tag
"PlantUML" plantuml
)
217 (const :tag
"Python" python
)
218 (const :tag
"Ruby" ruby
)
219 (const :tag
"Sass" sass
)
220 (const :tag
"Scala" scala
)
221 (const :tag
"Scheme" scheme
)
222 (const :tag
"Screen" screen
)
223 (const :tag
"Shell Script" sh
)
224 (const :tag
"Shen" shen
)
225 (const :tag
"Sql" sql
)
226 (const :tag
"Sqlite" sqlite
))
227 :value-type
(boolean :tag
"Activate" :value t
)))
229 ;;;; Customization variables
230 (defcustom org-clone-delete-id nil
231 "Remove ID property of clones of a subtree.
232 When non-nil, clones of a subtree don't inherit the ID property.
233 Otherwise they inherit the ID property with a new unique
240 (require 'org-compat
)
244 (defun org-version (&optional here full message
)
245 "Show the org-mode version in the echo area.
246 With prefix argument HERE, insert it at point.
247 When FULL is non-nil, use a verbose version string.
248 When MESSAGE is non-nil, display a message with the version."
250 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
251 (save-load-suffixes load-suffixes
)
252 (load-suffixes (list ".el"))
253 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (and (fboundp 'org-release
) (fboundp 'org-git-version
))
256 (load (concat org-dir
"org-version")
257 'noerror
'nomessage nil
'mustsuffix
)))
258 (load-suffixes save-load-suffixes
)
259 (org-version (org-release))
260 (git-version (org-git-version))
261 (version (format "Org-mode version %s (%s @ %s)"
265 (if (string= org-dir org-install-dir
)
267 (concat "mixed installation! " org-install-dir
" and " org-dir
))
268 "org-loaddefs.el can not be found!")))
269 (_version (if full version org-version
)))
270 (if (org-called-interactively-p 'interactive
)
274 (if message
(message _version
))
277 (defconst org-version
(org-version))
279 ;;; Compatibility constants
281 ;;; The custom variables
284 "Outline-based notes management and organizer."
289 (defcustom org-mode-hook nil
290 "Mode hook for Org-mode, run after the mode was turned on."
294 (defcustom org-load-hook nil
295 "Hook that is run after org.el has been loaded."
299 (defcustom org-log-buffer-setup-hook nil
300 "Hook that is run after an Org log buffer is created."
305 (defvar org-modules
) ; defined below
306 (defvar org-modules-loaded nil
307 "Have the modules been loaded already?")
309 (defun org-load-modules-maybe (&optional force
)
310 "Load all extensions listed in `org-modules'."
311 (when (or force
(not org-modules-loaded
))
313 (condition-case nil
(require ext
)
314 (error (message "Problems while trying to load feature `%s'" ext
))))
316 (setq org-modules-loaded t
)))
318 (defun org-set-modules (var value
)
319 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (when (featurep 'org
)
322 (org-load-modules-maybe 'force
)))
324 (when (org-bound-and-true-p org-modules
)
325 (let ((a (member 'org-infojs org-modules
)))
326 (and a
(setcar a
'org-jsinfo
))))
328 (defcustom org-modules
'(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl
)
329 "Modules that should always be loaded together with org.el.
330 If a description starts with <C>, the file is not part of Emacs
331 and loading it will require that you have downloaded and properly installed
332 the org-mode distribution.
334 You can also use this system to load external packages (i.e. neither Org
335 core modules, nor modules from the CONTRIB directory). Just add symbols
336 to the end of the list. If the package is called org-xyz.el, then you need
337 to add the symbol `xyz', and the package must have a call to
341 :set
'org-set-modules
344 (const :tag
" bbdb: Links to BBDB entries" org-bbdb
)
345 (const :tag
" bibtex: Links to BibTeX entries" org-bibtex
)
346 (const :tag
" crypt: Encryption of subtrees" org-crypt
)
347 (const :tag
" ctags: Access to Emacs tags with links" org-ctags
)
348 (const :tag
" docview: Links to doc-view buffers" org-docview
)
349 (const :tag
" gnus: Links to GNUS folders/messages" org-gnus
)
350 (const :tag
" id: Global IDs for identifying entries" org-id
)
351 (const :tag
" info: Links to Info nodes" org-info
)
352 (const :tag
" jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo
)
353 (const :tag
" habit: Track your consistency with habits" org-habit
)
354 (const :tag
" inlinetask: Tasks independent of outline hierarchy" org-inlinetask
)
355 (const :tag
" irc: Links to IRC/ERC chat sessions" org-irc
)
356 (const :tag
" mac-message: Links to messages in Apple Mail" org-mac-message
)
357 (const :tag
" mew Links to Mew folders/messages" org-mew
)
358 (const :tag
" mhe: Links to MHE folders/messages" org-mhe
)
359 (const :tag
" protocol: Intercept calls from emacsclient" org-protocol
)
360 (const :tag
" rmail: Links to RMAIL folders/messages" org-rmail
)
361 (const :tag
" special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks
)
362 (const :tag
" vm: Links to VM folders/messages" org-vm
)
363 (const :tag
" wl: Links to Wanderlust folders/messages" org-wl
)
364 (const :tag
" w3m: Special cut/paste from w3m to Org-mode." org-w3m
)
365 (const :tag
" mouse: Additional mouse support" org-mouse
)
366 (const :tag
" TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler
)
368 (const :tag
"C annotate-file: Annotate a file with org syntax" org-annotate-file
)
369 (const :tag
"C bookmark: Org-mode links to bookmarks" org-bookmark
)
370 (const :tag
"C checklist: Extra functions for checklists in repeated tasks" org-checklist
)
371 (const :tag
"C choose: Use TODO keywords to mark decisions states" org-choose
)
372 (const :tag
"C collector: Collect properties into tables" org-collector
)
373 (const :tag
"C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend
)
374 (const :tag
"C drill: Flashcards and spaced repetition for Org-mode" org-drill
)
375 (const :tag
"C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol
)
376 (const :tag
"C eshell Support for links to working directories in eshell" org-eshell
)
377 (const :tag
"C eval: Include command output as text" org-eval
)
378 (const :tag
"C eval-light: Evaluate inbuffer-code on demand" org-eval-light
)
379 (const :tag
"C expiry: Expiry mechanism for Org-mode entries" org-expiry
)
380 (const :tag
"C exp-bibtex: Export citations using BibTeX" org-exp-bibtex
)
381 (const :tag
"C git-link: Provide org links to specific file version" org-git-link
)
382 (const :tag
"C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query
)
384 (const :tag
"C invoice: Help manage client invoices in Org-mode" org-invoice
)
386 (const :tag
"C jira: Add a jira:ticket protocol to Org-mode" org-jira
)
387 (const :tag
"C learn: SuperMemo's incremental learning algorithm" org-learn
)
388 (const :tag
"C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix
)
389 (const :tag
"C notmuch: Provide org links to notmuch searches or messages" org-notmuch
)
390 (const :tag
"C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal
)
391 (const :tag
"C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber
)
392 (const :tag
"C man: Support for links to manpages in Org-mode" org-man
)
393 (const :tag
"C mtags: Support for muse-like tags" org-mtags
)
394 (const :tag
"C panel: Simple routines for us with bad memory" org-panel
)
395 (const :tag
"C registry: A registry for Org-mode links" org-registry
)
396 (const :tag
"C org2rem: Convert org appointments into reminders" org2rem
)
397 (const :tag
"C screen: Visit screen sessions through Org-mode links" org-screen
)
398 (const :tag
"C secretary: Team management with org-mode" org-secretary
)
399 (const :tag
"C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert
)
400 (const :tag
"C toc: Table of contents for Org-mode buffer" org-toc
)
401 (const :tag
"C track: Keep up with Org-mode development" org-track
)
402 (const :tag
"C velocity Something like Notational Velocity for Org" org-velocity
)
403 (const :tag
"C wikinodes: CamelCase wiki-like links" org-wikinodes
)
404 (repeat :tag
"External packages" :inline t
(symbol :tag
"Package"))))
406 (defcustom org-support-shift-select nil
407 "Non-nil means make shift-cursor commands select text when possible.
409 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
410 start selecting a region, or enlarge regions started in this way.
411 In Org-mode, in special contexts, these same keys are used for
412 other purposes, important enough to compete with shift selection.
413 Org tries to balance these needs by supporting `shift-select-mode'
414 outside these special contexts, under control of this variable.
416 The default of this variable is nil, to avoid confusing behavior. Shifted
417 cursor keys will then execute Org commands in the following contexts:
418 - on a headline, changing TODO state (left/right) and priority (up/down)
419 - on a time stamp, changing the time
420 - in a plain list item, changing the bullet type
421 - in a property definition line, switching between allowed values
422 - in the BEGIN line of a clock table (changing the time block).
423 Outside these contexts, the commands will throw an error.
425 When this variable is t and the cursor is not in a special
426 context, Org-mode will support shift-selection for making and
427 enlarging regions. To make this more effective, the bullet
428 cycling will no longer happen anywhere in an item line, but only
429 if the cursor is exactly on the bullet.
431 If you set this variable to the symbol `always', then the keys
432 will not be special in headlines, property lines, and item lines,
433 to make shift selection work there as well. If this is what you
434 want, you can use the following alternative commands: `C-c C-t'
435 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
436 can be used to switch TODO sets, `C-c -' to cycle item bullet
437 types, and properties can be edited by hand or in column view.
439 However, when the cursor is on a timestamp, shift-cursor commands
440 will still edit the time stamp - this is just too good to give up.
442 XEmacs user should have this variable set to nil, because
443 `shift-select-mode' is in Emacs 23 or later only."
446 (const :tag
"Never" nil
)
447 (const :tag
"When outside special context" t
)
448 (const :tag
"Everywhere except timestamps" always
)))
450 (defcustom org-loop-over-headlines-in-active-region nil
451 "Shall some commands act upon headlines in the active region?
453 When set to `t', some commands will be performed in all headlines
454 within the active region.
456 When set to `start-level', some commands will be performed in all
457 headlines within the active region, provided that these headlines
458 are of the same level than the first one.
460 When set to a string, those commands will be performed on the
461 matching headlines within the active region. Such string must be
462 a tags/property/todo match as it is used in the agenda tags view.
464 The list of commands is: `org-schedule', `org-deadline',
465 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
466 `org-archive-to-archive-sibling'. The archiving commands skip
467 already archived entries."
468 :type
'(choice (const :tag
"Don't loop" nil
)
469 (const :tag
"All headlines in active region" t
)
470 (const :tag
"In active region, headlines at the same level than the first one" 'start-level
)
471 (string :tag
"Tags/Property/Todo matcher"))
476 (defgroup org-startup nil
477 "Options concerning startup of Org-mode."
481 (defcustom org-startup-folded t
482 "Non-nil means entering Org-mode will switch to OVERVIEW.
483 This can also be configured on a per-file basis by adding one of
484 the following lines anywhere in the buffer:
486 #+STARTUP: fold (or `overview', this is equivalent)
487 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: showeverything"
492 (const :tag
"nofold: show all" nil
)
493 (const :tag
"fold: overview" t
)
494 (const :tag
"content: all headlines" content
)
495 (const :tag
"show everything, even drawers" showeverything
)))
497 (defcustom org-startup-truncated t
498 "Non-nil means entering Org-mode will set `truncate-lines'.
499 This is useful since some lines containing links can be very long and
500 uninteresting. Also tables look terrible when wrapped."
504 (defcustom org-startup-indented nil
505 "Non-nil means turn on `org-indent-mode' on startup.
506 This can also be configured on a per-file basis by adding one of
507 the following lines anywhere in the buffer:
511 :group
'org-structure
513 (const :tag
"Not" nil
)
514 (const :tag
"Globally (slow on startup in large files)" t
)))
516 (defcustom org-use-sub-superscripts t
517 "Non-nil means interpret \"_\" and \"^\" for export.
518 When this option is turned on, you can use TeX-like syntax for sub- and
519 superscripts. Several characters after \"_\" or \"^\" will be
520 considered as a single item - so grouping with {} is normally not
521 needed. For example, the following things will be parsed as single
522 sub- or superscripts.
524 10^24 or 10^tau several digits will be considered 1 item.
525 10^-12 or 10^-tau a leading sign with digits or a word
526 x^2-y^3 will be read as x^2 - y^3, because items are
527 terminated by almost any nonword/nondigit char.
528 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
530 Still, ambiguity is possible - so when in doubt use {} to enclose the
531 sub/superscript. If you set this variable to the symbol `{}',
532 the braces are *required* in order to trigger interpretations as
533 sub/superscript. This can be helpful in documents that need \"_\"
534 frequently in plain text.
536 Not all export backends support this, but HTML does.
538 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group
'org-export-translation
543 (const :tag
"Always interpret" t
)
544 (const :tag
"Only with braces" {})
545 (const :tag
"Never interpret" nil
)))
547 (if (fboundp 'defvaralias
)
548 (defvaralias 'org-export-with-sub-superscripts
'org-use-sub-superscripts
))
551 (defcustom org-startup-with-beamer-mode nil
552 "Non-nil means turn on `org-beamer-mode' on startup.
553 This can also be configured on a per-file basis by adding one of
554 the following lines anywhere in the buffer:
561 (defcustom org-startup-align-all-tables nil
562 "Non-nil means align all tables when visiting a file.
563 This is useful when the column width in tables is forced with <N> cookies
564 in table fields. Such tables will look correct only after the first re-align.
565 This can also be configured on a per-file basis by adding one of
566 the following lines anywhere in the buffer:
572 (defcustom org-startup-with-inline-images nil
573 "Non-nil means show inline images when loading a new Org file.
574 This can also be configured on a per-file basis by adding one of
575 the following lines anywhere in the buffer:
576 #+STARTUP: inlineimages
577 #+STARTUP: noinlineimages"
582 (defcustom org-insert-mode-line-in-empty-file nil
583 "Non-nil means insert the first line setting Org-mode in empty files.
584 When the function `org-mode' is called interactively in an empty file, this
585 normally means that the file name does not automatically trigger Org-mode.
586 To ensure that the file will always be in Org-mode in the future, a
587 line enforcing Org-mode will be inserted into the buffer, if this option
592 (defcustom org-replace-disputed-keys nil
593 "Non-nil means use alternative key bindings for some keys.
594 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
595 These keys are also used by other packages like shift-selection-mode'
596 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
597 If you want to use Org-mode together with one of these other modes,
598 or more generally if you would like to move some Org-mode commands to
599 other keys, set this variable and configure the keys with the variable
602 This option is only relevant at load-time of Org-mode, and must be set
603 *before* org.el is loaded. Changing it requires a restart of Emacs to
608 (defcustom org-use-extra-keys nil
609 "Non-nil means use extra key sequence definitions for certain commands.
610 This happens automatically if you run XEmacs or if `window-system'
611 is nil. This variable lets you do the same manually. You must
612 set it before loading org.
614 Example: on Carbon Emacs 22 running graphically, with an external
615 keyboard on a Powerbook, the default way of setting M-left might
616 not work for either Alt or ESC. Setting this variable will make
621 (if (fboundp 'defvaralias
)
622 (defvaralias 'org-CUA-compatible
'org-replace-disputed-keys
))
624 (defcustom org-disputed-keys
625 '(([(shift up
)] .
[(meta p
)])
626 ([(shift down
)] .
[(meta n
)])
627 ([(shift left
)] .
[(meta -
)])
628 ([(shift right
)] .
[(meta +)])
629 ([(control shift right
)] .
[(meta shift
+)])
630 ([(control shift left
)] .
[(meta shift -
)]))
631 "Keys for which Org-mode and other modes compete.
632 This is an alist, cars are the default keys, second element specifies
633 the alternative to use when `org-replace-disputed-keys' is t.
635 Keys can be specified in any syntax supported by `define-key'.
636 The value of this option takes effect only at Org-mode's startup,
637 therefore you'll have to restart Emacs to apply it after changing."
642 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
643 Or return the original if not disputed.
644 Also apply the translations defined in `org-xemacs-key-equivalents'."
645 (when org-replace-disputed-keys
646 (let* ((nkey (key-description key
))
647 (x (org-find-if (lambda (x)
648 (equal (key-description (car x
)) nkey
))
650 (setq key
(if x
(cdr x
) key
))))
651 (when (featurep 'xemacs
)
652 (setq key
(or (cdr (assoc key org-xemacs-key-equivalents
)) key
)))
655 (defun org-find-if (predicate seq
)
658 (if (funcall predicate
(car seq
))
659 (throw 'exit
(car seq
))
662 (defun org-defkey (keymap key def
)
663 "Define a key, possibly translated, as returned by `org-key'."
664 (define-key keymap
(org-key key
) def
))
666 (defcustom org-ellipsis nil
667 "The ellipsis to use in the Org-mode outline.
668 When nil, just use the standard three dots. When a string, use that instead,
669 When a face, use the standard 3 dots, but with the specified face.
670 The change affects only Org-mode (which will then use its own display table).
671 Changing this requires executing `M-x org-mode' in a buffer to become
674 :type
'(choice (const :tag
"Default" nil
)
675 (face :tag
"Face" :value org-warning
)
676 (string :tag
"String" :value
"...#")))
678 (defvar org-display-table nil
679 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
681 (defgroup org-keywords nil
682 "Keywords in Org-mode."
686 (defcustom org-deadline-string
"DEADLINE:"
687 "String to mark deadline entries.
688 A deadline is this string, followed by a time stamp. Should be a word,
689 terminated by a colon. You can insert a schedule keyword and
690 a timestamp with \\[org-deadline].
691 Changes become only effective after restarting Emacs."
695 (defcustom org-scheduled-string
"SCHEDULED:"
696 "String to mark scheduled TODO entries.
697 A schedule is this string, followed by a time stamp. Should be a word,
698 terminated by a colon. You can insert a schedule keyword and
699 a timestamp with \\[org-schedule].
700 Changes become only effective after restarting Emacs."
704 (defcustom org-closed-string
"CLOSED:"
705 "String used as the prefix for timestamps logging closing a TODO entry."
709 (defcustom org-clock-string
"CLOCK:"
710 "String used as prefix for timestamps clocking work hours on an item."
714 (defconst org-planning-or-clock-line-re
(concat "^[ \t]*\\("
715 org-scheduled-string
"\\|"
716 org-deadline-string
"\\|"
717 org-closed-string
"\\|"
718 org-clock-string
"\\)")
719 "Matches a line with planning or clock info.")
721 (defcustom org-comment-string
"COMMENT"
722 "Entries starting with this keyword will never be exported.
723 An entry can be toggled between COMMENT and normal with
724 \\[org-toggle-comment].
725 Changes become only effective after restarting Emacs."
729 (defcustom org-quote-string
"QUOTE"
730 "Entries starting with this keyword will be exported in fixed-width font.
731 Quoting applies only to the text in the entry following the headline, and does
732 not extend beyond the next headline, even if that is lower level.
733 An entry can be toggled between QUOTE and normal with
734 \\[org-toggle-fixed-width-section]."
738 (defconst org-repeat-re
739 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
740 "Regular expression for specifying repeated events.
741 After a match, group 1 contains the repeat expression.")
743 (defgroup org-structure nil
744 "Options concerning the general structure of Org-mode files."
748 (defgroup org-reveal-location nil
749 "Options about how to make context of a location visible."
750 :tag
"Org Reveal Location"
751 :group
'org-structure
)
753 (defconst org-context-choice
755 (const :tag
"Always" t
)
756 (const :tag
"Never" nil
)
757 (repeat :greedy t
:tag
"Individual contexts"
759 (choice :tag
"Context"
766 (const bookmark-jump
)
770 "Contexts for the reveal options.")
772 (defcustom org-show-hierarchy-above
'((default . t
))
773 "Non-nil means show full hierarchy when revealing a location.
774 Org-mode often shows locations in an org-mode file which might have
775 been invisible before. When this is set, the hierarchy of headings
776 above the exposed location is shown.
777 Turning this off for example for sparse trees makes them very compact.
778 Instead of t, this can also be an alist specifying this option for different
779 contexts. Valid contexts are
780 agenda when exposing an entry from the agenda
781 org-goto when using the command `org-goto' on key C-c C-j
782 occur-tree when using the command `org-occur' on key C-c /
783 tags-tree when constructing a sparse tree based on tags matches
784 link-search when exposing search matches associated with a link
785 mark-goto when exposing the jump goal of a mark
786 bookmark-jump when exposing a bookmark location
787 isearch when exiting from an incremental search
788 default default for all contexts not set explicitly"
789 :group
'org-reveal-location
790 :type org-context-choice
)
792 (defcustom org-show-following-heading
'((default . nil
))
793 "Non-nil means show following heading when revealing a location.
794 Org-mode often shows locations in an org-mode file which might have
795 been invisible before. When this is set, the heading following the
797 Turning this off for example for sparse trees makes them very compact,
798 but makes it harder to edit the location of the match. In such a case,
799 use the command \\[org-reveal] to show more context.
800 Instead of t, this can also be an alist specifying this option for different
801 contexts. See `org-show-hierarchy-above' for valid contexts."
802 :group
'org-reveal-location
803 :type org-context-choice
)
805 (defcustom org-show-siblings
'((default . nil
) (isearch t
))
806 "Non-nil means show all sibling heading when revealing a location.
807 Org-mode often shows locations in an org-mode file which might have
808 been invisible before. When this is set, the sibling of the current entry
809 heading are all made visible. If `org-show-hierarchy-above' is t,
810 the same happens on each level of the hierarchy above the current entry.
812 By default this is on for the isearch context, off for all other contexts.
813 Turning this off for example for sparse trees makes them very compact,
814 but makes it harder to edit the location of the match. In such a case,
815 use the command \\[org-reveal] to show more context.
816 Instead of t, this can also be an alist specifying this option for different
817 contexts. See `org-show-hierarchy-above' for valid contexts."
818 :group
'org-reveal-location
819 :type org-context-choice
)
821 (defcustom org-show-entry-below
'((default . nil
))
822 "Non-nil means show the entry below a headline when revealing a location.
823 Org-mode often shows locations in an org-mode file which might have
824 been invisible before. When this is set, the text below the headline that is
825 exposed is also shown.
827 By default this is off for all contexts.
828 Instead of t, this can also be an alist specifying this option for different
829 contexts. See `org-show-hierarchy-above' for valid contexts."
830 :group
'org-reveal-location
831 :type org-context-choice
)
833 (defcustom org-indirect-buffer-display
'other-window
834 "How should indirect tree buffers be displayed?
835 This applies to indirect buffers created with the commands
836 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 current-window Display in the current window
839 other-window Just display in another window.
840 dedicated-frame Create one new frame, and re-use it each time.
841 new-frame Make a new frame each time. Note that in this case
842 previously-made indirect buffers are kept, and you need to
843 kill these buffers yourself."
844 :group
'org-structure
845 :group
'org-agenda-windows
847 (const :tag
"In current window" current-window
)
848 (const :tag
"In current frame, other window" other-window
)
849 (const :tag
"Each time a new frame" new-frame
)
850 (const :tag
"One dedicated frame" dedicated-frame
)))
852 (defcustom org-use-speed-commands nil
853 "Non-nil means activate single letter commands at beginning of a headline.
854 This may also be a function to test for appropriate locations where speed
855 commands should be active."
856 :group
'org-structure
858 (const :tag
"Never" nil
)
859 (const :tag
"At beginning of headline stars" t
)
862 (defcustom org-speed-commands-user nil
863 "Alist of additional speed commands.
864 This list will be checked before `org-speed-commands-default'
865 when the variable `org-use-speed-commands' is non-nil
866 and when the cursor is at the beginning of a headline.
867 The car if each entry is a string with a single letter, which must
868 be assigned to `self-insert-command' in the global map.
869 The cdr is either a command to be called interactively, a function
870 to be called, or a form to be evaluated.
871 An entry that is just a list with a single string will be interpreted
872 as a descriptive headline that will be added when listing the speed
873 commands in the Help buffer using the `?' speed command."
874 :group
'org-structure
875 :type
'(repeat :value
("k" . ignore
)
876 (choice :value
("k" . ignore
)
877 (list :tag
"Descriptive Headline" (string :tag
"Headline"))
878 (cons :tag
"Letter and Command"
879 (string :tag
"Command letter")
884 (defgroup org-cycle nil
885 "Options concerning visibility cycling in Org-mode."
887 :group
'org-structure
)
889 (defcustom org-cycle-skip-children-state-if-no-children t
890 "Non-nil means skip CHILDREN state in entries that don't have any."
894 (defcustom org-cycle-max-level nil
895 "Maximum level which should still be subject to visibility cycling.
896 Levels higher than this will, for cycling, be treated as text, not a headline.
897 When `org-odd-levels-only' is set, a value of N in this variable actually
898 means 2N-1 stars as the limiting headline.
899 When nil, cycle all levels.
900 Note that the limiting level of cycling is also influenced by
901 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
902 `org-inlinetask-min-level' is, cycling will be limited to levels one less
906 (const :tag
"No limit" nil
)
907 (integer :tag
"Maximum level")))
909 (defcustom org-drawers
'("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
910 "Names of drawers. Drawers are not opened by cycling on the headline above.
911 Drawers only open with a TAB on the drawer line itself. A drawer looks like
916 The drawer \"PROPERTIES\" is special for capturing properties through
919 Drawers can be defined on the per-file basis with a line like:
921 #+DRAWERS: HIDDEN STATE PROPERTIES"
922 :group
'org-structure
924 :type
'(repeat (string :tag
"Drawer Name")))
926 (defcustom org-hide-block-startup nil
927 "Non-nil means entering Org-mode will fold all blocks.
928 This can also be set in on a per-file basis with
930 #+STARTUP: hideblocks
931 #+STARTUP: showblocks"
936 (defcustom org-cycle-global-at-bob nil
937 "Cycle globally if cursor is at beginning of buffer and not at a headline.
938 This makes it possible to do global cycling without having to use S-TAB or
939 \\[universal-argument] TAB. For this special case to work, the first line
940 of the buffer must not be a headline -- it may be empty or some other text.
941 When used in this way, `org-cycle-hook' is disabled temporarily to make
942 sure the cursor stays at the beginning of the buffer. When this option is
943 nil, don't do anything special at the beginning of the buffer."
947 (defcustom org-cycle-level-after-item
/entry-creation t
948 "Non-nil means cycle entry level or item indentation in new empty entries.
950 When the cursor is at the end of an empty headline, i.e with only stars
951 and maybe a TODO keyword, TAB will then switch the entry to become a child,
952 and then all possible ancestor states, before returning to the original state.
953 This makes data entry extremely fast: M-RET to create a new headline,
954 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
956 When the cursor is at the end of an empty plain list item, one TAB will
957 make it a subitem, two or more tabs will back up to make this an item
958 higher up in the item hierarchy."
962 (defcustom org-cycle-emulate-tab t
963 "Where should `org-cycle' emulate TAB.
965 white Only in completely white lines
966 whitestart Only at the beginning of lines, before the first non-white char
967 t Everywhere except in headlines
968 exc-hl-bol Everywhere except at the start of a headline
969 If TAB is used in a place where it does not emulate TAB, the current subtree
970 visibility is cycled."
972 :type
'(choice (const :tag
"Never" nil
)
973 (const :tag
"Only in completely white lines" white
)
974 (const :tag
"Before first char in a line" whitestart
)
975 (const :tag
"Everywhere except in headlines" t
)
976 (const :tag
"Everywhere except at bol in headlines" exc-hl-bol
)
979 (defcustom org-cycle-separator-lines
2
980 "Number of empty lines needed to keep an empty line between collapsed trees.
981 If you leave an empty line between the end of a subtree and the following
982 headline, this empty line is hidden when the subtree is folded.
983 Org-mode will leave (exactly) one empty line visible if the number of
984 empty lines is equal or larger to the number given in this variable.
985 So the default 2 means at least 2 empty lines after the end of a subtree
986 are needed to produce free space between a collapsed subtree and the
989 If the number is negative, and the number of empty lines is at least -N,
990 all empty lines are shown.
992 Special case: when 0, never leave empty lines in collapsed view."
995 (put 'org-cycle-separator-lines
'safe-local-variable
'integerp
)
997 (defcustom org-pre-cycle-hook nil
998 "Hook that is run before visibility cycling is happening.
999 The function(s) in this hook must accept a single argument which indicates
1000 the new state that will be set right after running this hook. The
1001 argument is a symbol. Before a global state change, it can have the values
1002 `overview', `content', or `all'. Before a local state change, it can have
1003 the values `folded', `children', or `subtree'."
1007 (defcustom org-cycle-hook
'(org-cycle-hide-archived-subtrees
1008 org-cycle-hide-drawers
1009 org-cycle-hide-inline-tasks
1010 org-cycle-show-empty-lines
1011 org-optimize-window-after-visibility-change
)
1012 "Hook that is run after `org-cycle' has changed the buffer visibility.
1013 The function(s) in this hook must accept a single argument which indicates
1014 the new state that was set by the most recent `org-cycle' command. The
1015 argument is a symbol. After a global state change, it can have the values
1016 `overview', `contents', or `all'. After a local state change, it can have
1017 the values `folded', `children', or `subtree'."
1021 (defgroup org-edit-structure nil
1022 "Options concerning structure editing in Org-mode."
1023 :tag
"Org Edit Structure"
1024 :group
'org-structure
)
1026 (defcustom org-odd-levels-only nil
1027 "Non-nil means skip even levels and only use odd levels for the outline.
1028 This has the effect that two stars are being added/taken away in
1029 promotion/demotion commands. It also influences how levels are
1030 handled by the exporters.
1031 Changing it requires restart of `font-lock-mode' to become effective
1032 for fontification also in regions already fontified.
1033 You may also set this on a per-file basis by adding one of the following
1034 lines to the buffer:
1038 :group
'org-edit-structure
1039 :group
'org-appearance
1042 (defcustom org-adapt-indentation t
1043 "Non-nil means adapt indentation to outline node level.
1045 When this variable is set, Org assumes that you write outlines by
1046 indenting text in each node to align with the headline (after the stars).
1047 The following issues are influenced by this variable:
1049 - When this is set and the *entire* text in an entry is indented, the
1050 indentation is increased by one space in a demotion command, and
1051 decreased by one in a promotion command. If any line in the entry
1052 body starts with text at column 0, indentation is not changed at all.
1054 - Property drawers and planning information is inserted indented when
1055 this variable s set. When nil, they will not be indented.
1057 - TAB indents a line relative to context. The lines below a headline
1058 will be indented when this variable is set.
1060 Note that this is all about true indentation, by adding and removing
1061 space characters. See also `org-indent.el' which does level-dependent
1062 indentation in a virtual way, i.e. at display time in Emacs."
1063 :group
'org-edit-structure
1066 (defcustom org-special-ctrl-a
/e nil
1067 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1069 When t, `C-a' will bring back the cursor to the beginning of the
1070 headline text, i.e. after the stars and after a possible TODO
1071 keyword. In an item, this will be the position after bullet and
1072 check-box, if any. When the cursor is already at that position,
1073 another `C-a' will bring it to the beginning of the line.
1075 `C-e' will jump to the end of the headline, ignoring the presence
1076 of tags in the headline. A second `C-e' will then jump to the
1077 true end of the line, after any tags. This also means that, when
1078 this variable is non-nil, `C-e' also will never jump beyond the
1079 end of the heading of a folded section, i.e. not after the
1082 When set to the symbol `reversed', the first `C-a' or `C-e' works
1083 normally, going to the true line boundary first. Only a directly
1084 following, identical keypress will bring the cursor to the
1087 This may also be a cons cell where the behavior for `C-a' and
1088 `C-e' is set separately."
1089 :group
'org-edit-structure
1091 (const :tag
"off" nil
)
1092 (const :tag
"on: after stars/bullet and before tags first" t
)
1093 (const :tag
"reversed: true line boundary first" reversed
)
1094 (cons :tag
"Set C-a and C-e separately"
1095 (choice :tag
"Special C-a"
1096 (const :tag
"off" nil
)
1097 (const :tag
"on: after stars/bullet first" t
)
1098 (const :tag
"reversed: before stars/bullet first" reversed
))
1099 (choice :tag
"Special C-e"
1100 (const :tag
"off" nil
)
1101 (const :tag
"on: before tags first" t
)
1102 (const :tag
"reversed: after tags first" reversed
)))))
1103 (if (fboundp 'defvaralias
)
1104 (defvaralias 'org-special-ctrl-a
'org-special-ctrl-a
/e
))
1106 (defcustom org-special-ctrl-k nil
1107 "Non-nil means `C-k' will behave specially in headlines.
1108 When nil, `C-k' will call the default `kill-line' command.
1109 When t, the following will happen while the cursor is in the headline:
1111 - When the cursor is at the beginning of a headline, kill the entire
1112 line and possible the folded subtree below the line.
1113 - When in the middle of the headline text, kill the headline up to the tags.
1114 - When after the headline text, kill the tags."
1115 :group
'org-edit-structure
1118 (defcustom org-ctrl-k-protect-subtree nil
1119 "Non-nil means, do not delete a hidden subtree with C-k.
1120 When set to the symbol `error', simply throw an error when C-k is
1121 used to kill (part-of) a headline that has hidden text behind it.
1122 Any other non-nil value will result in a query to the user, if it is
1123 OK to kill that hidden subtree. When nil, kill without remorse."
1124 :group
'org-edit-structure
1127 (const :tag
"Do not protect hidden subtrees" nil
)
1128 (const :tag
"Protect hidden subtrees with a security query" t
)
1129 (const :tag
"Never kill a hidden subtree with C-k" error
)))
1131 (defcustom org-catch-invisible-edits nil
1132 "Check if in invisible region before inserting or deleting a character.
1135 nil Do not check, so just do invisible edits.
1136 error Throw an error and do nothing.
1137 show Make point visible, and do the requested edit.
1138 show-and-error Make point visible, then throw an error and abort the edit.
1139 smart Make point visible, and do insertion/deletion if it is
1140 adjacent to visible text and the change feels predictable.
1141 Never delete a previously invisible character or add in the
1142 middle or right after an invisible region. Basically, this
1143 allows insertion and backward-delete right before ellipses.
1144 FIXME: maybe in this case we should not even show?"
1145 :group
'org-edit-structure
1148 (const :tag
"Do not check" nil
)
1149 (const :tag
"Throw error when trying to edit" error
)
1150 (const :tag
"Unhide, but do not do the edit" show-and-error
)
1151 (const :tag
"Show invisible part and do the edit" show
)
1152 (const :tag
"Be smart and do the right thing" smart
)))
1154 (defcustom org-yank-folded-subtrees t
1155 "Non-nil means when yanking subtrees, fold them.
1156 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1157 it starts with a heading and all other headings in it are either children
1158 or siblings, then fold all the subtrees. However, do this only if no
1159 text after the yank would be swallowed into a folded tree by this action."
1160 :group
'org-edit-structure
1163 (defcustom org-yank-adjusted-subtrees nil
1164 "Non-nil means when yanking subtrees, adjust the level.
1165 With this setting, `org-paste-subtree' is used to insert the subtree, see
1166 this function for details."
1167 :group
'org-edit-structure
1170 (defcustom org-M-RET-may-split-line
'((default . t
))
1171 "Non-nil means M-RET will split the line at the cursor position.
1172 When nil, it will go to the end of the line before making a
1174 You may also set this option in a different way for different
1175 contexts. Valid contexts are:
1177 headline when creating a new headline
1178 item when creating a new item
1179 table in a table field
1180 default the value to be used for all contexts not explicitly
1182 :group
'org-structure
1185 (const :tag
"Always" t
)
1186 (const :tag
"Never" nil
)
1187 (repeat :greedy t
:tag
"Individual contexts"
1189 (choice :tag
"Context"
1197 (defcustom org-insert-heading-respect-content nil
1198 "Non-nil means insert new headings after the current subtree.
1199 When nil, the new heading is created directly after the current line.
1200 The commands \\[org-insert-heading-respect-content] and
1201 \\[org-insert-todo-heading-respect-content] turn this variable on
1202 for the duration of the command."
1203 :group
'org-structure
1206 (defcustom org-blank-before-new-entry
'((heading . auto
)
1207 (plain-list-item . auto
))
1208 "Should `org-insert-heading' leave a blank line before new heading/item?
1209 The value is an alist, with `heading' and `plain-list-item' as CAR,
1210 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1211 which case Org will look at the surrounding headings/items and try to
1212 make an intelligent decision whether to insert a blank line or not.
1214 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1215 set, the setting here is ignored and no empty line is inserted, to avoid
1216 breaking the list structure."
1217 :group
'org-edit-structure
1219 (cons (const heading
)
1220 (choice (const :tag
"Never" nil
)
1221 (const :tag
"Always" t
)
1222 (const :tag
"Auto" auto
)))
1223 (cons (const plain-list-item
)
1224 (choice (const :tag
"Never" nil
)
1225 (const :tag
"Always" t
)
1226 (const :tag
"Auto" auto
)))))
1228 (defcustom org-insert-heading-hook nil
1229 "Hook being run after inserting a new heading."
1230 :group
'org-edit-structure
1233 (defcustom org-enable-fixed-width-editor t
1234 "Non-nil means lines starting with \":\" are treated as fixed-width.
1235 This currently only means they are never auto-wrapped.
1236 When nil, such lines will be treated like ordinary lines.
1237 See also the QUOTE keyword."
1238 :group
'org-edit-structure
1241 (defcustom org-goto-auto-isearch t
1242 "Non-nil means typing characters in `org-goto' starts incremental search."
1243 :group
'org-edit-structure
1246 (defgroup org-sparse-trees nil
1247 "Options concerning sparse trees in Org-mode."
1248 :tag
"Org Sparse Trees"
1249 :group
'org-structure
)
1251 (defcustom org-highlight-sparse-tree-matches t
1252 "Non-nil means highlight all matches that define a sparse tree.
1253 The highlights will automatically disappear the next time the buffer is
1254 changed by an edit command."
1255 :group
'org-sparse-trees
1258 (defcustom org-remove-highlights-with-change t
1259 "Non-nil means any change to the buffer will remove temporary highlights.
1260 Such highlights are created by `org-occur' and `org-clock-display'.
1261 When nil, `C-c C-c needs to be used to get rid of the highlights.
1262 The highlights created by `org-preview-latex-fragment' always need
1263 `C-c C-c' to be removed."
1264 :group
'org-sparse-trees
1269 (defcustom org-occur-hook
'(org-first-headline-recenter)
1270 "Hook that is run after `org-occur' has constructed a sparse tree.
1271 This can be used to recenter the window to show as much of the structure
1273 :group
'org-sparse-trees
1276 (defgroup org-imenu-and-speedbar nil
1277 "Options concerning imenu and speedbar in Org-mode."
1278 :tag
"Org Imenu and Speedbar"
1279 :group
'org-structure
)
1281 (defcustom org-imenu-depth
2
1282 "The maximum level for Imenu access to Org-mode headlines.
1283 This also applied for speedbar access."
1284 :group
'org-imenu-and-speedbar
1287 (defgroup org-table nil
1288 "Options concerning tables in Org-mode."
1292 (defcustom org-enable-table-editor
'optimized
1293 "Non-nil means lines starting with \"|\" are handled by the table editor.
1294 When nil, such lines will be treated like ordinary lines.
1296 When equal to the symbol `optimized', the table editor will be optimized to
1298 - Automatic overwrite mode in front of whitespace in table fields.
1299 This makes the structure of the table stay in tact as long as the edited
1300 field does not exceed the column width.
1301 - Minimize the number of realigns. Normally, the table is aligned each time
1302 TAB or RET are pressed to move to another field. With optimization this
1303 happens only if changes to a field might have changed the column width.
1304 Optimization requires replacing the functions `self-insert-command',
1305 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1306 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1307 very good at guessing when a re-align will be necessary, but you can always
1308 force one with \\[org-ctrl-c-ctrl-c].
1310 If you would like to use the optimized version in Org-mode, but the
1311 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1313 This variable can be used to turn on and off the table editor during a session,
1314 but in order to toggle optimization, a restart is required.
1316 See also the variable `org-table-auto-blank-field'."
1319 (const :tag
"off" nil
)
1321 (const :tag
"on, optimized" optimized
)))
1323 (defcustom org-self-insert-cluster-for-undo
(or (featurep 'xemacs
)
1324 (version<= emacs-version
"24.1"))
1325 "Non-nil means cluster self-insert commands for undo when possible.
1326 If this is set, then, like in the Emacs command loop, 20 consecutive
1327 characters will be undone together.
1328 This is configurable, because there is some impact on typing performance."
1332 (defcustom org-table-tab-recognizes-table.el t
1333 "Non-nil means TAB will automatically notice a table.el table.
1334 When it sees such a table, it moves point into it and - if necessary -
1335 calls `table-recognize-table'."
1336 :group
'org-table-editing
1339 (defgroup org-link nil
1340 "Options concerning links in Org-mode."
1344 (defvar org-link-abbrev-alist-local nil
1345 "Buffer-local version of `org-link-abbrev-alist', which see.
1346 The value of this is taken from the #+LINK lines.")
1347 (make-variable-buffer-local 'org-link-abbrev-alist-local
)
1349 (defcustom org-link-abbrev-alist nil
1350 "Alist of link abbreviations.
1351 The car of each element is a string, to be replaced at the start of a link.
1352 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1353 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1355 [[linkkey:tag][description]]
1357 The 'linkkey' must be a word word, starting with a letter, followed
1358 by letters, numbers, '-' or '_'.
1360 If REPLACE is a string, the tag will simply be appended to create the link.
1361 If the string contains \"%s\", the tag will be inserted there. If the string
1362 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1363 at that point (see the function `url-hexify-string'). If the string contains
1364 the specifier \"%(my-function)\", then the custom function `my-function' will
1365 be invoked: this function takes the tag as its only argument and must return
1368 REPLACE may also be a function that will be called with the tag as the
1369 only argument to create the link, which should be returned as a string.
1371 See the manual for examples."
1375 (string :tag
"Protocol")
1377 (string :tag
"Format")
1380 (defcustom org-descriptive-links t
1381 "Non-nil means Org will display descriptive links.
1382 E.g. [[http://orgmode.org][Org website]] will be displayed as
1383 \"Org Website\", hiding the link itself and just displaying its
1384 description. When set to `nil', Org will display the full links
1387 You can interactively set the value of this variable by calling
1388 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1392 (defcustom org-link-file-path-type
'adaptive
1393 "How the path name in file links should be stored.
1396 relative Relative to the current directory, i.e. the directory of the file
1397 into which the link is being inserted.
1398 absolute Absolute path, if possible with ~ for home directory.
1399 noabbrev Absolute path, no abbreviation of home directory.
1400 adaptive Use relative path for files in the current directory and sub-
1401 directories of it. For other files, use an absolute path."
1409 (defcustom org-activate-links
'(bracket angle plain radio tag date footnote
)
1410 "Types of links that should be activated in Org-mode files.
1411 This is a list of symbols, each leading to the activation of a certain link
1412 type. In principle, it does not hurt to turn on most link types - there may
1413 be a small gain when turning off unused link types. The types are:
1415 bracket The recommended [[link][description]] or [[link]] links with hiding.
1416 angle Links in angular brackets that may contain whitespace like
1417 <bbdb:Carsten Dominik>.
1418 plain Plain links in normal text, no whitespace, like http://google.com.
1419 radio Text that is matched by a radio target, see manual for details.
1420 tag Tag settings in a headline (link to tag search).
1421 date Time stamps (link to calendar).
1422 footnote Footnote labels.
1424 Changing this variable requires a restart of Emacs to become effective."
1426 :type
'(set :greedy t
1427 (const :tag
"Double bracket links" bracket
)
1428 (const :tag
"Angular bracket links" angle
)
1429 (const :tag
"Plain text links" plain
)
1430 (const :tag
"Radio target matches" radio
)
1431 (const :tag
"Tags" tag
)
1432 (const :tag
"Timestamps" date
)
1433 (const :tag
"Footnotes" footnote
)))
1435 (defcustom org-make-link-description-function nil
1436 "Function to use for generating link descriptions from links.
1437 When nil, the link location will be used. This function must take
1438 two parameters: the first one is the link, the second one is the
1439 description generated by `org-insert-link'. The function should
1440 return the description to use."
1444 (defgroup org-link-store nil
1445 "Options concerning storing links in Org-mode."
1446 :tag
"Org Store Link"
1449 (defcustom org-url-hexify-p t
1450 "When non-nil, hexify URL when creating a link."
1453 :group
'org-link-store
)
1455 (defcustom org-email-link-description-format
"Email %c: %.30s"
1456 "Format of the description part of a link to an email or usenet message.
1457 The following %-escapes will be replaced by corresponding information:
1459 %F full \"From\" field
1460 %f name, taken from \"From\" field, address if no name
1461 %T full \"To\" field
1462 %t first name in \"To\" field, address if no name
1463 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1464 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1469 You may use normal field width specification between the % and the letter.
1470 This is for example useful to limit the length of the subject.
1472 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1473 :group
'org-link-store
1476 (defcustom org-from-is-user-regexp
1478 (when (and user-mail-address
(not (string= user-mail-address
"")))
1479 (setq r1
(concat "\\<" (regexp-quote user-mail-address
) "\\>")))
1480 (when (and user-full-name
(not (string= user-full-name
"")))
1481 (setq r2
(concat "\\<" (regexp-quote user-full-name
) "\\>")))
1482 (if (and r1 r2
) (concat r1
"\\|" r2
) (or r1 r2
)))
1483 "Regexp matched against the \"From:\" header of an email or usenet message.
1484 It should match if the message is from the user him/herself."
1485 :group
'org-link-store
1488 (defcustom org-context-in-file-links t
1489 "Non-nil means file links from `org-store-link' contain context.
1490 A search string will be added to the file name with :: as separator and
1491 used to find the context when the link is activated by the command
1492 `org-open-at-point'. When this option is t, the entire active region
1493 will be placed in the search string of the file link. If set to a
1494 positive integer, only the first n lines of context will be stored.
1496 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1497 negates this setting for the duration of the command."
1498 :group
'org-link-store
1499 :type
'(choice boolean integer
))
1501 (defcustom org-keep-stored-link-after-insertion nil
1502 "Non-nil means keep link in list for entire session.
1504 The command `org-store-link' adds a link pointing to the current
1505 location to an internal list. These links accumulate during a session.
1506 The command `org-insert-link' can be used to insert links into any
1507 Org-mode file (offering completion for all stored links). When this
1508 option is nil, every link which has been inserted once using \\[org-insert-link]
1509 will be removed from the list, to make completing the unused links
1511 :group
'org-link-store
1514 (defgroup org-link-follow nil
1515 "Options concerning following links in Org-mode."
1516 :tag
"Org Follow Link"
1519 (defcustom org-link-translation-function nil
1520 "Function to translate links with different syntax to Org syntax.
1521 This can be used to translate links created for example by the Planner
1522 or emacs-wiki packages to Org syntax.
1523 The function must accept two parameters, a TYPE containing the link
1524 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1525 which is everything after the link protocol. It should return a cons
1526 with possibly modified values of type and path.
1527 Org contains a function for this, so if you set this variable to
1528 `org-translate-link-from-planner', you should be able follow many
1529 links created by planner."
1530 :group
'org-link-follow
1533 (defcustom org-follow-link-hook nil
1534 "Hook that is run after a link has been followed."
1535 :group
'org-link-follow
1538 (defcustom org-tab-follows-link nil
1539 "Non-nil means on links TAB will follow the link.
1540 Needs to be set before org.el is loaded.
1541 This really should not be used, it does not make sense, and the
1542 implementation is bad."
1543 :group
'org-link-follow
1546 (defcustom org-return-follows-link nil
1547 "Non-nil means on links RET will follow the link."
1548 :group
'org-link-follow
1551 (defcustom org-mouse-1-follows-link
1552 (if (boundp 'mouse-1-click-follows-link
) mouse-1-click-follows-link t
)
1553 "Non-nil means mouse-1 on a link will follow the link.
1554 A longer mouse click will still set point. Does not work on XEmacs.
1555 Needs to be set before org.el is loaded."
1556 :group
'org-link-follow
1559 (defcustom org-mark-ring-length
4
1560 "Number of different positions to be recorded in the ring.
1561 Changing this requires a restart of Emacs to work correctly."
1562 :group
'org-link-follow
1565 (defcustom org-link-search-must-match-exact-headline
'query-to-create
1566 "Non-nil means internal links in Org files must exactly match a headline.
1567 When nil, the link search tries to match a phrase with all words
1568 in the search text."
1569 :group
'org-link-follow
1572 (const :tag
"Use fuzzy text search" nil
)
1573 (const :tag
"Match only exact headline" t
)
1574 (const :tag
"Match exact headline or query to create it"
1577 (defcustom org-link-frame-setup
1578 '((vm . vm-visit-folder-other-frame
)
1579 (vm-imap . vm-visit-imap-folder-other-frame
)
1580 (gnus . org-gnus-no-new-news
)
1581 (file . find-file-other-window
)
1582 (wl . wl-other-frame
))
1583 "Setup the frame configuration for following links.
1584 When following a link with Emacs, it may often be useful to display
1585 this link in another window or frame. This variable can be used to
1586 set this up for the different types of links.
1589 `vm-visit-folder-other-window'
1590 `vm-visit-folder-other-frame'
1591 For Gnus, use any of
1594 `org-gnus-no-new-news'
1595 For FILE, use any of
1597 `find-file-other-window'
1598 `find-file-other-frame'
1599 For Wanderlust use any of
1602 For the calendar, use the variable `calendar-setup'.
1603 For BBDB, it is currently only possible to display the matches in
1605 :group
'org-link-follow
1609 (const vm-visit-folder
)
1610 (const vm-visit-folder-other-window
)
1611 (const vm-visit-folder-other-frame
)))
1615 (const gnus-other-frame
)
1616 (const org-gnus-no-new-news
)))
1620 (const find-file-other-window
)
1621 (const find-file-other-frame
)))
1625 (const wl-other-frame
)))))
1627 (defcustom org-display-internal-link-with-indirect-buffer nil
1628 "Non-nil means use indirect buffer to display infile links.
1629 Activating internal links (from one location in a file to another location
1630 in the same file) normally just jumps to the location. When the link is
1631 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 another window. When this option is set, the other window actually displays
1634 an indirect buffer clone of the current buffer, to avoid any visibility
1635 changes to the current buffer."
1636 :group
'org-link-follow
1639 (defcustom org-open-non-existing-files nil
1640 "Non-nil means `org-open-file' will open non-existing files.
1641 When nil, an error will be generated.
1642 This variable applies only to external applications because they
1643 might choke on non-existing files. If the link is to a file that
1644 will be opened in Emacs, the variable is ignored."
1645 :group
'org-link-follow
1648 (defcustom org-open-directory-means-index-dot-org nil
1649 "Non-nil means a link to a directory really means to index.org.
1650 When nil, following a directory link will run dired or open a finder/explorer
1651 window on that directory."
1652 :group
'org-link-follow
1655 (defcustom org-link-mailto-program
'(browse-url "mailto:%a?subject=%s")
1656 "Function and arguments to call for following mailto links.
1657 This is a list with the first element being a Lisp function, and the
1658 remaining elements being arguments to the function. In string arguments,
1659 %a will be replaced by the address, and %s will be replaced by the subject
1660 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1661 :group
'org-link-follow
1663 (const :tag
"browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1664 (const :tag
"compose-mail" (compose-mail "%a" "%s"))
1665 (const :tag
"message-mail" (message-mail "%a" "%s"))
1666 (cons :tag
"other" (function) (repeat :tag
"argument" sexp
))))
1668 (defcustom org-confirm-shell-link-function
'yes-or-no-p
1669 "Non-nil means ask for confirmation before executing shell links.
1670 Shell links can be dangerous: just think about a link
1672 [[shell:rm -rf ~/*][Google Search]]
1674 This link would show up in your Org-mode document as \"Google Search\",
1675 but really it would remove your entire home directory.
1676 Therefore we advise against setting this variable to nil.
1677 Just change it to `y-or-n-p' if you want to confirm with a
1678 single keystroke rather than having to type \"yes\"."
1679 :group
'org-link-follow
1681 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1682 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1683 (const :tag
"no confirmation (dangerous)" nil
)))
1684 (put 'org-confirm-shell-link-function
1685 'safe-local-variable
1686 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1688 (defcustom org-confirm-shell-link-not-regexp
""
1689 "A regexp to skip confirmation for shell links."
1690 :group
'org-link-follow
1694 (defcustom org-confirm-elisp-link-function
'yes-or-no-p
1695 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1696 Elisp links can be dangerous: just think about a link
1698 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1700 This link would show up in your Org-mode document as \"Google Search\",
1701 but really it would remove your entire home directory.
1702 Therefore we advise against setting this variable to nil.
1703 Just change it to `y-or-n-p' if you want to confirm with a
1704 single keystroke rather than having to type \"yes\"."
1705 :group
'org-link-follow
1707 (const :tag
"with yes-or-no (safer)" yes-or-no-p
)
1708 (const :tag
"with y-or-n (faster)" y-or-n-p
)
1709 (const :tag
"no confirmation (dangerous)" nil
)))
1710 (put 'org-confirm-shell-link-function
1711 'safe-local-variable
1712 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
1714 (defcustom org-confirm-elisp-link-not-regexp
""
1715 "A regexp to skip confirmation for Elisp links."
1716 :group
'org-link-follow
1720 (defconst org-file-apps-defaults-gnu
1724 "Default file applications on a UNIX or GNU/Linux system.
1725 See `org-file-apps'.")
1727 (defconst org-file-apps-defaults-macosx
1730 (system .
"open %s")
1732 ("eps.gz" .
"gv %s")
1734 ("fig" .
"xfig %s"))
1735 "Default file applications on a MacOS X system.
1736 The system \"open\" is known as a default, but we use X11 applications
1737 for some files for which the OS does not have a good default.
1738 See `org-file-apps'.")
1740 (defconst org-file-apps-defaults-windowsnt
1744 (list (if (featurep 'xemacs
)
1745 'mswindows-shell-execute
1749 (list (if (featurep 'xemacs
)
1750 'mswindows-shell-execute
1753 "Default file applications on a Windows NT system.
1754 The system \"open\" is used for most files.
1755 See `org-file-apps'.")
1757 (defcustom org-file-apps
1760 ("\\.mm\\'" . default
)
1761 ("\\.x?html?\\'" . default
)
1762 ("\\.pdf\\'" . default
)
1764 "External applications for opening `file:path' items in a document.
1765 Org-mode uses system defaults for different file types, but
1766 you can use this variable to set the application for a given file
1767 extension. The entries in this list are cons cells where the car identifies
1768 files and the cdr the corresponding command. Possible values for the
1770 \"string\" A string as a file identifier can be interpreted in different
1771 ways, depending on its contents:
1773 - Alphanumeric characters only:
1774 Match links with this file extension.
1775 Example: (\"pdf\" . \"evince %s\")
1776 to open PDFs with evince.
1778 - Regular expression: Match links where the
1779 filename matches the regexp. If you want to
1780 use groups here, use shy groups.
1782 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1783 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1784 to open *.html and *.xhtml with firefox.
1786 - Regular expression which contains (non-shy) groups:
1787 Match links where the whole link, including \"::\", and
1788 anything after that, matches the regexp.
1789 In a custom command string, %1, %2, etc. are replaced with
1790 the parts of the link that were matched by the groups.
1791 For backwards compatibility, if a command string is given
1792 that does not use any of the group matches, this case is
1793 handled identically to the second one (i.e. match against
1795 In a custom lisp form, you can access the group matches with
1796 (match-string n link).
1798 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1799 to open [[file:document.pdf::5]] with evince at page 5.
1801 `directory' Matches a directory
1802 `remote' Matches a remote file, accessible through tramp or efs.
1803 Remote files most likely should be visited through Emacs
1804 because external applications cannot handle such paths.
1805 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1806 so all files Emacs knows how to handle. Using this with
1807 command `emacs' will open most files in Emacs. Beware that this
1808 will also open html files inside Emacs, unless you add
1809 (\"html\" . default) to the list as well.
1810 t Default for files not matched by any of the other options.
1811 `system' The system command to open files, like `open' on Windows
1812 and Mac OS X, and mailcap under GNU/Linux. This is the command
1813 that will be selected if you call `C-c C-o' with a double
1814 \\[universal-argument] \\[universal-argument] prefix.
1816 Possible values for the command are:
1817 `emacs' The file will be visited by the current Emacs process.
1818 `default' Use the default application for this file type, which is the
1819 association for t in the list, most likely in the system-specific
1821 This can be used to overrule an unwanted setting in the
1822 system-specific variable.
1823 `system' Use the system command for opening files, like \"open\".
1824 This command is specified by the entry whose car is `system'.
1825 Most likely, the system-specific version of this variable
1826 does define this command, but you can overrule/replace it
1828 string A command to be executed by a shell; %s will be replaced
1829 by the path to the file.
1830 sexp A Lisp form which will be evaluated. The file path will
1831 be available in the Lisp variable `file'.
1832 For more examples, see the system specific constants
1833 `org-file-apps-defaults-macosx'
1834 `org-file-apps-defaults-windowsnt'
1835 `org-file-apps-defaults-gnu'."
1836 :group
'org-link-follow
1838 (cons (choice :value
""
1839 (string :tag
"Extension")
1840 (const :tag
"System command to open files" system
)
1841 (const :tag
"Default for unrecognized files" t
)
1842 (const :tag
"Remote file" remote
)
1843 (const :tag
"Links to a directory" directory
)
1844 (const :tag
"Any files that have Emacs modes"
1847 (const :tag
"Visit with Emacs" emacs
)
1848 (const :tag
"Use default" default
)
1849 (const :tag
"Use the system command" system
)
1850 (string :tag
"Command")
1851 (sexp :tag
"Lisp form")))))
1853 (defcustom org-doi-server-url
"http://dx.doi.org/"
1854 "The URL of the DOI server."
1857 :group
'org-link-follow
)
1859 (defgroup org-refile nil
1860 "Options concerning refiling entries in Org-mode."
1864 (defcustom org-directory
"~/org"
1865 "Directory with org files.
1866 This is just a default location to look for Org files. There is no need
1867 at all to put your files into this directory. It is only used in the
1868 following situations:
1870 1. When a capture template specifies a target file that is not an
1871 absolute path. The path will then be interpreted relative to
1873 2. When a capture note is filed away in an interactive way (when exiting the
1874 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1875 with `org-directory' as the default path."
1877 :group
'org-remember
1881 (defcustom org-default-notes-file
(convert-standard-filename "~/.notes")
1882 "Default target for storing notes.
1883 Used as a fall back file for org-remember.el and org-capture.el, for
1884 templates that do not specify a target file."
1886 :group
'org-remember
1889 (const :tag
"Default from remember-data-file" nil
)
1892 (defcustom org-goto-interface
'outline
1893 "The default interface to be used for `org-goto'.
1895 outline The interface shows an outline of the relevant file
1896 and the correct heading is found by moving through
1897 the outline or by searching with incremental search.
1898 outline-path-completion Headlines in the current buffer are offered via
1899 completion. This is the interface also used by
1900 the refile command."
1903 (const :tag
"Outline" outline
)
1904 (const :tag
"Outline-path-completion" outline-path-completion
)))
1906 (defcustom org-goto-max-level
5
1907 "Maximum target level when running `org-goto' with refile interface."
1911 (defcustom org-reverse-note-order nil
1912 "Non-nil means store new notes at the beginning of a file or entry.
1913 When nil, new notes will be filed to the end of a file or entry.
1914 This can also be a list with cons cells of regular expressions that
1915 are matched against file names, and values."
1916 :group
'org-remember
1920 (const :tag
"Reverse always" t
)
1921 (const :tag
"Reverse never" nil
)
1922 (repeat :tag
"By file name regexp"
1923 (cons regexp boolean
))))
1925 (defcustom org-log-refile nil
1926 "Information to record when a task is refiled.
1928 Possible values are:
1930 nil Don't add anything
1931 time Add a time stamp to the task
1932 note Prompt for a note and add it with template `org-log-note-headings'
1934 This option can also be set with on a per-file-basis with
1936 #+STARTUP: nologrefile
1937 #+STARTUP: logrefile
1938 #+STARTUP: lognoterefile
1940 You can have local logging settings for a subtree by setting the LOGGING
1941 property to one or more of these keywords.
1943 When bulk-refiling from the agenda, the value `note' is forbidden and
1944 will temporarily be changed to `time'."
1946 :group
'org-progress
1949 (const :tag
"No logging" nil
)
1950 (const :tag
"Record timestamp" time
)
1951 (const :tag
"Record timestamp with note." note
)))
1953 (defcustom org-refile-targets nil
1954 "Targets for refiling entries with \\[org-refile].
1955 This is a list of cons cells. Each cell contains:
1956 - a specification of the files to be considered, either a list of files,
1957 or a symbol whose function or variable value will be used to retrieve
1958 a file name or a list of file names. If you use `org-agenda-files' for
1959 that, all agenda files will be scanned for targets. Nil means consider
1960 headings in the current buffer.
1961 - A specification of how to find candidate refile targets. This may be
1963 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1964 This tag has to be present in all target headlines, inheritance will
1966 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1969 headlines that are refiling targets.
1970 - a cons cell (:level . N). Any headline of level N is considered a target.
1971 Note that, when `org-odd-levels-only' is set, level corresponds to
1972 order in hierarchy, not to the number of stars.
1973 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1974 Note that, when `org-odd-levels-only' is set, level corresponds to
1975 order in hierarchy, not to the number of stars.
1977 Each element of this list generates a set of possible targets.
1978 The union of these sets is presented (with completion) to
1979 the user by `org-refile'.
1981 You can set the variable `org-refile-target-verify-function' to a function
1982 to verify each headline found by the simple criteria above.
1984 When this variable is nil, all top-level headlines in the current buffer
1985 are used, equivalent to the value `((nil . (:level . 1))'."
1989 (choice :value org-agenda-files
1990 (const :tag
"All agenda files" org-agenda-files
)
1991 (const :tag
"Current buffer" nil
)
1992 (function) (variable) (file))
1993 (choice :tag
"Identify target headline by"
1994 (cons :tag
"Specific tag" (const :value
:tag
) (string))
1995 (cons :tag
"TODO keyword" (const :value
:todo
) (string))
1996 (cons :tag
"Regular expression" (const :value
:regexp
) (regexp))
1997 (cons :tag
"Level number" (const :value
:level
) (integer))
1998 (cons :tag
"Max Level number" (const :value
:maxlevel
) (integer))))))
2000 (defcustom org-refile-target-verify-function nil
2001 "Function to verify if the headline at point should be a refile target.
2002 The function will be called without arguments, with point at the
2003 beginning of the headline. It should return t and leave point
2004 where it is if the headline is a valid target for refiling.
2006 If the target should not be selected, the function must return nil.
2007 In addition to this, it may move point to a place from where the search
2008 should be continued. For example, the function may decide that the entire
2009 subtree of the current entry should be excluded and move point to the end
2014 (defcustom org-refile-use-cache nil
2015 "Non-nil means cache refile targets to speed up the process.
2016 The cache for a particular file will be updated automatically when
2017 the buffer has been killed, or when any of the marker used for flagging
2018 refile targets no longer points at a live buffer.
2019 If you have added new entries to a buffer that might themselves be targets,
2020 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2021 find that easier, `C-u C-u C-u C-c C-w'."
2026 (defcustom org-refile-use-outline-path nil
2027 "Non-nil means provide refile targets as paths.
2028 So a level 3 headline will be available as level1/level2/level3.
2030 When the value is `file', also include the file name (without directory)
2031 into the path. In this case, you can also stop the completion after
2032 the file name, to get entries inserted as top level in the file.
2034 When `full-file-path', include the full file path."
2037 (const :tag
"Not" nil
)
2038 (const :tag
"Yes" t
)
2039 (const :tag
"Start with file name" file
)
2040 (const :tag
"Start with full file path" full-file-path
)))
2042 (defcustom org-outline-path-complete-in-steps t
2043 "Non-nil means complete the outline path in hierarchical steps.
2044 When Org-mode uses the refile interface to select an outline path
2045 \(see variable `org-refile-use-outline-path'), the completion of
2046 the path can be done is a single go, or if can be done in steps down
2047 the headline hierarchy. Going in steps is probably the best if you
2048 do not use a special completion package like `ido' or `icicles'.
2049 However, when using these packages, going in one step can be very
2050 fast, while still showing the whole path to the entry."
2054 (defcustom org-refile-allow-creating-parent-nodes nil
2055 "Non-nil means allow to create new nodes as refile targets.
2056 New nodes are then created by adding \"/new node name\" to the completion
2057 of an existing node. When the value of this variable is `confirm',
2058 new node creation must be confirmed by the user (recommended)
2059 When nil, the completion must match an existing entry.
2061 Note that, if the new heading is not seen by the criteria
2062 listed in `org-refile-targets', multiple instances of the same
2063 heading would be created by trying again to file under the new
2067 (const :tag
"Never" nil
)
2068 (const :tag
"Always" t
)
2069 (const :tag
"Prompt for confirmation" confirm
)))
2071 (defcustom org-refile-active-region-within-subtree nil
2072 "Non-nil means also refile active region within a subtree.
2074 By default `org-refile' doesn't allow refiling regions if they
2075 don't contain a set of subtrees, but it might be convenient to
2076 do so sometimes: in that case, the first line of the region is
2077 converted to a headline before refiling."
2082 (defgroup org-todo nil
2083 "Options concerning TODO items in Org-mode."
2087 (defgroup org-progress nil
2088 "Options concerning Progress logging in Org-mode."
2092 (defvar org-todo-interpretation-widgets
2093 '((:tag
"Sequence (cycling hits every state)" sequence
)
2094 (:tag
"Type (cycling directly to DONE)" type
))
2095 "The available interpretation symbols for customizing `org-todo-keywords'.
2096 Interested libraries should add to this list.")
2098 (defcustom org-todo-keywords
'((sequence "TODO" "DONE"))
2099 "List of TODO entry keyword sequences and their interpretation.
2100 \\<org-mode-map>This is a list of sequences.
2102 Each sequence starts with a symbol, either `sequence' or `type',
2103 indicating if the keywords should be interpreted as a sequence of
2104 action steps, or as different types of TODO items. The first
2105 keywords are states requiring action - these states will select a headline
2106 for inclusion into the global TODO list Org-mode produces. If one of
2107 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2108 signify that no further action is necessary. If \"|\" is not found,
2109 the last keyword is treated as the only DONE state of the sequence.
2111 The command \\[org-todo] cycles an entry through these states, and one
2112 additional state where no keyword is present. For details about this
2113 cycling, see the manual.
2115 TODO keywords and interpretation can also be set on a per-file basis with
2116 the special #+SEQ_TODO and #+TYP_TODO lines.
2118 Each keyword can optionally specify a character for fast state selection
2119 \(in combination with the variable `org-use-fast-todo-selection')
2120 and specifiers for state change logging, using the same syntax that
2121 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2122 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2123 indicates to record a time stamp each time this state is selected.
2125 Each keyword may also specify if a timestamp or a note should be
2126 recorded when entering or leaving the state, by adding additional
2127 characters in the parenthesis after the keyword. This looks like this:
2128 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2129 record only the time of the state change. With X and Y being either
2130 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2131 Y when leaving the state if and only if the *target* state does not
2132 define X. You may omit any of the fast-selection key or X or /Y,
2133 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2135 For backward compatibility, this variable may also be just a list
2136 of keywords. In this case the interpretation (sequence or type) will be
2137 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group
'org-keywords
2141 (repeat :tag
"Old syntax, just keywords"
2142 (string :tag
"Keyword"))
2143 (repeat :tag
"New syntax"
2146 :tag
"Interpretation"
2147 ;;Quick and dirty way to see
2148 ;;`org-todo-interpretations'. This takes the
2149 ;;place of item arguments
2157 org-todo-interpretation-widgets
))
2160 (string :tag
"Keyword"))))))
2162 (defvar org-todo-keywords-1 nil
2163 "All TODO and DONE keywords active in a buffer.")
2164 (make-variable-buffer-local 'org-todo-keywords-1
)
2165 (defvar org-todo-keywords-for-agenda nil
)
2166 (defvar org-done-keywords-for-agenda nil
)
2167 (defvar org-drawers-for-agenda nil
)
2168 (defvar org-todo-keyword-alist-for-agenda nil
)
2169 (defvar org-tag-alist-for-agenda nil
)
2170 (defvar org-agenda-contributing-files nil
)
2171 (defvar org-not-done-keywords nil
)
2172 (make-variable-buffer-local 'org-not-done-keywords
)
2173 (defvar org-done-keywords nil
)
2174 (make-variable-buffer-local 'org-done-keywords
)
2175 (defvar org-todo-heads nil
)
2176 (make-variable-buffer-local 'org-todo-heads
)
2177 (defvar org-todo-sets nil
)
2178 (make-variable-buffer-local 'org-todo-sets
)
2179 (defvar org-todo-log-states nil
)
2180 (make-variable-buffer-local 'org-todo-log-states
)
2181 (defvar org-todo-kwd-alist nil
)
2182 (make-variable-buffer-local 'org-todo-kwd-alist
)
2183 (defvar org-todo-key-alist nil
)
2184 (make-variable-buffer-local 'org-todo-key-alist
)
2185 (defvar org-todo-key-trigger nil
)
2186 (make-variable-buffer-local 'org-todo-key-trigger
)
2188 (defcustom org-todo-interpretation
'sequence
2189 "Controls how TODO keywords are interpreted.
2190 This variable is in principle obsolete and is only used for
2191 backward compatibility, if the interpretation of todo keywords is
2192 not given already in `org-todo-keywords'. See that variable for
2195 :group
'org-keywords
2196 :type
'(choice (const sequence
)
2199 (defcustom org-use-fast-todo-selection t
2200 "Non-nil means use the fast todo selection scheme with C-c C-t.
2201 This variable describes if and under what circumstances the cycling
2202 mechanism for TODO keywords will be replaced by a single-key, direct
2205 When nil, fast selection is never used.
2207 When the symbol `prefix', it will be used when `org-todo' is called
2208 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2209 `C-u t' in an agenda buffer.
2211 When t, fast selection is used by default. In this case, the prefix
2212 argument forces cycling instead.
2214 In all cases, the special interface is only used if access keys have
2215 actually been assigned by the user, i.e. if keywords in the configuration
2216 are followed by a letter in parenthesis, like TODO(t)."
2219 (const :tag
"Never" nil
)
2220 (const :tag
"By default" t
)
2221 (const :tag
"Only with C-u C-c C-t" prefix
)))
2223 (defcustom org-provide-todo-statistics t
2224 "Non-nil means update todo statistics after insert and toggle.
2225 ALL-HEADLINES means update todo statistics by including headlines
2226 with no TODO keyword as well, counting them as not done.
2227 A list of TODO keywords means the same, but skip keywords that are
2230 When this is set, todo statistics is updated in the parent of the
2231 current entry each time a todo state is changed."
2234 (const :tag
"Yes, only for TODO entries" t
)
2235 (const :tag
"Yes, including all entries" 'all-headlines
)
2236 (repeat :tag
"Yes, for TODOs in this list"
2237 (string :tag
"TODO keyword"))
2238 (other :tag
"No TODO statistics" nil
)))
2240 (defcustom org-hierarchical-todo-statistics t
2241 "Non-nil means TODO statistics covers just direct children.
2242 When nil, all entries in the subtree are considered.
2243 This has only an effect if `org-provide-todo-statistics' is set.
2244 To set this to nil for only a single subtree, use a COOKIE_DATA
2245 property and include the word \"recursive\" into the value."
2249 (defcustom org-after-todo-state-change-hook nil
2250 "Hook which is run after the state of a TODO item was changed.
2251 The new state (a string with a TODO keyword, or nil) is available in the
2252 Lisp variable `org-state'."
2256 (defvar org-blocker-hook nil
2257 "Hook for functions that are allowed to block a state change.
2259 Each function gets as its single argument a property list, see
2260 `org-trigger-hook' for more information about this list.
2262 If any of the functions in this hook returns nil, the state change
2265 (defvar org-trigger-hook nil
2266 "Hook for functions that are triggered by a state change.
2268 Each function gets as its single argument a property list with at least
2269 the following elements:
2271 (:type type-of-change :position pos-at-entry-start
2272 :from old-state :to new-state)
2274 Depending on the type, more properties may be present.
2276 This mechanism is currently implemented for:
2280 :type todo-state-change
2281 :from previous state (keyword as a string), or nil, or a symbol
2282 'todo' or 'done', to indicate the general type of state.
2283 :to new state, like in :from")
2285 (defcustom org-enforce-todo-dependencies nil
2286 "Non-nil means undone TODO entries will block switching the parent to DONE.
2287 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2288 be blocked if any prior sibling is not yet done.
2289 Finally, if the parent is blocked because of ordered siblings of its own,
2290 the child will also be blocked."
2291 :set
(lambda (var val
)
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-children-or-siblings-or-parent
)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-children-or-siblings-or-parent
)))
2301 (defcustom org-enforce-todo-checkbox-dependencies nil
2302 "Non-nil means unchecked boxes will block switching the parent to DONE.
2303 When this is nil, checkboxes have no influence on switching TODO states.
2304 When non-nil, you first need to check off all check boxes before the TODO
2305 entry can be switched to DONE.
2306 This variable needs to be set before org.el is loaded, and you need to
2307 restart Emacs after a change to make the change effective. The only way
2308 to change is while Emacs is running is through the customize interface."
2309 :set
(lambda (var val
)
2312 (add-hook 'org-blocker-hook
2313 'org-block-todo-from-checkboxes
)
2314 (remove-hook 'org-blocker-hook
2315 'org-block-todo-from-checkboxes
)))
2319 (defcustom org-treat-insert-todo-heading-as-state-change nil
2320 "Non-nil means inserting a TODO heading is treated as state change.
2321 So when the command \\[org-insert-todo-heading] is used, state change
2322 logging will apply if appropriate. When nil, the new TODO item will
2323 be inserted directly, and no logging will take place."
2327 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2328 "Non-nil means switching TODO states with S-cursor counts as state change.
2329 This is the default behavior. However, setting this to nil allows a
2330 convenient way to select a TODO state and bypass any logging associated
2335 (defcustom org-todo-state-tags-triggers nil
2336 "Tag changes that should be triggered by TODO state changes.
2337 This is a list. Each entry is
2339 (state-change (tag . flag) .......)
2341 State-change can be a string with a state, and empty string to indicate the
2342 state that has no TODO keyword, or it can be one of the symbols `todo'
2343 or `done', meaning any not-done or done state, respectively."
2347 (cons (choice :tag
"When changing to"
2348 (const :tag
"Not-done state" todo
)
2349 (const :tag
"Done state" done
)
2350 (string :tag
"State"))
2352 (cons :tag
"Tag action"
2354 (choice (const :tag
"Add" t
) (const :tag
"Remove" nil
)))))))
2356 (defcustom org-log-done nil
2357 "Information to record when a task moves to the DONE state.
2359 Possible values are:
2361 nil Don't add anything, just change the keyword
2362 time Add a time stamp to the task
2363 note Prompt for a note and add it with template `org-log-note-headings'
2365 This option can also be set with on a per-file-basis with
2367 #+STARTUP: nologdone
2369 #+STARTUP: lognotedone
2371 You can have local logging settings for a subtree by setting the LOGGING
2372 property to one or more of these keywords."
2374 :group
'org-progress
2376 (const :tag
"No logging" nil
)
2377 (const :tag
"Record CLOSED timestamp" time
)
2378 (const :tag
"Record CLOSED timestamp with note." note
)))
2380 ;; Normalize old uses of org-log-done.
2382 ((eq org-log-done t
) (setq org-log-done
'time
))
2383 ((and (listp org-log-done
) (memq 'done org-log-done
))
2384 (setq org-log-done
'note
)))
2386 (defcustom org-log-reschedule nil
2387 "Information to record when the scheduling date of a tasks is modified.
2389 Possible values are:
2391 nil Don't add anything, just change the date
2392 time Add a time stamp to the task
2393 note Prompt for a note and add it with template `org-log-note-headings'
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: nologreschedule
2398 #+STARTUP: logreschedule
2399 #+STARTUP: lognotereschedule"
2401 :group
'org-progress
2403 (const :tag
"No logging" nil
)
2404 (const :tag
"Record timestamp" time
)
2405 (const :tag
"Record timestamp with note." note
)))
2407 (defcustom org-log-redeadline nil
2408 "Information to record when the deadline date of a tasks is modified.
2410 Possible values are:
2412 nil Don't add anything, just change the date
2413 time Add a time stamp to the task
2414 note Prompt for a note and add it with template `org-log-note-headings'
2416 This option can also be set with on a per-file-basis with
2418 #+STARTUP: nologredeadline
2419 #+STARTUP: logredeadline
2420 #+STARTUP: lognoteredeadline
2422 You can have local logging settings for a subtree by setting the LOGGING
2423 property to one or more of these keywords."
2425 :group
'org-progress
2427 (const :tag
"No logging" nil
)
2428 (const :tag
"Record timestamp" time
)
2429 (const :tag
"Record timestamp with note." note
)))
2431 (defcustom org-log-note-clock-out nil
2432 "Non-nil means record a note when clocking out of an item.
2433 This can also be configured on a per-file basis by adding one of
2434 the following lines anywhere in the buffer:
2436 #+STARTUP: lognoteclock-out
2437 #+STARTUP: nolognoteclock-out"
2439 :group
'org-progress
2442 (defcustom org-log-done-with-time t
2443 "Non-nil means the CLOSED time stamp will contain date and time.
2444 When nil, only the date will be recorded."
2445 :group
'org-progress
2448 (defcustom org-log-note-headings
2449 '((done .
"CLOSING NOTE %t")
2450 (state .
"State %-12s from %-12S %t")
2451 (note .
"Note taken on %t")
2452 (reschedule .
"Rescheduled from %S on %t")
2453 (delschedule .
"Not scheduled, was %S on %t")
2454 (redeadline .
"New deadline from %S on %t")
2455 (deldeadline .
"Removed deadline, was %S on %t")
2456 (refile .
"Refiled on %t")
2458 "Headings for notes added to entries.
2459 The value is an alist, with the car being a symbol indicating the note
2460 context, and the cdr is the heading to be used. The heading may also be the
2462 %t in the heading will be replaced by a time stamp.
2463 %T will be an active time stamp instead the default inactive one
2464 %d will be replaced by a short-format time stamp.
2465 %D will be replaced by an active short-format time stamp.
2466 %s will be replaced by the new TODO state, in double quotes.
2467 %S will be replaced by the old TODO state, in double quotes.
2468 %u will be replaced by the user name.
2469 %U will be replaced by the full user name.
2471 In fact, it is not a good idea to change the `state' entry, because
2472 agenda log mode depends on the format of these entries."
2474 :group
'org-progress
2475 :type
'(list :greedy t
2476 (cons (const :tag
"Heading when closing an item" done
) string
)
2478 "Heading when changing todo state (todo sequence only)"
2480 (cons (const :tag
"Heading when just taking a note" note
) string
)
2481 (cons (const :tag
"Heading when clocking out" clock-out
) string
)
2482 (cons (const :tag
"Heading when an item is no longer scheduled" delschedule
) string
)
2483 (cons (const :tag
"Heading when rescheduling" reschedule
) string
)
2484 (cons (const :tag
"Heading when changing deadline" redeadline
) string
)
2485 (cons (const :tag
"Heading when deleting a deadline" deldeadline
) string
)
2486 (cons (const :tag
"Heading when refiling" refile
) string
)))
2488 (unless (assq 'note org-log-note-headings
)
2489 (push '(note .
"%t") org-log-note-headings
))
2491 (defcustom org-log-into-drawer nil
2492 "Non-nil means insert state change notes and time stamps into a drawer.
2493 When nil, state changes notes will be inserted after the headline and
2494 any scheduling and clock lines, but not inside a drawer.
2496 The value of this variable should be the name of the drawer to use.
2497 LOGBOOK is proposed as the default drawer for this purpose, you can
2498 also set this to a string to define the drawer of your choice.
2500 A value of t is also allowed, representing \"LOGBOOK\".
2502 If this variable is set, `org-log-state-notes-insert-after-drawers'
2505 You can set the property LOG_INTO_DRAWER to overrule this setting for
2508 :group
'org-progress
2510 (const :tag
"Not into a drawer" nil
)
2511 (const :tag
"LOGBOOK" t
)
2512 (string :tag
"Other")))
2514 (if (fboundp 'defvaralias
)
2515 (defvaralias 'org-log-state-notes-into-drawer
'org-log-into-drawer
))
2517 (defun org-log-into-drawer ()
2518 "Return the value of `org-log-into-drawer', but let properties overrule.
2519 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2520 used instead of the default value."
2521 (let ((p (org-entry-get nil
"LOG_INTO_DRAWER" 'inherit
)))
2523 ((or (not p
) (equal p
"nil")) org-log-into-drawer
)
2524 ((equal p
"t") "LOGBOOK")
2527 (defcustom org-log-state-notes-insert-after-drawers nil
2528 "Non-nil means insert state change notes after any drawers in entry.
2529 Only the drawers that *immediately* follow the headline and the
2530 deadline/scheduled line are skipped.
2531 When nil, insert notes right after the heading and perhaps the line
2532 with deadline/scheduling if present.
2534 This variable will have no effect if `org-log-into-drawer' is
2537 :group
'org-progress
2540 (defcustom org-log-states-order-reversed t
2541 "Non-nil means the latest state note will be directly after heading.
2542 When nil, the state change notes will be ordered according to time."
2544 :group
'org-progress
2547 (defcustom org-todo-repeat-to-state nil
2548 "The TODO state to which a repeater should return the repeating task.
2549 By default this is the first task in a TODO sequence, or the previous state
2550 in a TODO_TYP set. But you can specify another task here.
2551 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2554 :type
'(choice (const :tag
"Head of sequence" nil
)
2555 (string :tag
"Specific state")))
2557 (defcustom org-log-repeat
'time
2558 "Non-nil means record moving through the DONE state when triggering repeat.
2559 An auto-repeating task is immediately switched back to TODO when
2560 marked DONE. If you are not logging state changes (by adding \"@\"
2561 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2562 record a closing note, there will be no record of the task moving
2563 through DONE. This variable forces taking a note anyway.
2565 nil Don't force a record
2566 time Record a time stamp
2567 note Prompt for a note and add it with template `org-log-note-headings'
2569 This option can also be set with on a per-file-basis with
2571 #+STARTUP: nologrepeat
2572 #+STARTUP: logrepeat
2573 #+STARTUP: lognoterepeat
2575 You can have local logging settings for a subtree by setting the LOGGING
2576 property to one or more of these keywords."
2578 :group
'org-progress
2580 (const :tag
"Don't force a record" nil
)
2581 (const :tag
"Force recording the DONE state" time
)
2582 (const :tag
"Force recording a note with the DONE state" note
)))
2585 (defgroup org-priorities nil
2586 "Priorities in Org-mode."
2587 :tag
"Org Priorities"
2590 (defcustom org-enable-priority-commands t
2591 "Non-nil means priority commands are active.
2592 When nil, these commands will be disabled, so that you never accidentally
2594 :group
'org-priorities
2597 (defcustom org-highest-priority ?A
2598 "The highest priority of TODO items. A character like ?A, ?B etc.
2599 Must have a smaller ASCII number than `org-lowest-priority'."
2600 :group
'org-priorities
2603 (defcustom org-lowest-priority ?C
2604 "The lowest priority of TODO items. A character like ?A, ?B etc.
2605 Must have a larger ASCII number than `org-highest-priority'."
2606 :group
'org-priorities
2609 (defcustom org-default-priority ?B
2610 "The default priority of TODO items.
2611 This is the priority an item gets if no explicit priority is given.
2612 When starting to cycle on an empty priority the first step in the cycle
2613 depends on `org-priority-start-cycle-with-default'. The resulting first
2614 step priority must not exceed the range from `org-highest-priority' to
2615 `org-lowest-priority' which means that `org-default-priority' has to be
2616 in this range exclusive or inclusive the range boundaries. Else the
2617 first step refuses to set the default and the second will fall back
2618 to (depending on the command used) the highest or lowest priority."
2619 :group
'org-priorities
2622 (defcustom org-priority-start-cycle-with-default t
2623 "Non-nil means start with default priority when starting to cycle.
2624 When this is nil, the first step in the cycle will be (depending on the
2625 command used) one higher or lower than the default priority.
2626 See also `org-default-priority'."
2627 :group
'org-priorities
2630 (defcustom org-get-priority-function nil
2631 "Function to extract the priority from a string.
2632 The string is normally the headline. If this is nil Org computes the
2633 priority from the priority cookie like [#A] in the headline. It returns
2634 an integer, increasing by 1000 for each priority level.
2635 The user can set a different function here, which should take a string
2636 as an argument and return the numeric priority."
2637 :group
'org-priorities
2641 (defgroup org-time nil
2642 "Options concerning time stamps and deadlines in Org-mode."
2646 (defcustom org-insert-labeled-timestamps-at-point nil
2647 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2648 When nil, these labeled time stamps are forces into the second line of an
2649 entry, just after the headline. When scheduling from the global TODO list,
2650 the time stamp will always be forced into the second line."
2654 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
2655 "Formats for `format-time-string' which are used for time stamps.
2656 It is not recommended to change this constant.")
2658 (defcustom org-time-stamp-rounding-minutes
'(0 5)
2659 "Number of minutes to round time stamps to.
2660 These are two values, the first applies when first creating a time stamp.
2661 The second applies when changing it with the commands `S-up' and `S-down'.
2662 When changing the time stamp, this means that it will change in steps
2663 of N minutes, as given by the second value.
2665 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2666 numbers should be factors of 60, so for example 5, 10, 15.
2668 When this is larger than 1, you can still force an exact time stamp by using
2669 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2670 and by using a prefix arg to `S-up/down' to specify the exact number
2671 of minutes to shift."
2673 :get
#'(lambda (var) ; Make sure both elements are there
2674 (if (integerp (default-value var
))
2675 (list (default-value var
) 5)
2676 (default-value var
)))
2678 (integer :tag
"when inserting times")
2679 (integer :tag
"when modifying times")))
2681 ;; Normalize old customizations of this variable.
2682 (when (integerp org-time-stamp-rounding-minutes
)
2683 (setq org-time-stamp-rounding-minutes
2684 (list org-time-stamp-rounding-minutes
2685 org-time-stamp-rounding-minutes
)))
2687 (defcustom org-display-custom-times nil
2688 "Non-nil means overlay custom formats over all time stamps.
2689 The formats are defined through the variable `org-time-stamp-custom-formats'.
2690 To turn this on on a per-file basis, insert anywhere in the file:
2691 #+STARTUP: customtime"
2695 (make-variable-buffer-local 'org-display-custom-times
)
2697 (defcustom org-time-stamp-custom-formats
2698 '("<%m/%d/%y %a>" .
"<%m/%d/%y %a %H:%M>") ; american
2699 "Custom formats for time stamps. See `format-time-string' for the syntax.
2700 These are overlaid over the default ISO format if the variable
2701 `org-display-custom-times' is set. Time like %H:%M should be at the
2702 end of the second format. The custom formats are also honored by export
2703 commands, if custom time display is turned on at the time of export."
2707 (defun org-time-stamp-format (&optional long inactive
)
2708 "Get the right format for a time string."
2709 (let ((f (if long
(cdr org-time-stamp-formats
)
2710 (car org-time-stamp-formats
))))
2712 (concat "[" (substring f
1 -
1) "]")
2715 (defcustom org-time-clocksum-format
"%d:%02d"
2716 "The format string used when creating CLOCKSUM lines.
2717 This is also used when org-mode generates a time duration."
2721 (defcustom org-time-clocksum-use-fractional nil
2722 "If non-nil, \\[org-clock-display] uses fractional times.
2723 org-mode generates a time duration."
2727 (defcustom org-time-clocksum-fractional-format
"%.2f"
2728 "The format string used when creating CLOCKSUM lines, or when
2729 org-mode generates a time duration."
2733 (defcustom org-deadline-warning-days
14
2734 "No. of days before expiration during which a deadline becomes active.
2735 This variable governs the display in sparse trees and in the agenda.
2736 When 0 or negative, it means use this number (the absolute value of it)
2737 even if a deadline has a different individual lead time specified.
2739 Custom commands can set this variable in the options section."
2741 :group
'org-agenda-daily
/weekly
2744 (defcustom org-read-date-prefer-future t
2745 "Non-nil means assume future for incomplete date input from user.
2746 This affects the following situations:
2747 1. The user gives a month but not a year.
2748 For example, if it is April and you enter \"feb 2\", this will be read
2749 as Feb 2, *next* year. \"May 5\", however, will be this year.
2750 2. The user gives a day, but no month.
2751 For example, if today is the 15th, and you enter \"3\", Org-mode will
2752 read this as the third of *next* month. However, if you enter \"17\",
2753 it will be considered as *this* month.
2755 If you set this variable to the symbol `time', then also the following
2758 3. If the user gives a time.
2759 If the time is before now, it will be interpreted as tomorrow.
2761 Currently none of this works for ISO week specifications.
2763 When this option is nil, the current day, month and year will always be
2766 See also `org-agenda-jump-prefer-future'."
2769 (const :tag
"Never" nil
)
2770 (const :tag
"Check month and day" t
)
2771 (const :tag
"Check month, day, and time" time
)))
2773 (defcustom org-agenda-jump-prefer-future
'org-read-date-prefer-future
2774 "Should the agenda jump command prefer the future for incomplete dates?
2775 The default is to do the same as configured in `org-read-date-prefer-future'.
2776 But you can also set a deviating value here.
2777 This may t or nil, or the symbol `org-read-date-prefer-future'."
2782 (const :tag
"Use org-read-date-prefer-future"
2783 org-read-date-prefer-future
)
2784 (const :tag
"Never" nil
)
2785 (const :tag
"Always" t
)))
2787 (defcustom org-read-date-force-compatible-dates t
2788 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2790 Depending on the system Emacs is running on, certain dates cannot
2791 be represented with the type used internally to represent time.
2792 Dates between 1970-1-1 and 2038-1-1 can always be represented
2793 correctly. Some systems allow for earlier dates, some for later,
2794 some for both. One way to find out it to insert any date into an
2795 Org buffer, putting the cursor on the year and hitting S-up and
2796 S-down to test the range.
2798 When this variable is set to t, the date/time prompt will not let
2799 you specify dates outside the 1970-2037 range, so it is certain that
2800 these dates will work in whatever version of Emacs you are
2801 running, and also that you can move a file from one Emacs implementation
2802 to another. WHenever Org is forcing the year for you, it will display
2805 When this variable is nil, Org will check if the date is
2806 representable in the specific Emacs implementation you are using.
2807 If not, it will force a year, usually the current year, and beep
2808 to remind you. Currently this setting is not recommended because
2809 the likelihood that you will open your Org files in an Emacs that
2810 has limited date range is not negligible.
2812 A workaround for this problem is to use diary sexp dates for time
2813 stamps outside of this range."
2818 (defcustom org-read-date-display-live t
2819 "Non-nil means display current interpretation of date prompt live.
2820 This display will be in an overlay, in the minibuffer."
2824 (defcustom org-read-date-popup-calendar t
2825 "Non-nil means pop up a calendar when prompting for a date.
2826 In the calendar, the date can be selected with mouse-1. However, the
2827 minibuffer will also be active, and you can simply enter the date as well.
2828 When nil, only the minibuffer will be available."
2831 (if (fboundp 'defvaralias
)
2832 (defvaralias 'org-popup-calendar-for-date-prompt
2833 'org-read-date-popup-calendar
))
2835 (defcustom org-read-date-minibuffer-setup-hook nil
2836 "Hook to be used to set up keys for the date/time interface.
2837 Add key definitions to `minibuffer-local-map', which will be a temporary
2842 (defcustom org-extend-today-until
0
2843 "The hour when your day really ends. Must be an integer.
2844 This has influence for the following applications:
2845 - When switching the agenda to \"today\". It it is still earlier than
2846 the time given here, the day recognized as TODAY is actually yesterday.
2847 - When a date is read from the user and it is still before the time given
2848 here, the current date and time will be assumed to be yesterday, 23:59.
2849 Also, timestamps inserted in capture templates follow this rule.
2851 IMPORTANT: This is a feature whose implementation is and likely will
2852 remain incomplete. Really, it is only here because past midnight seems to
2853 be the favorite working time of John Wiegley :-)"
2857 (defcustom org-use-effective-time nil
2858 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2859 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2860 \"effective time\" of any timestamps between midnight and 8am will be
2861 23:59 of the previous day."
2866 (defcustom org-use-last-clock-out-time-as-effective-time nil
2867 "When non-nil, use the last clock out time for `org-todo'.
2868 Note that this option has precedence over the combined use of
2869 `org-use-effective-time' and `org-extend-today-until'."
2874 (defcustom org-edit-timestamp-down-means-later nil
2875 "Non-nil means S-down will increase the time in a time stamp.
2876 When nil, S-up will increase."
2880 (defcustom org-calendar-follow-timestamp-change t
2881 "Non-nil means make the calendar window follow timestamp changes.
2882 When a timestamp is modified and the calendar window is visible, it will be
2883 moved to the new date."
2887 (defgroup org-tags nil
2888 "Options concerning tags in Org-mode."
2892 (defcustom org-tag-alist nil
2893 "List of tags allowed in Org-mode files.
2894 When this list is nil, Org-mode will base TAG input on what is already in the
2896 The value of this variable is an alist, the car of each entry must be a
2897 keyword as a string, the cdr may be a character that is used to select
2898 that tag through the fast-tag-selection interface.
2899 See the manual for details."
2903 (cons (string :tag
"Tag name")
2904 (character :tag
"Access char"))
2905 (list :tag
"Start radio group"
2907 (option (string :tag
"Group description")))
2908 (list :tag
"End radio group"
2910 (option (string :tag
"Group description")))
2911 (const :tag
"New line" (:newline
)))))
2913 (defcustom org-tag-persistent-alist nil
2914 "List of tags that will always appear in all Org-mode files.
2915 This is in addition to any in buffer settings or customizations
2917 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2918 The value of this variable is an alist, the car of each entry must be a
2919 keyword as a string, the cdr may be a character that is used to select
2920 that tag through the fast-tag-selection interface.
2921 See the manual for details.
2922 To disable these tags on a per-file basis, insert anywhere in the file:
2927 (cons (string :tag
"Tag name")
2928 (character :tag
"Access char"))
2929 (const :tag
"Start radio group" (:startgroup
))
2930 (const :tag
"End radio group" (:endgroup
))
2931 (const :tag
"New line" (:newline
)))))
2933 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2934 "If non-nil, always offer completion for all tags of all agenda files.
2935 Instead of customizing this variable directly, you might want to
2936 set it locally for capture buffers, because there no list of
2937 tags in that file can be created dynamically (there are none).
2939 (add-hook 'org-capture-mode-hook
2941 (set (make-local-variable
2942 'org-complete-tags-always-offer-all-agenda-tags)
2948 (defvar org-file-tags nil
2949 "List of tags that can be inherited by all entries in the file.
2950 The tags will be inherited if the variable `org-use-tag-inheritance'
2951 says they should be.
2952 This variable is populated from #+FILETAGS lines.")
2954 (defcustom org-use-fast-tag-selection
'auto
2955 "Non-nil means use fast tag selection scheme.
2956 This is a special interface to select and deselect tags with single keys.
2957 When nil, fast selection is never used.
2958 When the symbol `auto', fast selection is used if and only if selection
2959 characters for tags have been configured, either through the variable
2960 `org-tag-alist' or through a #+TAGS line in the buffer.
2961 When t, fast selection is always used and selection keys are assigned
2962 automatically if necessary."
2965 (const :tag
"Always" t
)
2966 (const :tag
"Never" nil
)
2967 (const :tag
"When selection characters are configured" 'auto
)))
2969 (defcustom org-fast-tag-selection-single-key nil
2970 "Non-nil means fast tag selection exits after first change.
2971 When nil, you have to press RET to exit it.
2972 During fast tag selection, you can toggle this flag with `C-c'.
2973 This variable can also have the value `expert'. In this case, the window
2974 displaying the tags menu is not even shown, until you press C-c again."
2977 (const :tag
"No" nil
)
2978 (const :tag
"Yes" t
)
2979 (const :tag
"Expert" expert
)))
2981 (defvar org-fast-tag-selection-include-todo nil
2982 "Non-nil means fast tags selection interface will also offer TODO states.
2983 This is an undocumented feature, you should not rely on it.")
2985 (defcustom org-tags-column
(if (featurep 'xemacs
) -
76 -
77)
2986 "The column to which tags should be indented in a headline.
2987 If this number is positive, it specifies the column. If it is negative,
2988 it means that the tags should be flushright to that column. For example,
2989 -80 works well for a normal 80 character screen.
2990 When 0, place tags directly after headline text, with only one space in
2995 (defcustom org-auto-align-tags t
2996 "Non-nil keeps tags aligned when modifying headlines.
2997 Some operations (i.e. demoting) change the length of a headline and
2998 therefore shift the tags around. With this option turned on, after
2999 each such operation the tags are again aligned to `org-tags-column'."
3003 (defcustom org-use-tag-inheritance t
3004 "Non-nil means tags in levels apply also for sublevels.
3005 When nil, only the tags directly given in a specific line apply there.
3006 This may also be a list of tags that should be inherited, or a regexp that
3007 matches tags that should be inherited. Additional control is possible
3008 with the variable `org-tags-exclude-from-inheritance' which gives an
3009 explicit list of tags to be excluded from inheritance., even if the value of
3010 `org-use-tag-inheritance' would select it for inheritance.
3012 If this option is t, a match early-on in a tree can lead to a large
3013 number of matches in the subtree when constructing the agenda or creating
3014 a sparse tree. If you only want to see the first match in a tree during
3015 a search, check out the variable `org-tags-match-list-sublevels'."
3018 (const :tag
"Not" nil
)
3019 (const :tag
"Always" t
)
3020 (repeat :tag
"Specific tags" (string :tag
"Tag"))
3021 (regexp :tag
"Tags matched by regexp")))
3023 (defcustom org-tags-exclude-from-inheritance nil
3024 "List of tags that should never be inherited.
3025 This is a way to exclude a few tags from inheritance. For way to do
3026 the opposite, to actively allow inheritance for selected tags,
3027 see the variable `org-use-tag-inheritance'."
3029 :type
'(repeat (string :tag
"Tag")))
3031 (defun org-tag-inherit-p (tag)
3032 "Check if TAG is one that should be inherited."
3034 ((member tag org-tags-exclude-from-inheritance
) nil
)
3035 ((eq org-use-tag-inheritance t
) t
)
3036 ((not org-use-tag-inheritance
) nil
)
3037 ((stringp org-use-tag-inheritance
)
3038 (string-match org-use-tag-inheritance tag
))
3039 ((listp org-use-tag-inheritance
)
3040 (member tag org-use-tag-inheritance
))
3041 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3043 (defcustom org-tags-match-list-sublevels t
3044 "Non-nil means list also sublevels of headlines matching a search.
3045 This variable applies to tags/property searches, and also to stuck
3046 projects because this search is based on a tags match as well.
3048 When set to the symbol `indented', sublevels are indented with
3051 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3052 the sublevels of a headline matching a tag search often also match
3053 the same search. Listing all of them can create very long lists.
3054 Setting this variable to nil causes subtrees of a match to be skipped.
3056 This variable is semi-obsolete and probably should always be true. It
3057 is better to limit inheritance to certain tags using the variables
3058 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3061 (const :tag
"No, don't list them" nil
)
3062 (const :tag
"Yes, do list them" t
)
3063 (const :tag
"List them, indented with leading dots" indented
)))
3065 (defcustom org-tags-sort-function nil
3066 "When set, tags are sorted using this function as a comparator."
3069 (const :tag
"No sorting" nil
)
3070 (const :tag
"Alphabetical" string
<)
3071 (const :tag
"Reverse alphabetical" string
>)
3072 (function :tag
"Custom function" nil
)))
3074 (defvar org-tags-history nil
3075 "History of minibuffer reads for tags.")
3076 (defvar org-last-tags-completion-table nil
3077 "The last used completion table for tags.")
3078 (defvar org-after-tags-change-hook nil
3079 "Hook that is run after the tags in a line have changed.")
3081 (defgroup org-properties nil
3082 "Options concerning properties in Org-mode."
3083 :tag
"Org Properties"
3086 (defcustom org-property-format
"%-10s %s"
3087 "How property key/value pairs should be formatted by `indent-line'.
3088 When `indent-line' hits a property definition, it will format the line
3089 according to this format, mainly to make sure that the values are
3090 lined-up with respect to each other."
3091 :group
'org-properties
3094 (defcustom org-properties-postprocess-alist nil
3095 "Alist of properties and functions to adjust inserted values.
3096 Elements of this alist must be of the form
3098 ([string] [function])
3100 where [string] must be a property name and [function] must be a
3101 lambda expression: this lambda expression must take one argument,
3102 the value to adjust, and return the new value as a string.
3104 For example, this element will allow the property \"Remaining\"
3105 to be updated wrt the relation between the \"Effort\" property
3106 and the clock summary:
3108 ((\"Remaining\" (lambda(value)
3109 (let ((clocksum (org-clock-sum-current-item))
3110 (effort (org-duration-string-to-minutes
3111 (org-entry-get (point) \"Effort\"))))
3112 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3113 :group
'org-properties
3115 :type
'(alist :key-type
(string :tag
"Property")
3116 :value-type
(function :tag
"Function")))
3118 (defcustom org-use-property-inheritance nil
3119 "Non-nil means properties apply also for sublevels.
3121 This setting is chiefly used during property searches. Turning it on can
3122 cause significant overhead when doing a search, which is why it is not
3125 When nil, only the properties directly given in the current entry count.
3126 When t, every property is inherited. The value may also be a list of
3127 properties that should have inheritance, or a regular expression matching
3128 properties that should be inherited.
3130 However, note that some special properties use inheritance under special
3131 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3132 and the properties ending in \"_ALL\" when they are used as descriptor
3133 for valid values of a property.
3135 Note for programmers:
3136 When querying an entry with `org-entry-get', you can control if inheritance
3137 should be used. By default, `org-entry-get' looks only at the local
3138 properties. You can request inheritance by setting the inherit argument
3139 to t (to force inheritance) or to `selective' (to respect the setting
3141 :group
'org-properties
3143 (const :tag
"Not" nil
)
3144 (const :tag
"Always" t
)
3145 (repeat :tag
"Specific properties" (string :tag
"Property"))
3146 (regexp :tag
"Properties matched by regexp")))
3148 (defun org-property-inherit-p (property)
3149 "Check if PROPERTY is one that should be inherited."
3151 ((eq org-use-property-inheritance t
) t
)
3152 ((not org-use-property-inheritance
) nil
)
3153 ((stringp org-use-property-inheritance
)
3154 (string-match org-use-property-inheritance property
))
3155 ((listp org-use-property-inheritance
)
3156 (member property org-use-property-inheritance
))
3157 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3159 (defcustom org-columns-default-format
"%25ITEM %TODO %3PRIORITY %TAGS"
3160 "The default column format, if no other format has been defined.
3161 This variable can be set on the per-file basis by inserting a line
3163 #+COLUMNS: %25ITEM ....."
3164 :group
'org-properties
3167 (defcustom org-columns-ellipses
".."
3168 "The ellipses to be used when a field in column view is truncated.
3169 When this is the empty string, as many characters as possible are shown,
3170 but then there will be no visual indication that the field has been truncated.
3171 When this is a string of length N, the last N characters of a truncated
3172 field are replaced by this string. If the column is narrower than the
3173 ellipses string, only part of the ellipses string will be shown."
3174 :group
'org-properties
3177 (defcustom org-columns-modify-value-for-display-function nil
3178 "Function that modifies values for display in column view.
3179 For example, it can be used to cut out a certain part from a time stamp.
3180 The function must take 2 arguments:
3182 column-title The title of the column (*not* the property name)
3183 value The value that should be modified.
3185 The function should return the value that should be displayed,
3186 or nil if the normal value should be used."
3187 :group
'org-properties
3190 (defcustom org-effort-property
"Effort"
3191 "The property that is being used to keep track of effort estimates.
3192 Effort estimates given in this property need to have the format H:MM."
3193 :group
'org-properties
3194 :group
'org-progress
3195 :type
'(string :tag
"Property"))
3197 (defconst org-global-properties-fixed
3198 '(("VISIBILITY_ALL" .
"folded children content all")
3199 ("CLOCK_MODELINE_TOTAL_ALL" .
"current today repeat all auto"))
3200 "List of property/value pairs that can be inherited by any entry.
3202 These are fixed values, for the preset properties. The user variable
3203 that can be used to add to this list is `org-global-properties'.
3205 The entries in this list are cons cells where the car is a property
3206 name and cdr is a string with the value. If the value represents
3207 multiple items like an \"_ALL\" property, separate the items by
3210 (defcustom org-global-properties nil
3211 "List of property/value pairs that can be inherited by any entry.
3213 This list will be combined with the constant `org-global-properties-fixed'.
3215 The entries in this list are cons cells where the car is a property
3216 name and cdr is a string with the value.
3218 You can set buffer-local values for the same purpose in the variable
3219 `org-file-properties' this by adding lines like
3221 #+PROPERTY: NAME VALUE"
3222 :group
'org-properties
3224 (cons (string :tag
"Property")
3225 (string :tag
"Value"))))
3227 (defvar org-file-properties nil
3228 "List of property/value pairs that can be inherited by any entry.
3229 Valid for the current buffer.
3230 This variable is populated from #+PROPERTY lines.")
3231 (make-variable-buffer-local 'org-file-properties
)
3233 (defgroup org-agenda nil
3234 "Options concerning agenda views in Org-mode."
3238 (defvar org-category nil
3239 "Variable used by org files to set a category for agenda display.
3240 Such files should use a file variable to set it, for example
3242 # -*- mode: org; org-category: \"ELisp\"
3244 or contain a special line
3248 If the file does not specify a category, then file's base name
3250 (make-variable-buffer-local 'org-category
)
3251 (put 'org-category
'safe-local-variable
#'(lambda (x) (or (symbolp x
) (stringp x
))))
3253 (defcustom org-agenda-files nil
3254 "The files to be used for agenda display.
3255 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3256 \\[org-remove-file]. You can also use customize to edit the list.
3258 If an entry is a directory, all files in that directory that are matched by
3259 `org-agenda-file-regexp' will be part of the file list.
3261 If the value of the variable is not a list but a single file name, then
3262 the list of agenda files is actually stored and maintained in that file, one
3263 agenda file per line. In this file paths can be given relative to
3264 `org-directory'. Tilde expansion and environment variable substitution
3268 (repeat :tag
"List of files and directories" file
)
3269 (file :tag
"Store list in a file\n" :value
"~/.agenda_files")))
3271 (defcustom org-agenda-file-regexp
"\\`[^.].*\\.org\\'"
3272 "Regular expression to match files for `org-agenda-files'.
3273 If any element in the list in that variable contains a directory instead
3274 of a normal file, all files in that directory that are matched by this
3275 regular expression will be included."
3279 (defcustom org-agenda-text-search-extra-files nil
3280 "List of extra files to be searched by text search commands.
3281 These files will be search in addition to the agenda files by the
3282 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3283 Note that these files will only be searched for text search commands,
3284 not for the other agenda views like todo lists, tag searches or the weekly
3285 agenda. This variable is intended to list notes and possibly archive files
3286 that should also be searched by these two commands.
3287 In fact, if the first element in the list is the symbol `agenda-archives',
3288 than all archive files of all agenda files will be added to the search
3291 :type
'(set :greedy t
3292 (const :tag
"Agenda Archives" agenda-archives
)
3293 (repeat :inline t
(file))))
3295 (if (fboundp 'defvaralias
)
3296 (defvaralias 'org-agenda-multi-occur-extra-files
3297 'org-agenda-text-search-extra-files
))
3299 (defcustom org-agenda-skip-unavailable-files nil
3300 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3301 A nil value means to remove them, after a query, from the list."
3305 (defcustom org-calendar-to-agenda-key
[?c
]
3306 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3307 The command `org-calendar-goto-agenda' will be bound to this key. The
3308 default is the character `c' because then `c' can be used to switch back and
3309 forth between agenda and calendar."
3313 (defcustom org-calendar-insert-diary-entry-key
[?i
]
3314 "The key to be installed in `calendar-mode-map' for adding diary entries.
3315 This option is irrelevant until `org-agenda-diary-file' has been configured
3316 to point to an Org-mode file. When that is the case, the command
3317 `org-agenda-diary-entry' will be bound to the key given here, by default
3318 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3319 if you want to continue doing this, you need to change this to a different
3324 (defcustom org-agenda-diary-file
'diary-file
3325 "File to which to add new entries with the `i' key in agenda and calendar.
3326 When this is the symbol `diary-file', the functionality in the Emacs
3327 calendar will be used to add entries to the `diary-file'. But when this
3328 points to a file, `org-agenda-diary-entry' will be used instead."
3331 (const :tag
"The standard Emacs diary file" diary-file
)
3332 (file :tag
"Special Org file diary entries")))
3334 (eval-after-load "calendar"
3336 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3337 'org-calendar-goto-agenda
)
3338 (add-hook 'calendar-mode-hook
3340 (unless (eq org-agenda-diary-file
'diary-file
)
3341 (define-key calendar-mode-map
3342 org-calendar-insert-diary-entry-key
3343 'org-agenda-diary-entry
))))))
3345 (defgroup org-latex nil
3346 "Options for embedding LaTeX code into Org-mode."
3350 (defcustom org-format-latex-options
3351 '(:foreground default
:background default
:scale
1.0
3352 :html-foreground
"Black" :html-background
"Transparent"
3353 :html-scale
1.0 :matchers
("begin" "$1" "$" "$$" "\\(" "\\["))
3354 "Options for creating images from LaTeX fragments.
3355 This is a property list with the following properties:
3356 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3357 `default' means use the foreground of the default face.
3358 `auto' means use the foreground from the text face.
3359 :background the background color, or \"Transparent\".
3360 `default' means use the background of the default face.
3361 `auto' means use the background from the text face.
3362 :scale a scaling factor for the size of the images, to get more pixels
3363 :html-foreground, :html-background, :html-scale
3364 the same numbers for HTML export.
3365 :matchers a list indicating which matchers should be used to
3366 find LaTeX fragments. Valid members of this list are:
3367 \"begin\" find environments
3368 \"$1\" find single characters surrounded by $.$
3369 \"$\" find math expressions surrounded by $...$
3370 \"$$\" find math expressions surrounded by $$....$$
3371 \"\\(\" find math expressions surrounded by \\(...\\)
3372 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3376 (defcustom org-format-latex-signal-error t
3377 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3378 When nil, just push out a message."
3383 (defcustom org-latex-to-mathml-jar-file nil
3384 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3385 Use this to specify additional executable file say a jar file.
3387 When using MathToWeb as the converter, specify the full-path to
3388 your mathtoweb.jar file."
3392 (const :tag
"None" nil
)
3393 (file :tag
"JAR file" :must-match t
)))
3395 (defcustom org-latex-to-mathml-convert-command nil
3396 "Command to convert LaTeX fragments to MathML.
3397 Replace format-specifiers in the command as noted below and use
3398 `shell-command' to convert LaTeX to MathML.
3399 %j: Executable file in fully expanded form as specified by
3400 `org-latex-to-mathml-jar-file'.
3401 %I: Input LaTeX file in fully expanded form
3402 %o: Output MathML file
3403 This command is used by `org-create-math-formula'.
3405 When using MathToWeb as the converter, set this to
3406 \"java -jar %j -unicode -force -df %o %I\"."
3410 (const :tag
"None" nil
)
3411 (string :tag
"\nShell command")))
3413 (defcustom org-latex-create-formula-image-program
'dvipng
3414 "Program to convert LaTeX fragments with.
3416 dvipng Process the LaTeX fragments to dvi file, then convert
3417 dvi files to png files using dvipng.
3418 This will also include processing of non-math environments.
3419 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3420 to convert pdf files to png files"
3424 (const :tag
"dvipng" dvipng
)
3425 (const :tag
"imagemagick" imagemagick
)))
3427 (defcustom org-latex-preview-ltxpng-directory
"ltxpng/"
3428 "Path to store latex preview images. A relative path here creates many
3429 directories relative to the processed org files paths. An absolute path
3430 puts all preview images at the same place."
3435 (defun org-format-latex-mathml-available-p ()
3436 "Return t if `org-latex-to-mathml-convert-command' is usable."
3438 (when (and (boundp 'org-latex-to-mathml-convert-command
)
3439 org-latex-to-mathml-convert-command
)
3440 (let ((executable (car (split-string
3441 org-latex-to-mathml-convert-command
))))
3442 (when (executable-find executable
)
3444 "%j" org-latex-to-mathml-convert-command
)
3445 (file-readable-p org-latex-to-mathml-jar-file
)
3448 (defcustom org-format-latex-header
"\\documentclass{article}
3449 \\usepackage[usenames]{color}
3450 \\usepackage{amsmath}
3451 \\usepackage[mathscr]{eucal}
3452 \\pagestyle{empty} % do not remove
3455 % The settings below are copied from fullpage.sty
3456 \\setlength{\\textwidth}{\\paperwidth}
3457 \\addtolength{\\textwidth}{-3cm}
3458 \\setlength{\\oddsidemargin}{1.5cm}
3459 \\addtolength{\\oddsidemargin}{-2.54cm}
3460 \\setlength{\\evensidemargin}{\\oddsidemargin}
3461 \\setlength{\\textheight}{\\paperheight}
3462 \\addtolength{\\textheight}{-\\headheight}
3463 \\addtolength{\\textheight}{-\\headsep}
3464 \\addtolength{\\textheight}{-\\footskip}
3465 \\addtolength{\\textheight}{-3cm}
3466 \\setlength{\\topmargin}{1.5cm}
3467 \\addtolength{\\topmargin}{-2.54cm}"
3468 "The document header used for processing LaTeX fragments.
3469 It is imperative that this header make sure that no page number
3470 appears on the page. The package defined in the variables
3471 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3472 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3477 (defvar org-format-latex-header-extra nil
)
3479 (defun org-set-packages-alist (var val
)
3480 "Set the packages alist and make sure it has 3 elements per entry."
3481 (set var
(mapcar (lambda (x)
3482 (if (and (consp x
) (= (length x
) 2))
3483 (list (car x
) (nth 1 x
) t
)
3487 (defun org-get-packages-alist (var)
3489 "Get the packages alist and make sure it has 3 elements per entry."
3491 (if (and (consp x
) (= (length x
) 2))
3492 (list (car x
) (nth 1 x
) t
)
3494 (default-value var
)))
3496 ;; The following variables are defined here because is it also used
3497 ;; when formatting latex fragments. Originally it was part of the
3498 ;; LaTeX exporter, which is why the name includes "export".
3499 (defcustom org-export-latex-default-packages-alist
3500 '(("AUTO" "inputenc" t
)
3504 ("" "longtable" nil
)
3516 "Alist of default packages to be inserted in the header.
3517 Change this only if one of the packages here causes an incompatibility
3518 with another package you are using.
3519 The packages in this list are needed by one part or another of Org-mode
3520 to function properly.
3522 - inputenc, fontenc: for basic font and character selection
3523 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3524 for interpreting the entities in `org-entities'. You can skip some of these
3525 packages if you don't use any of the symbols in it.
3526 - graphicx: for including images
3527 - float, wrapfig: for figure placement
3528 - longtable: for long tables
3529 - hyperref: for cross references
3531 Therefore you should not modify this variable unless you know what you
3532 are doing. The one reason to change it anyway is that you might be loading
3533 some other package that conflicts with one of the default packages.
3534 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3535 If SNIPPET-FLAG is t, the package also needs to be included when
3536 compiling LaTeX snippets into images for inclusion into HTML."
3537 :group
'org-export-latex
3538 :set
'org-set-packages-alist
3539 :get
'org-get-packages-alist
3543 (list :tag
"options/package pair"
3544 (string :tag
"options")
3545 (string :tag
"package")
3546 (boolean :tag
"Snippet"))
3547 (string :tag
"A line of LaTeX"))))
3549 (defcustom org-export-latex-packages-alist nil
3550 "Alist of packages to be inserted in every LaTeX header.
3551 These will be inserted after `org-export-latex-default-packages-alist'.
3552 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3553 SNIPPET-FLAG, when t, indicates that this package is also needed when
3554 turning LaTeX snippets into images for inclusion into HTML.
3555 Make sure that you only list packages here which:
3556 - you want in every file
3557 - do not conflict with the default packages in
3558 `org-export-latex-default-packages-alist'
3559 - do not conflict with the setup in `org-format-latex-header'."
3560 :group
'org-export-latex
3561 :set
'org-set-packages-alist
3562 :get
'org-get-packages-alist
3565 (list :tag
"options/package pair"
3566 (string :tag
"options")
3567 (string :tag
"package")
3568 (boolean :tag
"Snippet"))
3569 (string :tag
"A line of LaTeX"))))
3572 (defgroup org-appearance nil
3573 "Settings for Org-mode appearance."
3574 :tag
"Org Appearance"
3577 (defcustom org-level-color-stars-only nil
3578 "Non-nil means fontify only the stars in each headline.
3579 When nil, the entire headline is fontified.
3580 Changing it requires restart of `font-lock-mode' to become effective
3581 also in regions already fontified."
3582 :group
'org-appearance
3585 (defcustom org-hide-leading-stars nil
3586 "Non-nil means hide the first N-1 stars in a headline.
3587 This works by using the face `org-hide' for these stars. This
3588 face is white for a light background, and black for a dark
3589 background. You may have to customize the face `org-hide' to
3591 Changing it requires restart of `font-lock-mode' to become effective
3592 also in regions already fontified.
3593 You may also set this on a per-file basis by adding one of the following
3594 lines to the buffer:
3596 #+STARTUP: hidestars
3597 #+STARTUP: showstars"
3598 :group
'org-appearance
3601 (defcustom org-hidden-keywords nil
3602 "List of symbols corresponding to keywords to be hidden the org buffer.
3603 For example, a value '(title) for this list will make the document's title
3604 appear in the buffer without the initial #+TITLE: keyword."
3605 :group
'org-appearance
3607 :type
'(set (const :tag
"#+AUTHOR" author
)
3608 (const :tag
"#+DATE" date
)
3609 (const :tag
"#+EMAIL" email
)
3610 (const :tag
"#+TITLE" title
)))
3612 (defcustom org-custom-properties nil
3613 "List of properties (as strings) with a special meaning.
3614 The default use of these custom properties is to let the user
3615 hide them with `org-toggle-custom-properties-visibility'."
3616 :group
'org-properties
3617 :group
'org-appearance
3619 :type
'(repeat (string :tag
"Property Name")))
3621 (defcustom org-fontify-done-headline nil
3622 "Non-nil means change the face of a headline if it is marked DONE.
3623 Normally, only the TODO/DONE keyword indicates the state of a headline.
3624 When this is non-nil, the headline after the keyword is set to the
3625 `org-headline-done' as an additional indication."
3626 :group
'org-appearance
3629 (defcustom org-fontify-emphasized-text t
3630 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3631 Changing this variable requires a restart of Emacs to take effect."
3632 :group
'org-appearance
3635 (defcustom org-fontify-whole-heading-line nil
3636 "Non-nil means fontify the whole line for headings.
3637 This is useful when setting a background color for the
3639 :group
'org-appearance
3642 (defcustom org-highlight-latex-fragments-and-specials nil
3643 "Non-nil means fontify what is treated specially by the exporters."
3644 :group
'org-appearance
3647 (defcustom org-hide-emphasis-markers nil
3648 "Non-nil mean font-lock should hide the emphasis marker characters."
3649 :group
'org-appearance
3652 (defcustom org-pretty-entities nil
3653 "Non-nil means show entities as UTF8 characters.
3654 When nil, the \\name form remains in the buffer."
3655 :group
'org-appearance
3659 (defcustom org-pretty-entities-include-sub-superscripts t
3660 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3661 :group
'org-appearance
3665 (defvar org-emph-re nil
3666 "Regular expression for matching emphasis.
3667 After a match, the match groups contain these elements:
3668 0 The match of the full regular expression, including the characters
3669 before and after the proper match
3670 1 The character before the proper match, or empty at beginning of line
3671 2 The proper match, including the leading and trailing markers
3672 3 The leading marker like * or /, indicating the type of highlighting
3673 4 The text between the emphasis markers, not including the markers
3674 5 The character after the match, empty at the end of a line")
3675 (defvar org-verbatim-re nil
3676 "Regular expression for matching verbatim text.")
3677 (defvar org-emphasis-regexp-components
) ; defined just below
3678 (defvar org-emphasis-alist
) ; defined just below
3679 (defun org-set-emph-re (var val
)
3680 "Set variable and compute the emphasis regular expression."
3682 (when (and (boundp 'org-emphasis-alist
)
3683 (boundp 'org-emphasis-regexp-components
)
3684 org-emphasis-alist org-emphasis-regexp-components
)
3685 (let* ((e org-emphasis-regexp-components
)
3691 (body1 (concat body
"*?"))
3692 (markers (mapconcat 'car org-emphasis-alist
""))
3693 (vmarkers (mapconcat
3694 (lambda (x) (if (eq (nth 4 x
) 'verbatim
) (car x
) ""))
3695 org-emphasis-alist
"")))
3696 ;; make sure special characters appear at the right position in the class
3697 (if (string-match "\\^" markers
)
3698 (setq markers
(concat (replace-match "" t t markers
) "^")))
3699 (if (string-match "-" markers
)
3700 (setq markers
(concat (replace-match "" t t markers
) "-")))
3701 (if (string-match "\\^" vmarkers
)
3702 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "^")))
3703 (if (string-match "-" vmarkers
)
3704 (setq vmarkers
(concat (replace-match "" t t vmarkers
) "-")))
3706 (setq body1
(concat body1
"\\(?:\n" body
"*?\\)\\{0,"
3707 (int-to-string nl
) "\\}")))
3710 (concat "\\([" pre
"]\\|^\\)"
3712 "\\([" markers
"]\\)"
3720 "\\([" post
"]\\|$\\)"))
3721 (setq org-verbatim-re
3722 (concat "\\([" pre
"]\\|^\\)"
3724 "\\([" vmarkers
"]\\)"
3732 "\\([" post
"]\\|$\\)")))))
3734 (defcustom org-emphasis-regexp-components
3735 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3736 "Components used to build the regular expression for emphasis.
3737 This is a list with five entries. Terminology: In an emphasis string
3738 like \" *strong word* \", we call the initial space PREMATCH, the final
3739 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3740 and \"trong wor\" is the body. The different components in this variable
3741 specify what is allowed/forbidden in each part:
3743 pre Chars allowed as prematch. Beginning of line will be allowed too.
3744 post Chars allowed as postmatch. End of line will be allowed too.
3745 border The chars *forbidden* as border characters.
3746 body-regexp A regexp like \".\" to match a body character. Don't use
3747 non-shy groups here, and don't allow newline here.
3748 newline The maximum number of newlines allowed in an emphasis exp.
3750 Use customize to modify this, or restart Emacs after changing it."
3751 :group
'org-appearance
3752 :set
'org-set-emph-re
3754 (sexp :tag
"Allowed chars in pre ")
3755 (sexp :tag
"Allowed chars in post ")
3756 (sexp :tag
"Forbidden chars in border ")
3757 (sexp :tag
"Regexp for body ")
3758 (integer :tag
"number of newlines allowed")
3759 (option (boolean :tag
"Please ignore this button"))))
3761 (defcustom org-emphasis-alist
3762 `(("*" bold
"<b>" "</b>")
3763 ("/" italic
"<i>" "</i>")
3764 ("_" underline
"<span style=\"text-decoration:underline;\">" "</span>")
3765 ("=" org-code
"<code>" "</code>" verbatim
)
3766 ("~" org-verbatim
"<code>" "</code>" verbatim
)
3767 ("+" ,(if (featurep 'xemacs
) 'org-table
'(:strike-through t
))
3770 "Special syntax for emphasized text.
3771 Text starting and ending with a special character will be emphasized, for
3772 example *bold*, _underlined_ and /italic/. This variable sets the marker
3773 characters, the face to be used by font-lock for highlighting in Org-mode
3774 Emacs buffers, and the HTML tags to be used for this.
3775 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3776 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3777 Use customize to modify this, or restart Emacs after changing it."
3778 :group
'org-appearance
3779 :set
'org-set-emph-re
3782 (string :tag
"Marker character")
3784 (face :tag
"Font-lock-face")
3785 (plist :tag
"Face property list"))
3786 (string :tag
"HTML start tag")
3787 (string :tag
"HTML end tag")
3788 (option (const verbatim
)))))
3790 (defvar org-protecting-blocks
3791 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3792 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3793 This is needed for font-lock setup.")
3795 ;;; Miscellaneous options
3797 (defgroup org-completion nil
3798 "Completion in Org-mode."
3799 :tag
"Org Completion"
3802 (defcustom org-completion-use-ido nil
3803 "Non-nil means use ido completion wherever possible.
3804 Note that `ido-mode' must be active for this variable to be relevant.
3805 If you decide to turn this variable on, you might well want to turn off
3806 `org-outline-path-complete-in-steps'.
3807 See also `org-completion-use-iswitchb'."
3808 :group
'org-completion
3811 (defcustom org-completion-use-iswitchb nil
3812 "Non-nil means use iswitchb completion wherever possible.
3813 Note that `iswitchb-mode' must be active for this variable to be relevant.
3814 If you decide to turn this variable on, you might well want to turn off
3815 `org-outline-path-complete-in-steps'.
3816 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3817 :group
'org-completion
3820 (defcustom org-completion-fallback-command
'hippie-expand
3821 "The expansion command called by \\[pcomplete] in normal context.
3822 Normal means, no org-mode-specific context."
3823 :group
'org-completion
3826 ;;; Functions and variables from their packages
3827 ;; Declared here to avoid compiler warnings
3830 (defvar outline-mode-menu-heading
)
3831 (defvar outline-mode-menu-show
)
3832 (defvar outline-mode-menu-hide
)
3833 (defvar zmacs-regions
) ; XEmacs regions
3836 (defvar mark-active
)
3839 (declare-function calendar-absolute-from-iso
"cal-iso" (date))
3840 (declare-function calendar-forward-day
"cal-move" (arg))
3841 (declare-function calendar-goto-date
"cal-move" (date))
3842 (declare-function calendar-goto-today
"cal-move" ())
3843 (declare-function calendar-iso-from-absolute
"cal-iso" (date))
3844 (defvar calc-embedded-close-formula
)
3845 (defvar calc-embedded-open-formula
)
3846 (declare-function cdlatex-tab
"ext:cdlatex" ())
3847 (declare-function cdlatex-compute-tables
"ext:cdlatex" ())
3848 (declare-function dired-get-filename
"dired" (&optional localp no-error-if-not-filep
))
3849 (defvar font-lock-unfontify-region-function
)
3850 (declare-function iswitchb-read-buffer
"iswitchb"
3851 (prompt &optional default require-match start matches-set
))
3852 (defvar iswitchb-temp-buflist
)
3853 (declare-function org-gnus-follow-link
"org-gnus" (&optional group article
))
3854 (defvar org-agenda-tags-todo-honor-ignore-options
)
3855 (declare-function org-agenda-skip
"org-agenda" ())
3857 org-agenda-format-item
"org-agenda"
3858 (extra txt
&optional level category tags dotime noprefix remove-re habitp
))
3859 (declare-function org-agenda-new-marker
"org-agenda" (&optional pos
))
3860 (declare-function org-agenda-change-all-lines
"org-agenda"
3861 (newhead hdmarker
&optional fixface just-this
))
3862 (declare-function org-agenda-set-restriction-lock
"org-agenda" (&optional type
))
3863 (declare-function org-agenda-maybe-redo
"org-agenda" ())
3864 (declare-function org-agenda-save-markers-for-cut-and-paste
"org-agenda"
3866 (declare-function org-agenda-copy-local-variable
"org-agenda" (var))
3867 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3868 "org-agenda" (&optional end
))
3869 (declare-function org-inlinetask-remove-END-maybe
"org-inlinetask" ())
3870 (declare-function org-inlinetask-in-task-p
"org-inlinetask" ())
3871 (declare-function org-inlinetask-goto-beginning
"org-inlinetask" ())
3872 (declare-function org-inlinetask-goto-end
"org-inlinetask" ())
3873 (declare-function org-indent-mode
"org-indent" (&optional arg
))
3874 (declare-function parse-time-string
"parse-time" (string))
3875 (declare-function org-attach-reveal
"org-attach" (&optional if-exists
))
3876 (declare-function org-export-latex-fix-inputenc
"org-latex" ())
3877 (declare-function orgtbl-send-table
"org-table" (&optional maybe
))
3878 (defvar remember-data-file
)
3879 (defvar texmathp-why
)
3880 (declare-function speedbar-line-directory
"speedbar" (&optional depth
))
3881 (declare-function table--at-cell-p
"table" (position &optional object at-column
))
3883 (defvar w3m-current-url
)
3884 (defvar w3m-current-title
)
3886 (defvar org-latex-regexps
)
3888 ;;; Autoload and prepare some org modules
3890 ;; Some table stuff that needs to be defined here, because it is used
3891 ;; by the functions setting up org-mode or checking for table context.
3893 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
3894 "Detect an org-type or table-type table.")
3895 (defconst org-table-line-regexp
"^[ \t]*|"
3896 "Detect an org-type table line.")
3897 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
3898 "Detect an org-type table line.")
3899 (defconst org-table-hline-regexp
"^[ \t]*|-"
3900 "Detect an org-type table hline.")
3901 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
3902 "Detect a table-type table hline.")
3903 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
3904 "Detect the first line outside a table when searching from within it.
3905 This works for both table types.")
3907 ;; Autoload the functions in org-table.el that are needed by functions here.
3910 (org-autoload "org-table"
3911 '(org-table-begin org-table-blank-field org-table-end
)))
3914 (defun turn-on-orgtbl ()
3915 "Unconditionally turn on `orgtbl-mode'."
3916 (require 'org-table
)
3919 (defun org-at-table-p (&optional table-type
)
3920 "Return t if the cursor is inside an org-type table.
3921 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3922 (if org-enable-table-editor
3924 (beginning-of-line 1)
3925 (looking-at (if table-type org-table-any-line-regexp
3926 org-table-line-regexp
)))
3928 (defsubst org-table-p
() (org-at-table-p))
3930 (defun org-at-table.el-p
()
3931 "Return t if and only if we are at a table.el table."
3932 (and (org-at-table-p 'any
)
3934 (goto-char (org-table-begin 'any
))
3935 (looking-at org-table1-hline-regexp
))))
3936 (defun org-table-recognize-table.el
()
3937 "If there is a table.el table nearby, recognize it and move into it."
3938 (if org-table-tab-recognizes-table.el
3939 (if (org-at-table.el-p
)
3941 (beginning-of-line 1)
3942 (if (looking-at org-table-dataline-regexp
)
3944 (if (looking-at org-table1-hline-regexp
)
3946 (beginning-of-line 2)
3947 (if (looking-at org-table-any-border-regexp
)
3948 (beginning-of-line -
1)))))
3949 (if (re-search-forward "|" (org-table-end t
) t
)
3952 (if (table--at-cell-p (point))
3954 (message "recognizing table.el table...")
3955 (table-recognize-table)
3956 (message "recognizing table.el table...done")))
3957 (error "This should not happen"))
3962 (defun org-at-table-hline-p ()
3963 "Return t if the cursor is inside a hline in a table."
3964 (if org-enable-table-editor
3966 (beginning-of-line 1)
3967 (looking-at org-table-hline-regexp
))
3970 (defvar org-table-clean-did-remove-column nil
)
3972 (defun org-table-map-tables (function &optional quietly
)
3973 "Apply FUNCTION to the start of all tables in the buffer."
3977 (goto-char (point-min))
3978 (while (re-search-forward org-table-any-line-regexp nil t
)
3980 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3981 (beginning-of-line 1)
3982 (when (and (looking-at org-table-line-regexp
)
3983 ;; Exclude tables in src/example/verbatim/clocktable blocks
3984 (not (org-in-block-p '("src" "example"))))
3985 (save-excursion (funcall function
))
3986 (or (looking-at org-table-line-regexp
)
3988 (re-search-forward org-table-any-border-regexp nil
1))))
3989 (unless quietly
(message "Mapping tables: done")))
3991 ;; Declare and autoload functions from org-exp.el & Co
3993 (declare-function org-default-export-plist
"org-exp")
3994 (declare-function org-infile-export-plist
"org-exp")
3995 (declare-function org-get-current-options
"org-exp")
3997 ;; Declare and autoload functions from org-agenda.el
4000 (org-autoload "org-agenda"
4001 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4003 (declare-function org-clock-save-markers-for-cut-and-paste
"org-clock" (beg end
))
4004 (declare-function org-clock-update-mode-line
"org-clock" ())
4005 (declare-function org-resolve-clocks
"org-clock"
4006 (&optional also-non-dangling-p prompt last-valid
))
4007 (defvar org-clock-start-time
)
4008 (defvar org-clock-marker
(make-marker)
4009 "Marker recording the last clock-in.")
4010 (defvar org-clock-hd-marker
(make-marker)
4011 "Marker recording the last clock-in, but the headline position.")
4012 (defvar org-clock-heading
""
4013 "The heading of the current clock entry.")
4014 (defun org-clock-is-active ()
4015 "Return non-nil if clock is currently running.
4016 The return value is actually the clock marker."
4017 (marker-buffer org-clock-marker
))
4020 (org-autoload "org-clock" '(org-clock-remove-overlays
4021 org-clock-update-time-maybe
4022 org-clocktable-shift
)))
4024 (defun org-check-running-clock ()
4025 "Check if the current buffer contains the running clock.
4026 If yes, offer to stop it and to save the buffer with the changes."
4027 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
4028 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4031 (when (y-or-n-p "Save changed buffer?")
4034 (defun org-clocktable-try-shift (dir n
)
4035 "Check if this line starts a clock table, if yes, shift the time block."
4036 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4037 (org-clocktable-shift dir n
)))
4040 (defun org-clock-persistence-insinuate ()
4041 "Set up hooks for clock persistence."
4042 (require 'org-clock
)
4043 (add-hook 'org-mode-hook
'org-clock-load
)
4044 (add-hook 'kill-emacs-hook
'org-clock-save
))
4046 ;; Define the variable already here, to make sure we have it.
4047 (defvar org-indent-mode nil
4048 "Non-nil if Org-Indent mode is enabled.
4049 Use the command `org-indent-mode' to change this variable.")
4051 ;; Autoload archiving code
4052 ;; The stuff that is needed for cycling and tags has to be defined here.
4054 (defgroup org-archive nil
4055 "Options concerning archiving in Org-mode."
4057 :group
'org-structure
)
4059 (defcustom org-archive-location
"%s_archive::"
4060 "The location where subtrees should be archived.
4062 The value of this variable is a string, consisting of two parts,
4063 separated by a double-colon. The first part is a filename and
4064 the second part is a headline.
4066 When the filename is omitted, archiving happens in the same file.
4067 %s in the filename will be replaced by the current file
4068 name (without the directory part). Archiving to a different file
4069 is useful to keep archived entries from contributing to the
4072 The archived entries will be filed as subtrees of the specified
4073 headline. When the headline is omitted, the subtrees are simply
4074 filed away at the end of the file, as top-level entries. Also in
4075 the heading you can use %s to represent the file name, this can be
4076 useful when using the same archive for a number of different files.
4078 Here are a few examples:
4080 If the current file is Projects.org, archive in file
4081 Projects.org_archive, as top-level trees. This is the default.
4083 \"::* Archived Tasks\"
4084 Archive in the current file, under the top-level headline
4085 \"* Archived Tasks\".
4087 \"~/org/archive.org::\"
4088 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4090 \"~/org/archive.org::* From %s\"
4091 Archive in file ~/org/archive.org (absolute path), under headlines
4092 \"From FILENAME\" where file name is the current file name.
4094 \"~/org/datetree.org::datetree/* Finished Tasks\"
4095 The \"datetree/\" string is special, signifying to archive
4096 items to the datetree. Items are placed in either the CLOSED
4097 date of the item, or the current date if there is no CLOSED date.
4098 The heading will be a subentry to the current date. There doesn't
4099 need to be a heading, but there always needs to be a slash after
4100 datetree. For example, to store archived items directly in the
4101 datetree, use \"~/org/datetree.org::datetree/\".
4103 \"basement::** Finished Tasks\"
4104 Archive in file ./basement (relative path), as level 3 trees
4105 below the level 2 heading \"** Finished Tasks\".
4107 You may set this option on a per-file basis by adding to the buffer a
4110 #+ARCHIVE: basement::** Finished Tasks
4112 You may also define it locally for a subtree by setting an ARCHIVE property
4113 in the entry. If such a property is found in an entry, or anywhere up
4114 the hierarchy, it will be used."
4118 (defcustom org-archive-tag
"ARCHIVE"
4119 "The tag that marks a subtree as archived.
4120 An archived subtree does not open during visibility cycling, and does
4121 not contribute to the agenda listings.
4122 After changing this, font-lock must be restarted in the relevant buffers to
4123 get the proper fontification."
4125 :group
'org-keywords
4128 (defcustom org-agenda-skip-archived-trees t
4129 "Non-nil means the agenda will skip any items located in archived trees.
4130 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4131 variable is no longer recommended, you should leave it at the value t.
4132 Instead, use the key `v' to cycle the archives-mode in the agenda."
4134 :group
'org-agenda-skip
4137 (defcustom org-columns-skip-archived-trees t
4138 "Non-nil means ignore archived trees when creating column view."
4140 :group
'org-properties
4143 (defcustom org-cycle-open-archived-trees nil
4144 "Non-nil means `org-cycle' will open archived trees.
4145 An archived tree is a tree marked with the tag ARCHIVE.
4146 When nil, archived trees will stay folded. You can still open them with
4147 normal outline commands like `show-all', but not with the cycling commands."
4152 (defcustom org-sparse-tree-open-archived-trees nil
4153 "Non-nil means sparse tree construction shows matches in archived trees.
4154 When nil, matches in these trees are highlighted, but the trees are kept in
4157 :group
'org-sparse-trees
4160 (defcustom org-sparse-tree-default-date-type
'scheduled-or-deadline
4161 "The default date type when building a sparse tree.
4162 When this is nil, a date is a scheduled or a deadline timestamp.
4163 Otherwise, these types are allowed:
4166 active: only active timestamps (<...>)
4167 inactive: only inactive timestamps (<...)
4168 scheduled: only scheduled timestamps
4169 deadline: only deadline timestamps"
4170 :type
'(choice (const :tag
"Scheduled or deadline" 'scheduled-or-deadline
)
4171 (const :tag
"All timestamps" all
)
4172 (const :tag
"Only active timestamps" active
)
4173 (const :tag
"Only inactive timestamps" inactive
)
4174 (const :tag
"Only scheduled timestamps" scheduled
)
4175 (const :tag
"Only deadline timestamps" deadline
))
4177 :group
'org-sparse-trees
)
4179 (defun org-cycle-hide-archived-subtrees (state)
4180 "Re-hide all archived subtrees after a visibility state change."
4181 (when (and (not org-cycle-open-archived-trees
)
4182 (not (memq state
'(overview folded
))))
4184 (let* ((globalp (memq state
'(contents all
)))
4185 (beg (if globalp
(point-min) (point)))
4186 (end (if globalp
(point-max) (org-end-of-subtree t
))))
4187 (org-hide-archived-subtrees beg end
)
4189 (if (looking-at (concat ".*:" org-archive-tag
":"))
4190 (message "%s" (substitute-command-keys
4191 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4193 (defun org-force-cycle-archived ()
4194 "Cycle subtree even if it is archived."
4196 (setq this-command
'org-cycle
)
4197 (let ((org-cycle-open-archived-trees t
))
4198 (call-interactively 'org-cycle
)))
4200 (defun org-hide-archived-subtrees (beg end
)
4201 "Re-hide all archived subtrees after a visibility state change."
4203 (let* ((re (concat ":" org-archive-tag
":")))
4205 (while (re-search-forward re end t
)
4206 (when (org-at-heading-p)
4207 (org-flag-subtree t
)
4208 (org-end-of-subtree t
))))))
4210 (declare-function outline-end-of-heading
"outline" ())
4211 (declare-function outline-flag-region
"outline" (from to flag
))
4212 (defun org-flag-subtree (flag)
4214 (org-back-to-heading t
)
4215 (outline-end-of-heading)
4216 (outline-flag-region (point)
4217 (progn (org-end-of-subtree t
) (point))
4220 (defalias 'org-advertized-archive-subtree
'org-archive-subtree
)
4223 (org-autoload "org-archive"
4224 '(org-add-archive-files)))
4226 ;; Autoload Column View Code
4228 (declare-function org-columns-number-to-string
"org-colview" (n fmt
&optional printf
))
4229 (declare-function org-columns-get-format-and-top-level
"org-colview" ())
4230 (declare-function org-columns-compute
"org-colview" (property))
4232 (org-autoload (if (featurep 'xemacs
) "org-colview-xemacs" "org-colview")
4233 '(org-columns-number-to-string
4234 org-columns-get-format-and-top-level
4236 org-columns-remove-overlays
))
4240 (declare-function org-id-store-link
"org-id")
4241 (declare-function org-id-locations-load
"org-id")
4242 (declare-function org-id-locations-save
"org-id")
4243 (defvar org-id-track-globally
)
4244 (org-autoload "org-id"
4247 org-id-get-with-outline-path-completion
4248 org-id-get-with-outline-drilling
))
4250 ;;; Variables for pre-computed regular expressions, all buffer local
4252 (defvar org-drawer-regexp
"^[ \t]*:PROPERTIES:[ \t]*$"
4253 "Matches first line of a hidden block.")
4254 (make-variable-buffer-local 'org-drawer-regexp
)
4255 (defvar org-todo-regexp nil
4256 "Matches any of the TODO state keywords.")
4257 (make-variable-buffer-local 'org-todo-regexp
)
4258 (defvar org-not-done-regexp nil
4259 "Matches any of the TODO state keywords except the last one.")
4260 (make-variable-buffer-local 'org-not-done-regexp
)
4261 (defvar org-not-done-heading-regexp nil
4262 "Matches a TODO headline that is not done.")
4263 (make-variable-buffer-local 'org-not-done-regexp
)
4264 (defvar org-todo-line-regexp nil
4265 "Matches a headline and puts TODO state into group 2 if present.")
4266 (make-variable-buffer-local 'org-todo-line-regexp
)
4267 (defvar org-complex-heading-regexp nil
4268 "Matches a headline and puts everything into groups:
4270 group 2: The todo keyword, maybe
4271 group 3: Priority cookie
4272 group 4: True headline
4274 (make-variable-buffer-local 'org-complex-heading-regexp
)
4275 (defvar org-complex-heading-regexp-format nil
4276 "Printf format to make regexp to match an exact headline.
4277 This regexp will match the headline of any node which has the
4278 exact headline text that is put into the format, but may have any
4279 TODO state, priority and tags.")
4280 (make-variable-buffer-local 'org-complex-heading-regexp-format
)
4281 (defvar org-todo-line-tags-regexp nil
4282 "Matches a headline and puts TODO state into group 2 if present.
4283 Also put tags into group 4 if tags are present.")
4284 (make-variable-buffer-local 'org-todo-line-tags-regexp
)
4285 (defvar org-ds-keyword-length
12
4286 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4287 (make-variable-buffer-local 'org-ds-keyword-length
)
4288 (defvar org-deadline-regexp nil
4289 "Matches the DEADLINE keyword.")
4290 (make-variable-buffer-local 'org-deadline-regexp
)
4291 (defvar org-deadline-time-regexp nil
4292 "Matches the DEADLINE keyword together with a time stamp.")
4293 (make-variable-buffer-local 'org-deadline-time-regexp
)
4294 (defvar org-deadline-line-regexp nil
4295 "Matches the DEADLINE keyword and the rest of the line.")
4296 (make-variable-buffer-local 'org-deadline-line-regexp
)
4297 (defvar org-scheduled-regexp nil
4298 "Matches the SCHEDULED keyword.")
4299 (make-variable-buffer-local 'org-scheduled-regexp
)
4300 (defvar org-scheduled-time-regexp nil
4301 "Matches the SCHEDULED keyword together with a time stamp.")
4302 (make-variable-buffer-local 'org-scheduled-time-regexp
)
4303 (defvar org-closed-time-regexp nil
4304 "Matches the CLOSED keyword together with a time stamp.")
4305 (make-variable-buffer-local 'org-closed-time-regexp
)
4307 (defvar org-keyword-time-regexp nil
4308 "Matches any of the 4 keywords, together with the time stamp.")
4309 (make-variable-buffer-local 'org-keyword-time-regexp
)
4310 (defvar org-keyword-time-not-clock-regexp nil
4311 "Matches any of the 3 keywords, together with the time stamp.")
4312 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp
)
4313 (defvar org-maybe-keyword-time-regexp nil
4314 "Matches a timestamp, possibly preceded by a keyword.")
4315 (make-variable-buffer-local 'org-maybe-keyword-time-regexp
)
4316 (defvar org-all-time-keywords nil
4317 "List of time keywords.")
4318 (make-variable-buffer-local 'org-all-time-keywords
)
4320 (defconst org-plain-time-of-day-regexp
4323 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4326 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4328 "Regular expression to match a plain time or time range.
4329 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4330 groups carry important information:
4332 1 the first time, range or not
4333 8 the second time, if it is a range.")
4335 (defconst org-plain-time-extension-regexp
4338 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4339 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4340 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4341 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4342 groups carry important information:
4345 9 minutes of duration")
4347 (defconst org-stamp-time-of-day-regexp
4349 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4350 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4352 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4353 "Regular expression to match a timestamp time or time range.
4354 After a match, the following groups carry important information:
4356 1 date plus weekday, for back referencing to make sure both times are on the same day
4357 2 the first time, range or not
4358 4 the second time, if it is a range.")
4360 (defconst org-startup-options
4361 '(("fold" org-startup-folded t
)
4362 ("overview" org-startup-folded t
)
4363 ("nofold" org-startup-folded nil
)
4364 ("showall" org-startup-folded nil
)
4365 ("showeverything" org-startup-folded showeverything
)
4366 ("content" org-startup-folded content
)
4367 ("indent" org-startup-indented t
)
4368 ("noindent" org-startup-indented nil
)
4369 ("hidestars" org-hide-leading-stars t
)
4370 ("showstars" org-hide-leading-stars nil
)
4371 ("odd" org-odd-levels-only t
)
4372 ("oddeven" org-odd-levels-only nil
)
4373 ("align" org-startup-align-all-tables t
)
4374 ("noalign" org-startup-align-all-tables nil
)
4375 ("inlineimages" org-startup-with-inline-images t
)
4376 ("noinlineimages" org-startup-with-inline-images nil
)
4377 ("customtime" org-display-custom-times t
)
4378 ("logdone" org-log-done time
)
4379 ("lognotedone" org-log-done note
)
4380 ("nologdone" org-log-done nil
)
4381 ("lognoteclock-out" org-log-note-clock-out t
)
4382 ("nolognoteclock-out" org-log-note-clock-out nil
)
4383 ("logrepeat" org-log-repeat state
)
4384 ("lognoterepeat" org-log-repeat note
)
4385 ("nologrepeat" org-log-repeat nil
)
4386 ("logreschedule" org-log-reschedule time
)
4387 ("lognotereschedule" org-log-reschedule note
)
4388 ("nologreschedule" org-log-reschedule nil
)
4389 ("logredeadline" org-log-redeadline time
)
4390 ("lognoteredeadline" org-log-redeadline note
)
4391 ("nologredeadline" org-log-redeadline nil
)
4392 ("logrefile" org-log-refile time
)
4393 ("lognoterefile" org-log-refile note
)
4394 ("nologrefile" org-log-refile nil
)
4395 ("fninline" org-footnote-define-inline t
)
4396 ("nofninline" org-footnote-define-inline nil
)
4397 ("fnlocal" org-footnote-section nil
)
4398 ("fnauto" org-footnote-auto-label t
)
4399 ("fnprompt" org-footnote-auto-label nil
)
4400 ("fnconfirm" org-footnote-auto-label confirm
)
4401 ("fnplain" org-footnote-auto-label plain
)
4402 ("fnadjust" org-footnote-auto-adjust t
)
4403 ("nofnadjust" org-footnote-auto-adjust nil
)
4404 ("constcgs" constants-unit-system cgs
)
4405 ("constSI" constants-unit-system SI
)
4406 ("noptag" org-tag-persistent-alist nil
)
4407 ("hideblocks" org-hide-block-startup t
)
4408 ("nohideblocks" org-hide-block-startup nil
)
4409 ("beamer" org-startup-with-beamer-mode t
)
4410 ("entitiespretty" org-pretty-entities t
)
4411 ("entitiesplain" org-pretty-entities nil
))
4412 "Variable associated with STARTUP options for org-mode.
4413 Each element is a list of three items: the startup options (as written
4414 in the #+STARTUP line), the corresponding variable, and the value to set
4415 this variable to if the option is found. An optional forth element PUSH
4416 means to push this value onto the list in the variable.")
4418 (defun org-update-property-plist (key val props
)
4419 "Update PROPS with KEY and VAL."
4420 (let* ((appending (string= "+" (substring key
(- (length key
) 1))))
4421 (key (if appending
(substring key
0 (- (length key
) 1)) key
))
4422 (remainder (org-remove-if (lambda (p) (string= (car p
) key
)) props
))
4423 (previous (cdr (assoc key props
))))
4425 (cons (cons key
(if previous
(concat previous
" " val
) val
)) remainder
)
4426 (cons (cons key val
) remainder
))))
4428 (defconst org-block-regexp
4429 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4430 "Regular expression for hiding blocks.")
4431 (defconst org-heading-keyword-regexp-format
4432 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4433 "Printf format for a regexp matching an headline with some keyword.
4434 This regexp will match the headline of any node which has the
4435 exact keyword that is put into the format. The keyword isn't in
4436 any group by default, but the stars and the body are.")
4437 (defconst org-heading-keyword-maybe-regexp-format
4438 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4439 "Printf format for a regexp matching an headline, possibly with some keyword.
4440 This regexp can match any headline with the specified keyword, or
4441 without a keyword. The keyword isn't in any group by default,
4442 but the stars and the body are.")
4444 (defun org-set-regexps-and-options ()
4445 "Precompute regular expressions for current buffer."
4446 (when (derived-mode-p 'org-mode
)
4447 (org-set-local 'org-todo-kwd-alist nil
)
4448 (org-set-local 'org-todo-key-alist nil
)
4449 (org-set-local 'org-todo-key-trigger nil
)
4450 (org-set-local 'org-todo-keywords-1 nil
)
4451 (org-set-local 'org-done-keywords nil
)
4452 (org-set-local 'org-todo-heads nil
)
4453 (org-set-local 'org-todo-sets nil
)
4454 (org-set-local 'org-todo-log-states nil
)
4455 (org-set-local 'org-file-properties nil
)
4456 (org-set-local 'org-file-tags nil
)
4457 (let ((re (org-make-options-regexp
4458 '("CATEGORY" "TODO" "COLUMNS"
4459 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4460 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4462 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4464 (scripts org-use-sub-superscripts
)
4465 kwds kws0 kwsa key log value cat arch tags const links hw dws
4466 tail sep kws1 prio props ftags drawers beamer-p
4467 ext-setup-or-nil setup-contents
(start 0))
4471 (goto-char (point-min))
4472 (while (or (and ext-setup-or-nil
4473 (string-match re ext-setup-or-nil start
)
4474 (setq start
(match-end 0)))
4475 (and (setq ext-setup-or-nil nil start
0)
4476 (re-search-forward re nil t
)))
4477 (setq key
(upcase (match-string 1 ext-setup-or-nil
))
4478 value
(org-match-string-no-properties 2 ext-setup-or-nil
))
4479 (if (stringp value
) (setq value
(org-trim value
)))
4481 ((equal key
"CATEGORY")
4483 ((member key
'("SEQ_TODO" "TODO"))
4484 (push (cons 'sequence
(org-split-string value splitre
)) kwds
))
4485 ((equal key
"TYP_TODO")
4486 (push (cons 'type
(org-split-string value splitre
)) kwds
))
4487 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key
)
4488 ;; general TODO-like setup
4489 (push (cons (intern (downcase (match-string 1 key
)))
4490 (org-split-string value splitre
)) kwds
))
4492 (setq tags
(append tags
(if tags
'("\\n") nil
)
4493 (org-split-string value splitre
))))
4494 ((equal key
"COLUMNS")
4495 (org-set-local 'org-columns-default-format value
))
4497 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value
)
4498 (push (cons (match-string 1 value
)
4499 (org-trim (match-string 2 value
)))
4501 ((equal key
"PRIORITIES")
4502 (setq prio
(org-split-string value
" +")))
4503 ((equal key
"PROPERTY")
4504 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4505 (setq props
(org-update-property-plist (match-string 1 value
)
4506 (match-string 2 value
)
4508 ((equal key
"FILETAGS")
4509 (when (string-match "\\S-" value
)
4514 (mapcar (lambda (x) (org-split-string x
":"))
4515 (org-split-string value
)))))))
4516 ((equal key
"DRAWERS")
4517 (setq drawers
(delete-dups (append org-drawers
(org-split-string value splitre
)))))
4518 ((equal key
"CONSTANTS")
4519 (setq const
(append const
(org-split-string value splitre
))))
4520 ((equal key
"STARTUP")
4521 (let ((opts (org-split-string value splitre
))
4523 (while (setq l
(pop opts
))
4524 (when (setq l
(assoc l org-startup-options
))
4525 (setq var
(nth 1 l
) val
(nth 2 l
))
4527 (set (make-local-variable var
) val
)
4528 (if (not (listp (symbol-value var
)))
4529 (set (make-local-variable var
) nil
))
4530 (set (make-local-variable var
) (symbol-value var
))
4531 (add-to-list var val
))))))
4532 ((equal key
"ARCHIVE")
4534 (remove-text-properties 0 (length arch
)
4535 '(face t fontified t
) arch
))
4536 ((equal key
"LATEX_CLASS")
4537 (setq beamer-p
(equal value
"beamer")))
4538 ((equal key
"OPTIONS")
4539 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value
)
4540 (setq scripts
(read (match-string 2 value
)))))
4541 ((equal key
"SETUPFILE")
4542 (setq setup-contents
(org-file-contents
4544 (org-remove-double-quotes value
))
4546 (if (not ext-setup-or-nil
)
4547 (setq ext-setup-or-nil setup-contents start
0)
4548 (setq ext-setup-or-nil
4549 (concat (substring ext-setup-or-nil
0 start
)
4550 "\n" setup-contents
"\n"
4551 (substring ext-setup-or-nil start
)))))))
4552 ;; search for property blocks
4553 (goto-char (point-min))
4554 (while (re-search-forward org-block-regexp nil t
)
4555 (when (equal "PROPERTY" (upcase (match-string 1)))
4556 (setq value
(replace-regexp-in-string
4557 "[\n\r]" " " (match-string 4)))
4558 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value
)
4559 (setq props
(org-update-property-plist (match-string 1 value
)
4560 (match-string 2 value
)
4562 (org-set-local 'org-use-sub-superscripts scripts
)
4564 (org-set-local 'org-category
(intern cat
))
4565 (push (cons "CATEGORY" cat
) props
))
4567 (if (< (length prio
) 3) (setq prio
'("A" "C" "B")))
4568 (setq prio
(mapcar 'string-to-char prio
))
4569 (org-set-local 'org-highest-priority
(nth 0 prio
))
4570 (org-set-local 'org-lowest-priority
(nth 1 prio
))
4571 (org-set-local 'org-default-priority
(nth 2 prio
)))
4572 (and props
(org-set-local 'org-file-properties
(nreverse props
)))
4573 (and ftags
(org-set-local 'org-file-tags
4574 (mapcar 'org-add-prop-inherited ftags
)))
4575 (and drawers
(org-set-local 'org-drawers drawers
))
4576 (and arch
(org-set-local 'org-archive-location arch
))
4577 (and links
(setq org-link-abbrev-alist-local
(nreverse links
)))
4578 ;; Process the TODO keywords
4580 ;; Use the global values as if they had been given locally.
4581 (setq kwds
(default-value 'org-todo-keywords
))
4582 (if (stringp (car kwds
))
4583 (setq kwds
(list (cons org-todo-interpretation
4584 (default-value 'org-todo-keywords
)))))
4585 (setq kwds
(reverse kwds
)))
4586 (setq kwds
(nreverse kwds
))
4588 (while (setq kws
(pop kwds
))
4590 (run-hook-with-args-until-success
4591 'org-todo-setup-filter-hook kws
)
4593 (setq inter
(pop kws
) sep
(member "|" kws
)
4594 kws0
(delete "|" (copy-sequence kws
))
4599 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x
)
4601 (setq kw
(match-string 1 x
)
4602 key
(and (match-end 2) (match-string 2 x
))
4603 log
(org-extract-log-state-settings x
))
4604 (push (cons kw
(and key
(string-to-char key
))) kwsa
)
4605 (and log
(push log org-todo-log-states
))
4607 (error "Invalid TODO keyword %s" x
)))
4609 kwsa
(if kwsa
(append '((:startgroup
))
4613 dws
(if sep
(org-remove-keyword-keys (cdr sep
)) (last kws1
))
4614 tail
(list inter hw
(car dws
) (org-last dws
))))
4615 (add-to-list 'org-todo-heads hw
'append
)
4616 (push kws1 org-todo-sets
)
4617 (setq org-done-keywords
(append org-done-keywords dws nil
))
4618 (setq org-todo-key-alist
(append org-todo-key-alist kwsa
))
4619 (mapc (lambda (x) (push (cons x tail
) org-todo-kwd-alist
)) kws1
)
4620 (setq org-todo-keywords-1
(append org-todo-keywords-1 kws1 nil
)))
4621 (setq org-todo-sets
(nreverse org-todo-sets
)
4622 org-todo-kwd-alist
(nreverse org-todo-kwd-alist
)
4623 org-todo-key-trigger
(delq nil
(mapcar 'cdr org-todo-key-alist
))
4624 org-todo-key-alist
(org-assign-fast-keys org-todo-key-alist
)))
4625 ;; Process the constants
4628 (while (setq e
(pop const
))
4629 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e
)
4630 (push (cons (match-string 1 e
) (match-string 2 e
)) cst
)))
4631 (setq org-table-formula-constants-local cst
)))
4633 ;; Process the tags.
4636 (while (setq e
(pop tags
))
4638 ((equal e
"{") (push '(:startgroup
) tgs
))
4639 ((equal e
"}") (push '(:endgroup
) tgs
))
4640 ((equal e
"\\n") (push '(:newline
) tgs
))
4641 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e
)
4642 (push (cons (match-string 1 e
)
4643 (string-to-char (match-string 2 e
)))
4645 (t (push (list e
) tgs
))))
4646 (org-set-local 'org-tag-alist nil
)
4647 (while (setq e
(pop tgs
))
4648 (or (and (stringp (car e
))
4649 (assoc (car e
) org-tag-alist
))
4650 (push e org-tag-alist
)))))
4652 ;; Compute the regular expressions and other local variables.
4653 ;; Using `org-outline-regexp-bol' would complicate them much,
4654 ;; because of the fixed white space at the end of that string.
4655 (if (not org-done-keywords
)
4656 (setq org-done-keywords
(and org-todo-keywords-1
4657 (list (org-last org-todo-keywords-1
)))))
4658 (setq org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
4659 (length org-scheduled-string
)
4660 (length org-clock-string
)
4661 (length org-closed-string
)))
4663 (concat "^[ \t]*:\\("
4664 (mapconcat 'regexp-quote org-drawers
"\\|")
4666 org-not-done-keywords
4667 (org-delete-all org-done-keywords
(copy-sequence org-todo-keywords-1
))
4670 (mapconcat 'regexp-quote org-todo-keywords-1
"\\|")
4674 (mapconcat 'regexp-quote org-not-done-keywords
"\\|")
4676 org-not-done-heading-regexp
4677 (format org-heading-keyword-regexp-format org-not-done-regexp
)
4678 org-todo-line-regexp
4679 (format org-heading-keyword-maybe-regexp-format org-todo-regexp
)
4680 org-complex-heading-regexp
4681 (concat "^\\(\\*+\\)"
4682 "\\(?: +" org-todo-regexp
"\\)?"
4683 "\\(?: +\\(\\[#.\\]\\)\\)?"
4684 "\\(?: +\\(.*?\\)\\)??"
4685 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4687 org-complex-heading-regexp-format
4688 (concat "^\\(\\*+\\)"
4689 "\\(?: +" org-todo-regexp
"\\)?"
4690 "\\(?: +\\(\\[#.\\]\\)\\)?"
4692 ;; Stats cookies can be stuck to body.
4693 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4695 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4697 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4699 org-todo-line-tags-regexp
4700 (concat "^\\(\\*+\\)"
4701 "\\(?: +" org-todo-regexp
"\\)?"
4702 "\\(?: +\\(.*?\\)\\)??"
4703 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4705 org-deadline-regexp
(concat "\\<" org-deadline-string
)
4706 org-deadline-time-regexp
4707 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
4708 org-deadline-line-regexp
4709 (concat "\\<\\(" org-deadline-string
"\\).*")
4710 org-scheduled-regexp
4711 (concat "\\<" org-scheduled-string
)
4712 org-scheduled-time-regexp
4713 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>")
4714 org-closed-time-regexp
4715 (concat "\\<" org-closed-string
" *\\[\\([^]]+\\)\\]")
4716 org-keyword-time-regexp
4717 (concat "\\<\\(" org-scheduled-string
4718 "\\|" org-deadline-string
4719 "\\|" org-closed-string
4720 "\\|" org-clock-string
"\\)"
4721 " *[[<]\\([^]>]+\\)[]>]")
4722 org-keyword-time-not-clock-regexp
4723 (concat "\\<\\(" org-scheduled-string
4724 "\\|" org-deadline-string
4725 "\\|" org-closed-string
4727 " *[[<]\\([^]>]+\\)[]>]")
4728 org-maybe-keyword-time-regexp
4729 (concat "\\(\\<\\(" org-scheduled-string
4730 "\\|" org-deadline-string
4731 "\\|" org-closed-string
4732 "\\|" org-clock-string
"\\)\\)?"
4733 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4734 org-all-time-keywords
4735 (mapcar (lambda (w) (substring w
0 -
1))
4736 (list org-scheduled-string org-deadline-string
4737 org-clock-string org-closed-string
))
4739 (org-compute-latex-and-specials-regexp)
4740 (org-set-font-lock-defaults))))
4742 (defun org-file-contents (file &optional noerror
)
4743 "Return the contents of FILE, as a string."
4745 (not (file-readable-p file
)))
4748 (message "Cannot read file \"%s\"" file
)
4751 (error "Cannot read file \"%s\"" file
))
4753 (insert-file-contents file
)
4756 (defun org-extract-log-state-settings (x)
4757 "Extract the log state setting from a TODO keyword string.
4758 This will extract info from a string like \"WAIT(w@/!)\"."
4759 (let (kw key log1 log2
)
4760 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x
)
4761 (setq kw
(match-string 1 x
)
4762 key
(and (match-end 2) (match-string 2 x
))
4763 log1
(and (match-end 3) (match-string 3 x
))
4764 log2
(and (match-end 4) (match-string 4 x
)))
4767 (and log1
(if (equal log1
"!") 'time
'note
))
4768 (and log2
(if (equal log2
"!") 'time
'note
)))))))
4770 (defun org-remove-keyword-keys (list)
4771 "Remove a pair of parenthesis at the end of each string in LIST."
4773 (if (string-match "(.*)$" x
)
4774 (substring x
0 (match-beginning 0))
4778 (defun org-assign-fast-keys (alist)
4779 "Assign fast keys to a keyword-key alist.
4780 Respect keys that are already there."
4781 (let (new e
(alt ?
0))
4782 (while (setq e
(pop alist
))
4783 (if (or (memq (car e
) '(:newline
:endgroup
:startgroup
))
4784 (cdr e
)) ;; Key already assigned.
4786 (let ((clist (string-to-list (downcase (car e
))))
4787 (used (append new alist
)))
4788 (when (= (car clist
) ?
@)
4790 (while (and clist
(rassoc (car clist
) used
))
4793 (while (rassoc alt used
)
4795 (push (cons (car e
) (or (car clist
) alt
)) new
))))
4798 ;;; Some variables used in various places
4800 (defvar org-window-configuration nil
4801 "Used in various places to store a window configuration.")
4802 (defvar org-selected-window nil
4803 "Used in various places to store a window configuration.")
4804 (defvar org-finish-function nil
4805 "Function to be called when `C-c C-c' is used.
4806 This is for getting out of special buffers like capture.")
4809 ;; FIXME: Occasionally check by commenting these, to make sure
4810 ;; no other functions uses these, forgetting to let-bind them.
4811 (org-no-warnings (defvar entry
)) ;; unprefixed, from calendar.el
4812 (defvar org-last-state
)
4813 (org-no-warnings (defvar date
)) ;; unprefixed, from calendar.el
4815 ;; Defined somewhere in this file, but used before definition.
4816 (defvar org-entities
) ;; defined in org-entities.el
4817 (defvar org-struct-menu
)
4818 (defvar org-org-menu
)
4819 (defvar org-tbl-menu
)
4821 ;;;; Define the Org-mode
4823 ;; We use a before-change function to check if a table might need
4825 (defvar org-table-may-need-update t
4826 "Indicates that a table might need an update.
4827 This variable is set by `org-before-change-function'.
4828 `org-table-align' sets it back to nil.")
4829 (defun org-before-change-function (beg end
)
4830 "Every change indicates that a table might need an update."
4831 (setq org-table-may-need-update t
))
4832 (defvar org-mode-map
)
4833 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
4834 (defvar org-inhibit-startup-visibility-stuff nil
) ; Dynamically-scoped param.
4835 (defvar org-agenda-keep-modes nil
) ; Dynamically-scoped param.
4836 (defvar org-inhibit-logging nil
) ; Dynamically-scoped param.
4837 (defvar org-inhibit-blocking nil
) ; Dynamically-scoped param.
4838 (defvar org-table-buffer-is-an nil
)
4840 (defvar bidi-paragraph-direction
)
4841 (defvar buffer-face-mode-face
)
4844 (if (and (not (keymapp outline-mode-map
)) (featurep 'allout
))
4845 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
4846 (require 'noutline
"noutline" 'noerror
) ;; stock XEmacs does not have it
4848 ;; Other stuff we need.
4849 (require 'time-date
)
4850 (unless (fboundp 'time-subtract
) (defalias 'time-subtract
'subtract-time
))
4855 (require 'org-entities
)
4856 ;; (require 'org-compat) moved higher up in the file before it is first used
4857 (require 'org-faces
)
4859 (require 'org-pcomplete
)
4861 (require 'org-footnote
)
4868 (require 'ob-tangle
)
4869 (require 'ob-comint
)
4873 (define-derived-mode org-mode outline-mode
"Org"
4874 "Outline-based notes management and organizer, alias
4875 \"Carsten's outline-mode for keeping track of everything.\"
4877 Org-mode develops organizational tasks around a NOTES file which
4878 contains information about projects as plain text. Org-mode is
4879 implemented on top of outline-mode, which is ideal to keep the content
4880 of large files well structured. It supports ToDo items, deadlines and
4881 time stamps, which magically appear in the diary listing of the Emacs
4882 calendar. Tables are easily created with a built-in table editor.
4883 Plain text URL-like links connect to websites, emails (VM), Usenet
4884 messages (Gnus), BBDB entries, and any files related to the project.
4885 For printing and sharing of notes, an Org-mode file (or a part of it)
4886 can be exported as a structured ASCII or HTML file.
4888 The following commands are available:
4892 ;; Get rid of Outline menus, they are not needed
4893 ;; Need to do this here because define-derived-mode sets up
4894 ;; the keymap so late. Still, it is a waste to call this each time
4895 ;; we switch another buffer into org-mode.
4896 (if (featurep 'xemacs
)
4897 (when (boundp 'outline-mode-menu-heading
)
4898 ;; Assume this is Greg's port, it uses easymenu
4899 (easy-menu-remove outline-mode-menu-heading
)
4900 (easy-menu-remove outline-mode-menu-show
)
4901 (easy-menu-remove outline-mode-menu-hide
))
4902 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
4903 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
4904 (define-key org-mode-map
[menu-bar show
] 'undefined
))
4906 (org-load-modules-maybe)
4907 (easy-menu-add org-org-menu
)
4908 (easy-menu-add org-tbl-menu
)
4909 (org-install-agenda-files-menu)
4910 (if org-descriptive-links
(add-to-invisibility-spec '(org-link)))
4911 (add-to-invisibility-spec '(org-cwidth))
4912 (add-to-invisibility-spec '(org-hide-block . t
))
4913 (when (featurep 'xemacs
)
4914 (org-set-local 'line-move-ignore-invisible t
))
4915 (org-set-local 'outline-regexp org-outline-regexp
)
4916 (org-set-local 'outline-level
'org-outline-level
)
4917 (setq bidi-paragraph-direction
'left-to-right
)
4918 (when (and org-ellipsis
4919 (fboundp 'set-display-table-slot
) (boundp 'buffer-display-table
)
4920 (fboundp 'make-glyph-code
))
4921 (unless org-display-table
4922 (setq org-display-table
(make-display-table)))
4923 (set-display-table-slot
4926 (lambda (c) (make-glyph-code c
(and (not (stringp org-ellipsis
))
4928 (if (stringp org-ellipsis
) org-ellipsis
"..."))))
4929 (setq buffer-display-table org-display-table
))
4930 (org-set-regexps-and-options)
4931 (when (and org-tag-faces
(not org-tags-special-faces-re
))
4932 ;; tag faces set outside customize.... force initialization.
4933 (org-set-tag-faces 'org-tag-faces org-tag-faces
))
4935 (org-set-local 'calc-embedded-open-mode
"# ")
4936 (modify-syntax-entry ?
@ "w")
4937 (modify-syntax-entry ?
\" "\"")
4938 (if org-startup-truncated
(setq truncate-lines t
))
4939 (org-set-local 'font-lock-unfontify-region-function
4940 'org-unfontify-region
)
4941 ;; Activate before-change-function
4942 (org-set-local 'org-table-may-need-update t
)
4943 (org-add-hook 'before-change-functions
'org-before-change-function nil
4945 ;; Check for running clock before killing a buffer
4946 (org-add-hook 'kill-buffer-hook
'org-check-running-clock nil
'local
)
4947 ;; Initialize macros templates.
4948 (org-macro-initialize-templates)
4949 ;; Initialize radio targets.
4950 (org-update-radio-target-regexp)
4952 (org-set-local 'indent-line-function
'org-indent-line
)
4953 (org-set-local 'indent-region-function
'org-indent-region
)
4954 ;; Filling and auto-filling.
4957 (org-setup-comments-handling)
4958 ;; Beginning/end of defun
4959 (org-set-local 'beginning-of-defun-function
'org-back-to-heading
)
4960 (org-set-local 'end-of-defun-function
(lambda () (interactive) (org-end-of-subtree nil t
)))
4961 ;; Next error for sparse trees
4962 (org-set-local 'next-error-function
'org-occur-next-match
)
4963 ;; Make sure dependence stuff works reliably, even for users who set it
4965 (if org-enforce-todo-dependencies
4966 (add-hook 'org-blocker-hook
4967 'org-block-todo-from-children-or-siblings-or-parent
)
4968 (remove-hook 'org-blocker-hook
4969 'org-block-todo-from-children-or-siblings-or-parent
))
4970 (if org-enforce-todo-checkbox-dependencies
4971 (add-hook 'org-blocker-hook
4972 'org-block-todo-from-checkboxes
)
4973 (remove-hook 'org-blocker-hook
4974 'org-block-todo-from-checkboxes
))
4976 ;; Align options lines
4978 'align-mode-rules-list
4979 '((org-in-buffer-settings
4980 (regexp .
"^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4981 (modes .
'(org-mode)))))
4984 (org-set-local 'imenu-create-index-function
4985 'org-imenu-get-tree
)
4987 ;; Make isearch reveal context
4988 (if (or (featurep 'xemacs
)
4989 (not (boundp 'outline-isearch-open-invisible-function
)))
4990 ;; Emacs 21 and XEmacs make use of the hook
4991 (org-add-hook 'isearch-mode-end-hook
'org-isearch-end
'append
'local
)
4992 ;; Emacs 22 deals with this through a special variable
4993 (org-set-local 'outline-isearch-open-invisible-function
4994 (lambda (&rest ignore
) (org-show-context 'isearch
))))
4996 ;; Turn on org-beamer-mode?
4997 (and org-startup-with-beamer-mode
(org-beamer-mode))
4999 ;; Setup the pcomplete hooks
5000 (set (make-local-variable 'pcomplete-command-completion-function
)
5001 'org-pcomplete-initial
)
5002 (set (make-local-variable 'pcomplete-command-name-function
)
5003 'org-command-at-point
)
5004 (set (make-local-variable 'pcomplete-default-completion-function
)
5006 (set (make-local-variable 'pcomplete-parse-arguments-function
)
5007 'org-parse-arguments
)
5008 (set (make-local-variable 'pcomplete-termination-string
) "")
5009 (when (>= emacs-major-version
23)
5010 (set (make-local-variable 'buffer-face-mode-face
) 'org-default
))
5012 ;; If empty file that did not turn on org-mode automatically, make it to.
5013 (if (and org-insert-mode-line-in-empty-file
5014 (org-called-interactively-p 'any
)
5015 (= (point-min) (point-max)))
5016 (insert "# -*- mode: org -*-\n\n"))
5017 (unless org-inhibit-startup
5018 (when org-startup-align-all-tables
5019 (let ((bmp (buffer-modified-p)))
5020 (org-table-map-tables 'org-table-align
'quietly
)
5021 (set-buffer-modified-p bmp
)))
5022 (when org-startup-with-inline-images
5023 (org-display-inline-images))
5024 (when org-startup-indented
5025 (require 'org-indent
)
5026 (org-indent-mode 1))
5027 (unless org-inhibit-startup-visibility-stuff
5028 (org-set-startup-visibility)))
5029 ;; Try to set org-hide correctly
5030 (set-face-foreground 'org-hide
(org-find-invisible-foreground)))
5032 (when (fboundp 'abbrev-table-put
)
5033 (abbrev-table-put org-mode-abbrev-table
5034 :parents
(list text-mode-abbrev-table
)))
5036 (put 'org-mode
'flyspell-mode-predicate
'org-mode-flyspell-verify
)
5039 (defun org-find-invisible-foreground ()
5040 (let ((candidates (remove
5043 (face-background 'default
)
5044 (face-background 'org-default
)
5045 (cdr (assoc 'background-color default-frame-alist
))
5046 (cdr (assoc 'background-color initial-frame-alist
))
5047 (cdr (assoc 'background-color window-system-default-frame-alist
))
5048 (face-foreground 'org-hide
)))))
5049 (car (remove nil candidates
))))
5051 (defun org-current-time ()
5052 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5053 (if (> (car org-time-stamp-rounding-minutes
) 1)
5054 (let ((r (car org-time-stamp-rounding-minutes
))
5055 (time (decode-time)))
5057 (append (list 0 (* r
(floor (+ .5 (/ (float (nth 1 time
)) r
)))))
5062 "Return today date, considering `org-extend-today-until'."
5064 (time-subtract (current-time)
5065 (list 0 (* 3600 org-extend-today-until
) 0))))
5067 ;;;; Font-Lock stuff, including the activators
5069 (defvar org-mouse-map
(make-sparse-keymap))
5070 (org-defkey org-mouse-map
[mouse-2
] 'org-open-at-mouse
)
5071 (org-defkey org-mouse-map
[mouse-3
] 'org-find-file-at-mouse
)
5072 (when org-mouse-1-follows-link
5073 (org-defkey org-mouse-map
[follow-link
] 'mouse-face
))
5074 (when org-tab-follows-link
5075 (org-defkey org-mouse-map
[(tab)] 'org-open-at-point
)
5076 (org-defkey org-mouse-map
"\C-i" 'org-open-at-point
))
5078 (require 'font-lock
)
5080 (defconst org-non-link-chars
"]\t\n\r<>")
5081 (defvar org-link-types
'("http" "https" "ftp" "mailto" "file" "news"
5082 "shell" "elisp" "doi" "message"))
5083 (defvar org-link-types-re nil
5084 "Matches a link that has a url-like prefix like \"http:\"")
5085 (defvar org-link-re-with-space nil
5086 "Matches a link with spaces, optional angular brackets around it.")
5087 (defvar org-link-re-with-space2 nil
5088 "Matches a link with spaces, optional angular brackets around it.")
5089 (defvar org-link-re-with-space3 nil
5090 "Matches a link with spaces, only for internal part in bracket links.")
5091 (defvar org-angle-link-re nil
5092 "Matches link with angular brackets, spaces are allowed.")
5093 (defvar org-plain-link-re nil
5094 "Matches plain link, without spaces.")
5095 (defvar org-bracket-link-regexp nil
5096 "Matches a link in double brackets.")
5097 (defvar org-bracket-link-analytic-regexp nil
5098 "Regular expression used to analyze links.
5099 Here is what the match groups contain after a match:
5105 (defvar org-bracket-link-analytic-regexp
++ nil
5106 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5107 (defvar org-any-link-re nil
5108 "Regular expression matching any link.")
5110 (defcustom org-match-sexp-depth
3
5111 "Number of stacked braces for sub/superscript matching.
5112 This has to be set before loading org.el to be effective."
5113 :group
'org-export-translation
; ??????????????????????????/
5116 (defun org-create-multibrace-regexp (left right n
)
5117 "Create a regular expression which will match a balanced sexp.
5118 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5119 as single character strings.
5120 The regexp returned will match the entire expression including the
5121 delimiters. It will also define a single group which contains the
5122 match except for the outermost delimiters. The maximum depth of
5123 stacked delimiters is N. Escaping delimiters is not possible."
5124 (let* ((nothing (concat "[^" left right
"]*?"))
5127 (next (concat "\\(?:" nothing left nothing right
"\\)+" nothing
)))
5130 re
(concat re or next
)
5131 next
(concat "\\(?:" nothing left next right
"\\)+" nothing
)))
5132 (concat left
"\\(" re
"\\)" right
)))
5134 (defvar org-match-substring-regexp
5136 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5137 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5139 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth
) "\\)"
5141 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5142 "The regular expression matching a sub- or superscript.")
5144 (defvar org-match-substring-with-braces-regexp
5146 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5147 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth
) "\\)"
5149 "The regular expression matching a sub- or superscript, forcing braces.")
5151 (defun org-make-link-regexps ()
5152 "Update the link regular expressions.
5153 This should be called after the variable `org-link-types' has changed."
5154 (setq org-link-types-re
5156 "\\`\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):")
5157 org-link-re-with-space
5159 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5160 "\\([^" org-non-link-chars
" ]"
5161 "[^" org-non-link-chars
"]*"
5162 "[^" org-non-link-chars
" ]\\)>?")
5163 org-link-re-with-space2
5165 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5166 "\\([^" org-non-link-chars
" ]"
5168 "[^" org-non-link-chars
" ]\\)>?")
5169 org-link-re-with-space3
5171 "<?\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5172 "\\([^" org-non-link-chars
" ]"
5176 "<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5177 "\\([^" org-non-link-chars
" ]"
5178 "[^" org-non-link-chars
"]*"
5182 "\\<\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):"
5183 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5184 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5185 org-bracket-link-regexp
5186 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5187 org-bracket-link-analytic-regexp
5190 "\\(\\(" (mapconcat 'regexp-quote org-link-types
"\\|") "\\):\\)?"
5193 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5195 org-bracket-link-analytic-regexp
++
5198 "\\(\\(" (mapconcat 'regexp-quote
(cons "coderef" org-link-types
) "\\|") "\\):\\)?"
5201 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5204 (concat "\\(" org-bracket-link-regexp
"\\)\\|\\("
5205 org-angle-link-re
"\\)\\|\\("
5206 org-plain-link-re
"\\)")))
5208 (org-make-link-regexps)
5210 (defconst org-ts-regexp
"<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5211 "Regular expression for fast time stamp matching.")
5212 (defconst org-ts-regexp-both
"[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5213 "Regular expression for fast time stamp matching.")
5214 (defconst org-ts-regexp0
5215 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5216 "Regular expression matching time strings for analysis.
5217 This one does not require the space after the date, so it can be used
5218 on a string that terminates immediately after the date.")
5219 (defconst org-ts-regexp1
"\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5220 "Regular expression matching time strings for analysis.")
5221 (defconst org-ts-regexp2
(concat "<" org-ts-regexp1
"[^>\n]\\{0,16\\}>")
5222 "Regular expression matching time stamps, with groups.")
5223 (defconst org-ts-regexp3
(concat "[[<]" org-ts-regexp1
"[^]>\n]\\{0,16\\}[]>]")
5224 "Regular expression matching time stamps (also [..]), with groups.")
5225 (defconst org-tr-regexp
(concat org-ts-regexp
"--?-?" org-ts-regexp
)
5226 "Regular expression matching a time stamp range.")
5227 (defconst org-tr-regexp-both
5228 (concat org-ts-regexp-both
"--?-?" org-ts-regexp-both
)
5229 "Regular expression matching a time stamp range.")
5230 (defconst org-tsr-regexp
(concat org-ts-regexp
"\\(--?-?"
5231 org-ts-regexp
"\\)?")
5232 "Regular expression matching a time stamp or time stamp range.")
5233 (defconst org-tsr-regexp-both
(concat org-ts-regexp-both
"\\(--?-?"
5234 org-ts-regexp-both
"\\)?")
5235 "Regular expression matching a time stamp or time stamp range.
5236 The time stamps may be either active or inactive.")
5238 (defvar org-emph-face nil
)
5240 (defun org-do-emphasis-faces (limit)
5241 "Run through the buffer and add overlays to emphasized strings."
5243 (while (and (not rtn
) (re-search-forward org-emph-re limit t
))
5244 (if (not (= (char-after (match-beginning 3))
5245 (char-after (match-beginning 4))))
5248 (setq a
(assoc (match-string 3) org-emphasis-alist
))
5249 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5253 (org-remove-flyspell-overlays-in
5254 (match-beginning 0) (match-end 0)))
5255 (add-text-properties (match-beginning 2) (match-end 2)
5256 '(font-lock-multiline t org-emphasis t
))
5257 (when org-hide-emphasis-markers
5258 (add-text-properties (match-end 4) (match-beginning 5)
5259 '(invisible org-link
))
5260 (add-text-properties (match-beginning 3) (match-end 3)
5261 '(invisible org-link
)))))
5265 (defun org-emphasize (&optional char
)
5266 "Insert or change an emphasis, i.e. a font like bold or italic.
5267 If there is an active region, change that region to a new emphasis.
5268 If there is no region, just insert the marker characters and position
5269 the cursor between them.
5270 CHAR should be either the marker character, or the first character of the
5271 HTML tag associated with that emphasis. If CHAR is a space, the means
5272 to remove the emphasis of the selected region.
5273 If char is not given (for example in an interactive call) it
5274 will be prompted for."
5276 (let ((eal org-emphasis-alist
) e det
5277 (erc org-emphasis-regexp-components
)
5279 (string "") beg end move tag c s
)
5280 (if (org-region-active-p)
5281 (setq beg
(region-beginning) end
(region-end)
5282 string
(buffer-substring beg end
))
5285 (while (setq e
(pop eal
))
5286 (setq tag
(car (org-split-string (nth 2 e
) "[ <>/]+"))
5288 (push (cons c
(string-to-char (car e
))) det
)
5289 (setq prompt
(concat prompt
(format " [%s%c]%s" (car e
) c
5290 (substring tag
1)))))
5291 (setq det
(nreverse det
))
5293 (message "%s" (concat "Emphasis marker or tag:" prompt
))
5294 (setq char
(read-char-exclusive)))
5295 (setq char
(or (cdr (assoc char det
)) char
))
5296 (if (equal char ?\
)
5297 (setq s
"" move nil
)
5298 (unless (assoc (char-to-string char
) org-emphasis-alist
)
5299 (error "No such emphasis marker: \"%c\"" char
))
5300 (setq s
(char-to-string char
)))
5301 (while (and (> (length string
) 1)
5302 (equal (substring string
0 1) (substring string -
1))
5303 (assoc (substring string
0 1) org-emphasis-alist
))
5304 (setq string
(substring string
1 -
1)))
5305 (setq string
(concat s string s
))
5306 (if beg
(delete-region beg end
))
5308 (string-match (concat "[" (nth 0 erc
) "\n]")
5309 (char-to-string (char-before (point)))))
5312 (string-match (concat "[" (nth 1 erc
) "\n]")
5313 (char-to-string (char-after (point)))))
5314 (insert " ") (backward-char 1))
5316 (and move
(backward-char 1))))
5318 (defconst org-nonsticky-props
5319 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text
))
5321 (defsubst org-rear-nonsticky-at
(pos)
5322 (add-text-properties (1- pos
) pos
(list 'rear-nonsticky org-nonsticky-props
)))
5324 (defun org-activate-plain-links (limit)
5325 "Run through the buffer and add overlays to links."
5328 (when (re-search-forward (concat org-plain-link-re
) limit t
)
5329 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5330 (setq f
(get-text-property (match-beginning 0) 'face
))
5331 (setq hl
(org-match-string-no-properties 0))
5332 (if (or (eq f
'org-tag
)
5333 (and (listp f
) (memq 'org-tag f
)))
5335 (add-text-properties (match-beginning 0) (match-end 0)
5336 (list 'mouse-face
'highlight
5338 'htmlize-link
`(:uri
,hl
)
5339 'keymap org-mouse-map
))
5340 (org-rear-nonsticky-at (match-end 0)))
5343 (defun org-activate-code (limit)
5344 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t
)
5346 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5347 (remove-text-properties (match-beginning 0) (match-end 0)
5348 '(display t invisible t intangible t
))
5351 (defcustom org-src-fontify-natively nil
5352 "When non-nil, fontify code in code blocks."
5355 :group
'org-appearance
5358 (defcustom org-allow-promoting-top-level-subtree nil
5359 "When non-nil, allow promoting a top level subtree.
5360 The leading star of the top level headline will be replaced
5364 :group
'org-appearance
)
5366 (defun org-fontify-meta-lines-and-blocks (limit)
5368 (org-fontify-meta-lines-and-blocks-1 limit
)
5369 (error (message "org-mode fontification error"))))
5371 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5372 "Fontify #+ lines and blocks, in the correct ways."
5373 (let ((case-fold-search t
))
5374 (if (re-search-forward
5375 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5377 (let ((beg (match-beginning 0))
5378 (block-start (match-end 0))
5380 (lang (match-string 7))
5381 (beg1 (line-beginning-position 2))
5382 (dc1 (downcase (match-string 2)))
5383 (dc3 (downcase (match-string 3)))
5384 end end1 quoting block-type ovl
)
5386 ((member dc1
'("+html:" "+ascii:" "+latex:" "+docbook:"))
5387 ;; a single line of backend-specific content
5388 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5389 (remove-text-properties (match-beginning 0) (match-end 0)
5390 '(display t invisible t intangible t
))
5391 (add-text-properties (match-beginning 1) (match-end 3)
5392 '(font-lock-fontified t face org-meta-line
))
5393 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5394 '(font-lock-fontified t face org-block
))
5395 ; for backend-specific code
5397 ((and (match-end 4) (equal dc3
"+begin"))
5399 (setq block-type
(downcase (match-string 5))
5400 quoting
(member block-type org-protecting-blocks
))
5401 (when (re-search-forward
5402 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5403 nil t
) ;; on purpose, we look further than LIMIT
5404 (setq end
(min (point-max) (match-end 0))
5405 end1
(min (point-max) (1- (match-beginning 0))))
5406 (setq block-end
(match-beginning 0))
5408 (remove-text-properties beg end
5409 '(display t invisible t intangible t
)))
5410 (add-text-properties
5412 '(font-lock-fontified t font-lock-multiline t
))
5413 (add-text-properties beg beg1
'(face org-meta-line
))
5414 (add-text-properties end1
(min (point-max) (1+ end
))
5415 '(face org-meta-line
)) ; for end_src
5417 ((and lang
(not (string= lang
"")) org-src-fontify-natively
)
5418 (org-src-font-lock-fontify-block lang block-start block-end
)
5419 ;; remove old background overlays
5421 (if (eq (overlay-get ov
'face
) 'org-block-background
)
5422 (delete-overlay ov
)))
5423 (overlays-at (/ (+ beg1 block-end
) 2)))
5424 ;; add a background overlay
5425 (setq ovl
(make-overlay beg1 block-end
))
5426 (overlay-put ovl
'face
'org-block-background
)
5427 (overlay-put ovl
'evaporate t
)) ;; make it go away when empty
5429 (add-text-properties beg1
(min (point-max) (1+ end1
))
5430 '(face org-block
))) ; end of source block
5431 ((not org-fontify-quote-and-verse-blocks
))
5432 ((string= block-type
"quote")
5433 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-quote
)))
5434 ((string= block-type
"verse")
5435 (add-text-properties beg1
(min (point-max) (1+ end1
)) '(face org-verse
))))
5436 (add-text-properties beg beg1
'(face org-block-begin-line
))
5437 (add-text-properties (min (point-max) (1+ end
)) (min (point-max) (1+ end1
))
5438 '(face org-block-end-line
))
5440 ((member dc1
'("+title:" "+author:" "+email:" "+date:"))
5441 (add-text-properties
5443 (if (member (intern (substring dc1
0 -
1)) org-hidden-keywords
)
5444 '(font-lock-fontified t invisible t
)
5445 '(font-lock-fontified t face org-document-info-keyword
)))
5446 (add-text-properties
5447 (match-beginning 6) (match-end 6)
5448 (if (string-equal dc1
"+title:")
5449 '(font-lock-fontified t face org-document-title
)
5450 '(font-lock-fontified t face org-document-info
))))
5451 ((or (equal dc1
"+results")
5452 (member dc1
'("+begin:" "+end:" "+caption:" "+label:"
5453 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5454 "+call:" "+header:" "+headers:" "+name:"))
5455 (and (match-end 4) (equal dc3
"+attr")))
5456 (add-text-properties
5458 '(font-lock-fontified t face org-meta-line
))
5460 ((member dc3
'(" " ""))
5461 (add-text-properties
5463 '(font-lock-fontified t face font-lock-comment-face
)))
5464 ((not (member (char-after beg
) '(?\ ?
\t)))
5465 ;; just any other in-buffer setting, but not indented
5466 (add-text-properties
5468 '(font-lock-fontified t face org-meta-line
))
5472 (defun org-activate-angle-links (limit)
5473 "Run through the buffer and add overlays to links."
5474 (if (re-search-forward org-angle-link-re limit t
)
5476 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5477 (add-text-properties (match-beginning 0) (match-end 0)
5478 (list 'mouse-face
'highlight
5479 'keymap org-mouse-map
))
5480 (org-rear-nonsticky-at (match-end 0))
5483 (defun org-activate-footnote-links (limit)
5484 "Run through the buffer and add overlays to footnotes."
5485 (let ((fn (org-footnote-next-reference-or-definition limit
)))
5487 (let ((beg (nth 1 fn
)) (end (nth 2 fn
)))
5488 (org-remove-flyspell-overlays-in beg end
)
5489 (add-text-properties beg end
5490 (list 'mouse-face
'highlight
5491 'keymap org-mouse-map
5493 (if (= (point-at-bol) beg
)
5494 "Footnote definition"
5495 "Footnote reference")
5496 'font-lock-fontified t
5497 'font-lock-multiline t
5498 'face
'org-footnote
))))))
5500 (defun org-activate-bracket-links (limit)
5501 "Run through the buffer and add overlays to bracketed links."
5502 (if (re-search-forward org-bracket-link-regexp limit t
)
5503 (let* ((hl (org-match-string-no-properties 1))
5504 (help (concat "LINK: " hl
))
5505 ;; FIXME: Above we should remove the escapes. But that
5506 ;; requires another match, protecting match data, a lot
5507 ;; of overhead for font-lock.
5508 (ip (org-maybe-intangible
5509 (list 'invisible
'org-link
5510 'keymap org-mouse-map
'mouse-face
'highlight
5511 'font-lock-multiline t
'help-echo help
5512 'htmlize-link
`(:uri
,hl
))))
5513 (vp (list 'keymap org-mouse-map
'mouse-face
'highlight
5514 'font-lock-multiline t
'help-echo help
5515 'htmlize-link
`(:uri
,hl
))))
5516 ;; We need to remove the invisible property here. Table narrowing
5517 ;; may have made some of this invisible.
5518 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5519 (remove-text-properties (match-beginning 0) (match-end 0)
5523 (add-text-properties (match-beginning 0) (match-beginning 3) ip
)
5524 (org-rear-nonsticky-at (match-beginning 3))
5525 (add-text-properties (match-beginning 3) (match-end 3) vp
)
5526 (org-rear-nonsticky-at (match-end 3))
5527 (add-text-properties (match-end 3) (match-end 0) ip
)
5528 (org-rear-nonsticky-at (match-end 0)))
5529 (add-text-properties (match-beginning 0) (match-beginning 1) ip
)
5530 (org-rear-nonsticky-at (match-beginning 1))
5531 (add-text-properties (match-beginning 1) (match-end 1) vp
)
5532 (org-rear-nonsticky-at (match-end 1))
5533 (add-text-properties (match-end 1) (match-end 0) ip
)
5534 (org-rear-nonsticky-at (match-end 0)))
5537 (defun org-activate-dates (limit)
5538 "Run through the buffer and add overlays to dates."
5539 (if (re-search-forward org-tsr-regexp-both limit t
)
5541 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5542 (add-text-properties (match-beginning 0) (match-end 0)
5543 (list 'mouse-face
'highlight
5544 'keymap org-mouse-map
))
5545 (org-rear-nonsticky-at (match-end 0))
5546 (when org-display-custom-times
5548 (org-display-custom-time (match-beginning 3) (match-end 3)))
5549 (org-display-custom-time (match-beginning 1) (match-end 1)))
5552 (defvar org-target-link-regexp nil
5553 "Regular expression matching radio targets in plain text.")
5554 (make-variable-buffer-local 'org-target-link-regexp
)
5555 (defvar org-target-regexp
"<<\\([^<>\n\r]+\\)>>"
5556 "Regular expression matching a link target.")
5557 (defvar org-radio-target-regexp
"<<<\\([^<>\n\r]+\\)>>>"
5558 "Regular expression matching a radio target.")
5559 (defvar org-any-target-regexp
"<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5560 "Regular expression matching any target.")
5562 (defun org-activate-target-links (limit)
5563 "Run through the buffer and add overlays to target matches."
5564 (when org-target-link-regexp
5565 (let ((case-fold-search t
))
5566 (if (re-search-forward org-target-link-regexp limit t
)
5568 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5569 (add-text-properties (match-beginning 0) (match-end 0)
5570 (list 'mouse-face
'highlight
5571 'keymap org-mouse-map
5572 'help-echo
"Radio target link"
5573 'org-linked-text t
))
5574 (org-rear-nonsticky-at (match-end 0))
5577 (defun org-update-radio-target-regexp ()
5578 "Find all radio targets in this file and update the regular expression."
5580 (when (memq 'radio org-activate-links
)
5581 (setq org-target-link-regexp
5582 (org-make-target-link-regexp (org-all-targets 'radio
)))
5583 (org-restart-font-lock)))
5585 (defun org-hide-wide-columns (limit)
5587 (setq s
(text-property-any (point) (or limit
(point-max))
5590 (setq e
(next-single-property-change s
'org-cwidth
))
5591 (add-text-properties s e
(org-maybe-intangible '(invisible org-cwidth
)))
5595 (defvar org-latex-and-specials-regexp nil
5596 "Regular expression for highlighting export special stuff.")
5597 (defvar org-match-substring-regexp
)
5598 (defvar org-match-substring-with-braces-regexp
)
5600 ;; This should be with the exporter code, but we also use if for font-locking
5601 (defconst org-export-html-special-string-regexps
5602 '(("\\\\-" .
"­")
5603 ("---\\([^-]\\)" .
"—\\1")
5604 ("--\\([^-]\\)" .
"–\\1")
5605 ("\\.\\.\\." .
"…"))
5606 "Regular expressions for special string conversion.")
5609 (defun org-compute-latex-and-specials-regexp ()
5610 "Compute regular expression for stuff treated specially by exporters."
5611 (if (not org-highlight-latex-fragments-and-specials
)
5612 (org-set-local 'org-latex-and-specials-regexp nil
)
5615 ((matchers (plist-get org-format-latex-options
:matchers
))
5616 (latexs (delq nil
(mapcar (lambda (x) (if (member (car x
) matchers
) x
))
5617 org-latex-regexps
)))
5618 (org-export-allow-BIND nil
)
5619 (options (org-combine-plists (org-default-export-plist)
5620 (org-infile-export-plist)))
5621 (org-export-with-sub-superscripts (plist-get options
:sub-superscript
))
5622 (org-export-with-LaTeX-fragments (plist-get options
:LaTeX-fragments
))
5623 (org-export-with-TeX-macros (plist-get options
:TeX-macros
))
5624 (org-export-html-expand (plist-get options
:expand-quoted-html
))
5625 (org-export-with-special-strings (plist-get options
:special-strings
))
5628 ((equal org-export-with-sub-superscripts
'{})
5629 (list org-match-substring-with-braces-regexp
))
5630 (org-export-with-sub-superscripts
5631 (list org-match-substring-regexp
))))
5633 (if org-export-with-LaTeX-fragments
5634 (mapcar (lambda (x) (nth 1 x
)) latexs
)))
5636 (if org-export-with-TeX-macros
5637 (list (concat "\\\\"
5643 (append org-entities-user
5645 (if (boundp 'org-latex-entities
)
5647 (or (car-safe x
) x
))
5652 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5653 (re-special (if org-export-with-special-strings
5654 (mapcar (lambda (x) (car x
))
5655 org-export-html-special-string-regexps
)))
5659 (if org-export-html-expand
"@<[^>\n]+>")
5662 'org-latex-and-specials-regexp
5663 (mapconcat 'identity
(append re-latex re-sub re-macros re-special
5666 (defun org-do-latex-and-special-faces (limit)
5667 "Run through the buffer and add overlays to links."
5668 (when org-latex-and-specials-regexp
5670 (while (and (not rtn
) (re-search-forward org-latex-and-specials-regexp
5672 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5674 '(org-code org-verbatim underline
)))
5677 d
(cond ((member (char-after (1+ (match-beginning 0)))
5680 (font-lock-prepend-text-property
5681 (+ d
(match-beginning 0)) (match-end 0)
5682 'face
'org-latex-and-export-specials
)
5683 (add-text-properties (+ d
(match-beginning 0)) (match-end 0)
5684 '(font-lock-multiline t
)))))
5687 (defun org-restart-font-lock ()
5688 "Restart `font-lock-mode', to force refontification."
5689 (when (and (boundp 'font-lock-mode
) font-lock-mode
)
5691 (font-lock-mode 1)))
5693 (defun org-all-targets (&optional radio
)
5694 "Return a list of all targets in this file.
5695 When optional argument RADIO is non-nil, only find radio
5697 (let ((re (if radio org-radio-target-regexp org-target-regexp
)) rtn
)
5699 (goto-char (point-min))
5700 (while (re-search-forward re nil t
)
5701 (let ((obj (org-element-context)))
5702 (when (memq (org-element-type obj
) '(radio-target target
))
5703 (add-to-list 'rtn
(downcase (org-element-property :value obj
))))))
5706 (defun org-make-target-link-regexp (targets)
5707 "Make regular expression matching all strings in TARGETS.
5708 The regular expression finds the targets also if there is a line break
5715 (setq x
(regexp-quote x
))
5716 (while (string-match " +" x
)
5717 (setq x
(replace-match "\\s-+" t t x
)))
5723 (defun org-activate-tags (limit)
5724 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t
)
5726 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5727 (add-text-properties (match-beginning 1) (match-end 1)
5728 (list 'mouse-face
'highlight
5729 'keymap org-mouse-map
))
5730 (org-rear-nonsticky-at (match-end 1))
5733 (defun org-outline-level ()
5734 "Compute the outline level of the heading at point.
5735 If this is called at a normal headline, the level is the number of stars.
5736 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5738 (if (not (condition-case nil
5739 (org-back-to-heading t
)
5742 (looking-at org-outline-regexp
)
5743 (1- (- (match-end 0) (match-beginning 0))))))
5745 (defvar org-font-lock-keywords nil
)
5747 (defconst org-property-re
(org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5748 "Regular expression matching a property line.")
5750 (defvar org-font-lock-hook nil
5751 "Functions to be called for special font lock stuff.")
5753 (defvar org-font-lock-set-keywords-hook nil
5754 "Functions that can manipulate `org-font-lock-extra-keywords'.
5755 This is called after `org-font-lock-extra-keywords' is defined, but before
5756 it is installed to be used by font lock. This can be useful if something
5757 needs to be inserted at a specific position in the font-lock sequence.")
5759 (defun org-font-lock-hook (limit)
5760 "Run `org-font-lock-hook' within LIMIT."
5761 (run-hook-with-args 'org-font-lock-hook limit
))
5763 (defun org-set-font-lock-defaults ()
5764 "Set font lock defaults for the current buffer."
5765 (let* ((em org-fontify-emphasized-text
)
5766 (lk org-activate-links
)
5767 (org-font-lock-extra-keywords
5770 '(org-font-lock-hook)
5772 `(,(if org-fontify-whole-heading-line
5773 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5774 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5775 (1 (org-get-level-face 1))
5776 (2 (org-get-level-face 2))
5777 (3 (org-get-level-face 3)))
5779 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5782 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t
))
5783 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t
))
5784 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t
))
5785 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t
))
5787 (list org-drawer-regexp
'(0 'org-special-keyword t
))
5788 (list "^[ \t]*:END:" '(0 'org-special-keyword t
))
5790 (list org-property-re
5791 '(1 'org-special-keyword t
)
5792 '(3 'org-property-value t
))
5794 (if (memq 'tag lk
) '(org-activate-tags (1 'org-tag prepend
)))
5795 (if (memq 'angle lk
) '(org-activate-angle-links (0 'org-link t
)))
5796 (if (memq 'plain lk
) '(org-activate-plain-links))
5797 (if (memq 'bracket lk
) '(org-activate-bracket-links (0 'org-link t
)))
5798 (if (memq 'radio lk
) '(org-activate-target-links (0 'org-link t
)))
5799 (if (memq 'date lk
) '(org-activate-dates (0 'org-date t
)))
5800 (if (memq 'footnote lk
) '(org-activate-footnote-links))
5801 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t
))
5802 '(org-hide-wide-columns (0 nil append
))
5804 (list (format org-heading-keyword-regexp-format
5806 '(2 (org-get-todo-face 2) t
))
5808 (if org-fontify-done-headline
5809 (list (format org-heading-keyword-regexp-format
5812 (mapconcat 'regexp-quote org-done-keywords
"\\|")
5814 '(2 'org-headline-done t
))
5817 '(org-font-lock-add-priority-faces)
5819 '(org-font-lock-add-tag-faces)
5821 (list (concat "\\<" org-deadline-string
) '(0 'org-special-keyword t
))
5822 (list (concat "\\<" org-scheduled-string
) '(0 'org-special-keyword t
))
5823 (list (concat "\\<" org-closed-string
) '(0 'org-special-keyword t
))
5824 (list (concat "\\<" org-clock-string
) '(0 'org-special-keyword t
))
5827 (if (featurep 'xemacs
)
5828 '(org-do-emphasis-faces (0 nil append
))
5829 '(org-do-emphasis-faces)))
5831 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5832 1 'org-checkbox prepend
)
5833 (if (cdr (assq 'checkbox org-list-automatic-rules
))
5834 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5835 (0 (org-get-checkbox-statistics-face) t
)))
5836 ;; Description list items
5837 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5838 1 'org-list-dt prepend
)
5839 ;; ARCHIVEd headings
5841 org-outline-regexp-bol
5842 "\\(.*:" org-archive-tag
":.*\\)")
5843 '(1 'org-archived prepend
))
5845 '(org-do-latex-and-special-faces)
5846 '(org-fontify-entities)
5847 '(org-raise-scripts)
5849 '(org-activate-code (1 'org-code t
))
5851 (list (format org-heading-keyword-regexp-format
5853 org-comment-string
"\\|" org-quote-string
5855 '(2 'org-special-keyword t
))
5856 ;; Blocks and meta lines
5857 '(org-fontify-meta-lines-and-blocks)
5859 (setq org-font-lock-extra-keywords
(delq nil org-font-lock-extra-keywords
))
5860 (run-hooks 'org-font-lock-set-keywords-hook
)
5861 ;; Now set the full font-lock-keywords
5862 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords
)
5863 (org-set-local 'font-lock-defaults
5864 '(org-font-lock-keywords t nil nil backward-paragraph
))
5865 (kill-local-variable 'font-lock-keywords
) nil
))
5867 (defun org-toggle-pretty-entities ()
5868 "Toggle the composition display of entities as UTF8 characters."
5870 (org-set-local 'org-pretty-entities
(not org-pretty-entities
))
5871 (org-restart-font-lock)
5872 (if org-pretty-entities
5873 (message "Entities are displayed as UTF8 characters")
5876 (org-decompose-region (point-min) (point-max))
5877 (message "Entities are displayed plain"))))
5879 (defvar org-custom-properties-overlays nil
5880 "List of overlays used for custom properties.")
5881 (make-variable-buffer-local 'org-custom-properties-overlays
)
5883 (defun org-toggle-custom-properties-visibility ()
5884 "Display or hide properties in `org-custom-properties'."
5886 (if org-custom-properties-overlays
5887 (progn (mapc 'delete-overlay org-custom-properties-overlays
)
5888 (setq org-custom-properties-overlays nil
))
5889 (unless (not org-custom-properties
)
5893 (goto-char (point-min))
5894 (while (re-search-forward org-property-re nil t
)
5896 (when (equal p
(substring (match-string 1) 1 -
1))
5897 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5898 (overlay-put o
'invisible t
)
5899 (overlay-put o
'org-custom-property t
)
5900 (push o org-custom-properties-overlays
))))
5901 org-custom-properties
)))))))
5903 (defun org-fontify-entities (limit)
5904 "Find an entity to fontify."
5906 (when org-pretty-entities
5908 (while (re-search-forward
5909 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
5911 (if (and (not (org-in-indented-comment-line))
5912 (setq ee
(org-entity-get (match-string 1)))
5913 (= (length (nth 6 ee
)) 1))
5915 ((end (if (equal (match-string 2) "{}")
5918 (add-text-properties
5919 (match-beginning 0) end
5920 (list 'font-lock-fontified t
))
5921 (compose-region (match-beginning 0) end
5927 (defun org-fontify-like-in-org-mode (s &optional odd-levels
)
5928 "Fontify string S like in Org-mode."
5931 (let ((org-odd-levels-only odd-levels
))
5933 (font-lock-fontify-buffer)
5939 (defun org-get-level-face (n)
5940 "Get the right face for match N in font-lock matching of headlines."
5941 (setq org-l
(- (match-end 2) (match-beginning 1) 1))
5942 (if org-odd-levels-only
(setq org-l
(1+ (/ org-l
2))))
5943 (if org-cycle-level-faces
5944 (setq org-f
(nth (%
(1- org-l
) org-n-level-faces
) org-level-faces
))
5945 (setq org-f
(nth (1- (min org-l org-n-level-faces
)) org-level-faces
)))
5947 ((eq n
1) (if org-hide-leading-stars
'org-hide org-f
))
5949 (t (if org-level-color-stars-only nil org-f
))))
5952 (defun org-get-todo-face (kwd)
5953 "Get the right face for a TODO keyword KWD.
5954 If KWD is a number, get the corresponding match group."
5955 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
5956 (or (org-face-from-face-or-color
5957 'todo
'org-todo
(cdr (assoc kwd org-todo-keyword-faces
)))
5958 (and (member kwd org-done-keywords
) 'org-done
)
5961 (defun org-face-from-face-or-color (context inherit face-or-color
)
5962 "Create a face list that inherits INHERIT, but sets the foreground color.
5963 When FACE-OR-COLOR is not a string, just return it."
5964 (if (stringp face-or-color
)
5965 (list :inherit inherit
5966 (cdr (assoc context org-faces-easy-properties
))
5970 (defun org-font-lock-add-tag-faces (limit)
5971 "Add the special tag faces."
5972 (when (and org-tag-faces org-tags-special-faces-re
)
5973 (while (re-search-forward org-tags-special-faces-re limit t
)
5974 (add-text-properties (match-beginning 1) (match-end 1)
5975 (list 'face
(org-get-tag-face 1)
5976 'font-lock-fontified t
))
5977 (backward-char 1))))
5979 (defun org-font-lock-add-priority-faces (limit)
5980 "Add the special priority faces."
5981 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t
)
5982 (when (save-match-data (org-at-heading-p))
5983 (add-text-properties
5984 (match-beginning 0) (match-end 0)
5985 (list 'face
(or (org-face-from-face-or-color
5986 'priority
'org-special-keyword
5987 (cdr (assoc (char-after (match-beginning 1))
5988 org-priority-faces
)))
5989 'org-special-keyword
)
5990 'font-lock-fontified t
)))))
5992 (defun org-get-tag-face (kwd)
5993 "Get the right face for a TODO keyword KWD.
5994 If KWD is a number, get the corresponding match group."
5995 (if (numberp kwd
) (setq kwd
(match-string kwd
)))
5996 (or (org-face-from-face-or-color
5997 'tag
'org-tag
(cdr (assoc kwd org-tag-faces
)))
6000 (defun org-unfontify-region (beg end
&optional maybe_loudly
)
6001 "Remove fontification and activation overlays from links."
6002 (font-lock-default-unfontify-region beg end
)
6003 (let* ((buffer-undo-list t
)
6004 (inhibit-read-only t
) (inhibit-point-motion-hooks t
)
6005 (inhibit-modification-hooks t
)
6006 deactivate-mark buffer-file-name buffer-file-truename
)
6007 (org-decompose-region beg end
)
6008 (remove-text-properties beg end
6009 '(mouse-face t keymap t org-linked-text t
6010 invisible t intangible t
6011 org-no-flyspell t org-emphasis t
))
6012 (org-remove-font-lock-display-properties beg end
)))
6014 (defconst org-script-display
'(((raise -
0.3) (height 0.7))
6015 ((raise 0.3) (height 0.7))
6018 "Display properties for showing superscripts and subscripts.")
6020 (defun org-remove-font-lock-display-properties (beg end
)
6021 "Remove specific display properties that have been added by font lock.
6022 The will remove the raise properties that are used to show superscripts
6026 (setq next
(next-single-property-change beg
'display nil end
)
6027 prop
(get-text-property beg
'display
))
6028 (if (member prop org-script-display
)
6029 (put-text-property beg next
'display nil
))
6032 (defun org-raise-scripts (limit)
6033 "Add raise properties to sub/superscripts."
6034 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
)
6035 (if (re-search-forward
6036 (if (eq org-use-sub-superscripts t
)
6037 org-match-substring-regexp
6038 org-match-substring-with-braces-regexp
)
6040 (let* ((pos (point)) table-p comment-p
6041 (mpos (match-beginning 3))
6042 (emph-p (get-text-property mpos
'org-emphasis
))
6043 (link-p (get-text-property mpos
'mouse-face
))
6044 (keyw-p (eq 'org-special-keyword
(get-text-property mpos
'face
))))
6045 (goto-char (point-at-bol))
6046 (setq table-p
(org-looking-at-p org-table-dataline-regexp
)
6047 comment-p
(org-looking-at-p "[ \t]*#"))
6049 ;; FIXME: Should we go back one character here, for a_b^c
6050 ;; (goto-char (1- pos)) ;????????????????????
6051 (if (or comment-p emph-p link-p keyw-p
)
6053 (put-text-property (match-beginning 3) (match-end 0)
6055 (if (equal (char-after (match-beginning 2)) ?^
)
6056 (nth (if table-p
3 1) org-script-display
)
6057 (nth (if table-p
2 0) org-script-display
)))
6058 (add-text-properties (match-beginning 2) (match-end 2)
6060 'org-dwidth t
'org-dwidth-n
1))
6061 (if (and (eq (char-after (match-beginning 3)) ?
{)
6062 (eq (char-before (match-end 3)) ?
}))
6064 (add-text-properties
6065 (match-beginning 3) (1+ (match-beginning 3))
6066 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))
6067 (add-text-properties
6068 (1- (match-end 3)) (match-end 3)
6069 (list 'invisible t
'org-dwidth t
'org-dwidth-n
1))))
6072 ;;;; Visibility cycling, including org-goto and indirect buffer
6076 (defvar org-cycle-global-status nil
)
6077 (make-variable-buffer-local 'org-cycle-global-status
)
6078 (defvar org-cycle-subtree-status nil
)
6079 (make-variable-buffer-local 'org-cycle-subtree-status
)
6081 (defvar org-inlinetask-min-level
)
6084 (defun org-cycle (&optional arg
)
6085 "TAB-action and visibility cycling for Org-mode.
6087 This is the command invoked in Org-mode by the TAB key. Its main purpose
6088 is outline visibility cycling, but it also invokes other actions
6089 in special contexts.
6091 - When this function is called with a prefix argument, rotate the entire
6092 buffer through 3 states (global cycling)
6093 1. OVERVIEW: Show only top-level headlines.
6094 2. CONTENTS: Show all headlines of all levels, but no body text.
6095 3. SHOW ALL: Show everything.
6096 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6097 determined by the variable `org-startup-folded', and by any VISIBILITY
6098 properties in the buffer.
6099 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6100 including any drawers.
6102 - When inside a table, re-align the table and move to the next field.
6104 - When point is at the beginning of a headline, rotate the subtree started
6105 by this line through 3 different states (local cycling)
6106 1. FOLDED: Only the main headline is shown.
6107 2. CHILDREN: The main headline and the direct children are shown.
6108 From this state, you can move to one of the children
6109 and zoom in further.
6110 3. SUBTREE: Show the entire subtree, including body text.
6111 If there is no subtree, switch directly from CHILDREN to FOLDED.
6113 - When point is at the beginning of an empty headline and the variable
6114 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6115 of the headline by demoting and promoting it to likely levels. This
6116 speeds up creation document structure by pressing TAB once or several
6117 times right after creating a new headline.
6119 - When there is a numeric prefix, go up to a heading with level ARG, do
6120 a `show-subtree' and return to the previous cursor position. If ARG
6121 is negative, go up that many levels.
6123 - When point is not at the beginning of a headline, execute the global
6124 binding for TAB, which is re-indenting the line. See the option
6125 `org-cycle-emulate-tab' for details.
6127 - Special case: if point is at the beginning of the buffer and there is
6128 no headline in line 1, this function will act as if called with prefix arg
6129 (C-u TAB, same as S-TAB) also when called without prefix arg.
6130 But only if also the variable `org-cycle-global-at-bob' is t."
6132 (org-load-modules-maybe)
6133 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook
)
6134 (and org-cycle-level-after-item
/entry-creation
6135 (or (org-cycle-level)
6136 (org-cycle-item-indentation))))
6138 (or org-cycle-max-level
6139 (and (boundp 'org-inlinetask-min-level
)
6140 org-inlinetask-min-level
6141 (1- org-inlinetask-min-level
))))
6142 (nstars (and limit-level
6143 (if org-odd-levels-only
6144 (and limit-level
(1- (* limit-level
2)))
6147 (if (not (derived-mode-p 'org-mode
))
6149 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ "))))
6150 (bob-special (and org-cycle-global-at-bob
(not arg
) (bobp)
6151 (not (looking-at org-outline-regexp
))))
6154 (delq 'org-optimize-window-after-visibility-change
6155 (copy-sequence org-cycle-hook
))
6159 (if (or bob-special
(equal arg
'(4)))
6160 ;; special case: use global cycling
6166 (setq last-command
'dummy
)
6167 (org-set-startup-visibility)
6168 (message "Startup visibility, plus VISIBILITY properties"))
6172 (message "Entire buffer visible, including drawers"))
6174 ;; Table: enter it or move to the next field.
6175 ((org-at-table-p 'any
)
6176 (if (org-at-table.el-p
)
6177 (message "Use C-c ' to edit table.el tables")
6178 (if arg
(org-table-edit-field t
)
6179 (org-table-justify-field-maybe)
6180 (call-interactively 'org-table-next-field
))))
6182 ((run-hook-with-args-until-success
6183 'org-tab-after-check-for-table-hook
))
6185 ;; Global cycling: delegate to `org-cycle-internal-global'.
6186 ((eq arg t
) (org-cycle-internal-global))
6188 ;; Drawers: delegate to `org-flag-drawer'.
6189 ((and org-drawers org-drawer-regexp
6191 (beginning-of-line 1)
6192 (looking-at org-drawer-regexp
)))
6193 (org-flag-drawer ; toggle block visibility
6194 (not (get-char-property (match-end 0) 'invisible
))))
6196 ;; Show-subtree, ARG levels up from here.
6199 (org-back-to-heading)
6200 (outline-up-heading (if (< arg
0) (- arg
)
6201 (- (funcall outline-level
) arg
)))
6202 (org-show-subtree)))
6204 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6205 ((and (featurep 'org-inlinetask
)
6206 (org-inlinetask-at-task-p)
6207 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6208 (org-inlinetask-toggle-visibility))
6210 ((org-try-cdlatex-tab))
6212 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6213 ((and (or (and org-cycle-include-plain-lists
(org-at-item-p))
6214 (save-excursion (beginning-of-line 1)
6215 (looking-at org-outline-regexp
)))
6216 (or (bolp) (not (eq org-cycle-emulate-tab
'exc-hl-bol
))))
6217 (org-cycle-internal-local))
6219 ;; From there: TAB emulation and template completion.
6220 (buffer-read-only (org-back-to-heading))
6222 ((run-hook-with-args-until-success
6223 'org-tab-after-check-for-cycling-hook
))
6225 ((org-try-structure-completion))
6227 ((run-hook-with-args-until-success
6228 'org-tab-before-tab-emulation-hook
))
6230 ((and (eq org-cycle-emulate-tab
'exc-hl-bol
)
6232 (not (looking-at org-outline-regexp
))))
6233 (call-interactively (global-key-binding "\t")))
6235 ((if (and (memq org-cycle-emulate-tab
'(white whitestart
))
6236 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6237 (or (and (eq org-cycle-emulate-tab
'white
)
6238 (= (match-end 0) (point-at-eol)))
6239 (and (eq org-cycle-emulate-tab
'whitestart
)
6240 (>= (match-end 0) pos
))))
6242 (eq org-cycle-emulate-tab t
))
6243 (call-interactively (global-key-binding "\t")))
6246 (org-back-to-heading)
6249 (defun org-cycle-internal-global ()
6250 "Do the global cycling action."
6251 ;; Hack to avoid display of messages for .org attachments in Gnus
6252 (let ((ga (string-match "\\*fontification" (buffer-name))))
6254 ((and (eq last-command this-command
)
6255 (eq org-cycle-global-status
'overview
))
6256 ;; We just created the overview - now do table of contents
6257 ;; This can be slow in very large buffers, so indicate action
6258 (run-hook-with-args 'org-pre-cycle-hook
'contents
)
6259 (unless ga
(message "CONTENTS..."))
6261 (unless ga
(message "CONTENTS...done"))
6262 (setq org-cycle-global-status
'contents
)
6263 (run-hook-with-args 'org-cycle-hook
'contents
))
6265 ((and (eq last-command this-command
)
6266 (eq org-cycle-global-status
'contents
))
6267 ;; We just showed the table of contents - now show everything
6268 (run-hook-with-args 'org-pre-cycle-hook
'all
)
6270 (unless ga
(message "SHOW ALL"))
6271 (setq org-cycle-global-status
'all
)
6272 (run-hook-with-args 'org-cycle-hook
'all
))
6275 ;; Default action: go to overview
6276 (run-hook-with-args 'org-pre-cycle-hook
'overview
)
6278 (unless ga
(message "OVERVIEW"))
6279 (setq org-cycle-global-status
'overview
)
6280 (run-hook-with-args 'org-cycle-hook
'overview
)))))
6282 (defun org-cycle-internal-local ()
6283 "Do the local cycling action."
6284 (let ((goal-column 0) eoh eol eos has-children children-skipped struct
)
6285 ;; First, determine end of headline (EOH), end of subtree or item
6286 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6291 (setq struct
(org-list-struct))
6292 (setq eoh
(point-at-eol))
6293 (setq eos
(org-list-get-item-end-before-blank (point) struct
))
6294 (setq has-children
(org-list-has-child-p (point) struct
)))
6295 (org-back-to-heading)
6296 (setq eoh
(save-excursion (outline-end-of-heading) (point)))
6297 (setq eos
(save-excursion
6298 (org-end-of-subtree t
)
6300 (skip-chars-forward " \t\n"))
6301 (if (eobp) (point) (1- (point)))))
6304 (let ((level (funcall outline-level
)))
6305 (outline-next-heading)
6306 (and (org-at-heading-p t
)
6307 (> (funcall outline-level
) level
))))
6309 (org-list-search-forward (org-item-beginning-re) eos t
)))))
6310 ;; Determine end invisible part of buffer (EOL)
6311 (beginning-of-line 2)
6312 ;; XEmacs doesn't have `next-single-char-property-change'
6313 (if (featurep 'xemacs
)
6314 (while (and (not (eobp)) ;; this is like `next-line'
6315 (get-char-property (1- (point)) 'invisible
))
6316 (beginning-of-line 2))
6317 (while (and (not (eobp)) ;; this is like `next-line'
6318 (get-char-property (1- (point)) 'invisible
))
6319 (goto-char (next-single-char-property-change (point) 'invisible
))
6320 (and (eolp) (beginning-of-line 2))))
6322 ;; Find out what to do next and set `this-command'
6325 ;; Nothing is hidden behind this heading
6326 (run-hook-with-args 'org-pre-cycle-hook
'empty
)
6327 (message "EMPTY ENTRY")
6328 (setq org-cycle-subtree-status nil
)
6331 (outline-next-heading)
6332 (if (outline-invisible-p) (org-flag-heading nil
))))
6333 ((and (or (>= eol eos
)
6334 (not (string-match "\\S-" (buffer-substring eol eos
))))
6336 (not (setq children-skipped
6337 org-cycle-skip-children-state-if-no-children
))))
6338 ;; Entire subtree is hidden in one line: children view
6339 (run-hook-with-args 'org-pre-cycle-hook
'children
)
6341 (org-list-set-item-visibility (point-at-bol) struct
'children
)
6343 (org-with-limited-levels (show-children))
6344 ;; FIXME: This slows down the func way too much.
6345 ;; How keep drawers hidden in subtree anyway?
6346 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6347 ;; (org-cycle-hide-drawers 'subtree))
6349 ;; Fold every list in subtree to top-level items.
6350 (when (eq org-cycle-include-plain-lists
'integrate
)
6352 (org-back-to-heading)
6353 (while (org-list-search-forward (org-item-beginning-re) eos t
)
6354 (beginning-of-line 1)
6355 (let* ((struct (org-list-struct))
6356 (prevs (org-list-prevs-alist struct
))
6357 (end (org-list-get-bottom-point struct
)))
6358 (mapc (lambda (e) (org-list-set-item-visibility e struct
'folded
))
6359 (org-list-get-all-items (point) struct prevs
))
6360 (goto-char end
))))))
6361 (message "CHILDREN")
6364 (outline-next-heading)
6365 (if (outline-invisible-p) (org-flag-heading nil
)))
6366 (setq org-cycle-subtree-status
'children
)
6367 (run-hook-with-args 'org-cycle-hook
'children
))
6368 ((or children-skipped
6369 (and (eq last-command this-command
)
6370 (eq org-cycle-subtree-status
'children
)))
6371 ;; We just showed the children, or no children are there,
6372 ;; now show everything.
6373 (run-hook-with-args 'org-pre-cycle-hook
'subtree
)
6374 (outline-flag-region eoh eos nil
)
6375 (message (if children-skipped
"SUBTREE (NO CHILDREN)" "SUBTREE"))
6376 (setq org-cycle-subtree-status
'subtree
)
6377 (run-hook-with-args 'org-cycle-hook
'subtree
))
6379 ;; Default action: hide the subtree.
6380 (run-hook-with-args 'org-pre-cycle-hook
'folded
)
6381 (outline-flag-region eoh eos t
)
6383 (setq org-cycle-subtree-status
'folded
)
6384 (run-hook-with-args 'org-cycle-hook
'folded
)))))
6387 (defun org-global-cycle (&optional arg
)
6388 "Cycle the global visibility. For details see `org-cycle'.
6389 With \\[universal-argument] prefix arg, switch to startup visibility.
6390 With a numeric prefix, show all headlines up to that level."
6392 (let ((org-cycle-include-plain-lists
6393 (if (derived-mode-p 'org-mode
) org-cycle-include-plain-lists nil
)))
6397 (hide-sublevels arg
)
6398 (setq org-cycle-global-status
'contents
))
6400 (org-set-startup-visibility)
6401 (message "Startup visibility, plus VISIBILITY properties."))
6403 (org-cycle '(4))))))
6405 (defun org-set-startup-visibility ()
6406 "Set the visibility required by startup options and properties."
6408 ((eq org-startup-folded t
)
6410 ((eq org-startup-folded
'content
)
6411 (let ((this-command 'org-cycle
) (last-command 'org-cycle
))
6412 (org-cycle '(4)) (org-cycle '(4)))))
6413 (unless (eq org-startup-folded
'showeverything
)
6414 (if org-hide-block-startup
(org-hide-block-all))
6415 (org-set-visibility-according-to-property 'no-cleanup
)
6416 (org-cycle-hide-archived-subtrees 'all
)
6417 (org-cycle-hide-drawers 'all
)
6418 (org-cycle-show-empty-lines t
)))
6420 (defun org-set-visibility-according-to-property (&optional no-cleanup
)
6421 "Switch subtree visibilities according to :VISIBILITY: property."
6423 (let (org-show-entry-below state
)
6425 (goto-char (point-min))
6426 (while (re-search-forward
6427 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6429 (setq state
(match-string 1))
6431 (org-back-to-heading t
)
6435 ((equal state
'("fold" "folded"))
6437 ((equal state
"children")
6438 (org-show-hidden-entry)
6440 ((equal state
"content")
6443 (org-narrow-to-subtree)
6445 ((member state
'("all" "showall"))
6448 (org-cycle-hide-archived-subtrees 'all
)
6449 (org-cycle-hide-drawers 'all
)
6450 (org-cycle-show-empty-lines 'all
)))))
6452 ;; This function uses outline-regexp instead of the more fundamental
6453 ;; org-outline-regexp so that org-cycle-global works outside of Org
6454 ;; buffers, where outline-regexp is needed.
6455 (defun org-overview ()
6456 "Switch to overview mode, showing only top-level headlines.
6457 Really, this shows all headlines with level equal or greater than the level
6458 of the first headline in the buffer. This is important, because if the
6459 first headline is not level one, then (hide-sublevels 1) gives confusing
6462 (let ((level (save-excursion
6463 (goto-char (point-min))
6464 (if (re-search-forward (concat "^" outline-regexp
) nil t
)
6466 (goto-char (match-beginning 0))
6467 (funcall outline-level
))))))
6468 (and level
(hide-sublevels level
))))
6470 (defun org-content (&optional arg
)
6471 "Show all headlines in the buffer, like a table of contents.
6472 With numerical argument N, show content up to level N."
6475 ;; Visit all headings and show their offspring
6476 (and (integerp arg
) (org-overview))
6477 (goto-char (point-max))
6479 (while (and (progn (condition-case nil
6480 (outline-previous-visible-heading 1)
6481 (error (goto-char (point-min))))
6483 (looking-at org-outline-regexp
))
6485 (show-children (1- arg
))
6487 (if (bobp) (throw 'exit nil
))))))
6490 (defun org-optimize-window-after-visibility-change (state)
6491 "Adjust the window after a change in outline visibility.
6492 This function is the default value of the hook `org-cycle-hook'."
6493 (when (get-buffer-window (current-buffer))
6495 ((eq state
'content
) nil
)
6496 ((eq state
'all
) nil
)
6497 ((eq state
'folded
) nil
)
6498 ((eq state
'children
) (or (org-subtree-end-visible-p) (recenter 1)))
6499 ((eq state
'subtree
) (or (org-subtree-end-visible-p) (recenter 1))))))
6501 (defun org-remove-empty-overlays-at (pos)
6502 "Remove outline overlays that do not contain non-white stuff."
6505 (and (eq 'outline
(overlay-get o
'invisible
))
6506 (not (string-match "\\S-" (buffer-substring (overlay-start o
)
6508 (delete-overlay o
)))
6511 (defun org-clean-visibility-after-subtree-move ()
6512 "Fix visibility issues after moving a subtree."
6513 ;; First, find a reasonable region to look at:
6514 ;; Start two siblings above, end three below
6515 (let* ((beg (save-excursion
6516 (and (org-get-last-sibling)
6517 (org-get-last-sibling))
6519 (end (save-excursion
6520 (and (org-get-next-sibling)
6521 (org-get-next-sibling)
6522 (org-get-next-sibling))
6523 (if (org-at-heading-p)
6526 (level (looking-at "\\*+"))
6527 (re (if level
(concat "^" (regexp-quote (match-string 0)) " "))))
6530 (narrow-to-region beg end
)
6532 ;; Properly fold already folded siblings
6533 (goto-char (point-min))
6534 (while (re-search-forward re nil t
)
6535 (if (and (not (outline-invisible-p))
6537 (goto-char (point-at-eol)) (outline-invisible-p)))
6539 (org-cycle-show-empty-lines 'overview
)
6540 (org-cycle-hide-drawers 'overview
)))))
6542 (defun org-cycle-show-empty-lines (state)
6543 "Show empty lines above all visible headlines.
6544 The region to be covered depends on STATE when called through
6545 `org-cycle-hook'. Lisp program can use t for STATE to get the
6546 entire buffer covered. Note that an empty line is only shown if there
6547 are at least `org-cycle-separator-lines' empty lines before the headline."
6548 (when (not (= org-cycle-separator-lines
0))
6550 (let* ((n (abs org-cycle-separator-lines
))
6552 ((= n
1) "\\(\n[ \t]*\n\\*+\\) ")
6553 ((= n
2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6554 (t (let ((ns (number-to-string (- n
2))))
6555 (concat "^\\(?:[ \t]*\n\\)\\{" ns
"," ns
"\\}"
6556 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6559 ((memq state
'(overview contents t
))
6560 (setq beg
(point-min) end
(point-max)))
6561 ((memq state
'(children folded
))
6562 (setq beg
(point) end
(progn (org-end-of-subtree t t
)
6563 (beginning-of-line 2)
6567 (while (re-search-forward re end t
)
6568 (unless (get-char-property (match-end 1) 'invisible
)
6569 (setq e
(match-end 1))
6570 (if (< org-cycle-separator-lines
0)
6571 (setq b
(save-excursion
6572 (goto-char (match-beginning 0))
6573 (org-back-over-empty-lines)
6575 (goto-char (max (point-min) (1- (point))))
6579 (setq b
(match-beginning 1)))
6580 (outline-flag-region b e nil
)))))))
6581 ;; Never hide empty lines at the end of the file.
6583 (goto-char (point-max))
6584 (outline-previous-heading)
6585 (outline-end-of-heading)
6586 (if (and (looking-at "[ \t\n]+")
6587 (= (match-end 0) (point-max)))
6588 (outline-flag-region (point) (match-end 0) nil
))))
6590 (defun org-show-empty-lines-in-parent ()
6591 "Move to the parent and re-show empty lines before visible headlines."
6593 (let ((context (if (org-up-heading-safe) 'children
'overview
)))
6594 (org-cycle-show-empty-lines context
))))
6596 (defun org-files-list ()
6597 "Return `org-agenda-files' list, plus all open org-mode files.
6598 This is useful for operations that need to scan all of a user's
6599 open and agenda-wise Org files."
6600 (let ((files (mapcar 'expand-file-name
(org-agenda-files))))
6601 (dolist (buf (buffer-list))
6602 (with-current-buffer buf
6603 (if (and (derived-mode-p 'org-mode
) (buffer-file-name))
6604 (let ((file (expand-file-name (buffer-file-name))))
6605 (unless (member file files
)
6606 (push file files
))))))
6609 (defsubst org-entry-beginning-position
()
6610 "Return the beginning position of the current entry."
6611 (save-excursion (outline-back-to-heading t
) (point)))
6613 (defsubst org-entry-end-position
()
6614 "Return the end position of the current entry."
6615 (save-excursion (outline-next-heading) (point)))
6617 (defun org-cycle-hide-drawers (state)
6618 "Re-hide all drawers after a visibility state change."
6619 (when (and (derived-mode-p 'org-mode
)
6620 (not (memq state
'(overview folded contents
))))
6622 (let* ((globalp (memq state
'(contents all
)))
6623 (beg (if globalp
(point-min) (point)))
6624 (end (if globalp
(point-max)
6625 (if (eq state
'children
)
6626 (save-excursion (outline-next-heading) (point))
6627 (org-end-of-subtree t
)))))
6629 (while (re-search-forward org-drawer-regexp end t
)
6630 (org-flag-drawer t
))))))
6632 (defun org-cycle-hide-inline-tasks (state)
6633 "Re-hide inline task when switching to 'contents visibility state."
6634 (when (and (eq state
'contents
)
6635 (boundp 'org-inlinetask-min-level
)
6636 org-inlinetask-min-level
)
6637 (hide-sublevels (1- org-inlinetask-min-level
))))
6639 (defun org-flag-drawer (flag)
6640 "When FLAG is non-nil, hide the drawer we are within.
6641 Otherwise make it visible."
6643 (beginning-of-line 1)
6644 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6645 (let ((b (match-end 0)))
6646 (if (re-search-forward
6648 (save-excursion (outline-next-heading) (point)) t
)
6649 (outline-flag-region b
(point-at-eol) flag
)
6650 (error ":END: line missing at position %s" b
))))))
6652 (defun org-subtree-end-visible-p ()
6653 "Is the end of the current subtree visible?"
6654 (pos-visible-in-window-p
6655 (save-excursion (org-end-of-subtree t
) (point))))
6657 (defun org-first-headline-recenter (&optional N
)
6658 "Move cursor to the first headline and recenter the headline.
6659 Optional argument N means put the headline into the Nth line of the window."
6660 (goto-char (point-min))
6661 (when (re-search-forward (concat "^\\(" org-outline-regexp
"\\)") nil t
)
6663 (recenter (prefix-numeric-value N
))))
6665 ;;; Saving and restoring visibility
6667 (defun org-outline-overlay-data (&optional use-markers
)
6668 "Return a list of the locations of all outline overlays.
6669 These are overlays with the `invisible' property value `outline'.
6670 The return value is a list of cons cells, with start and stop
6671 positions for each overlay.
6672 If USE-MARKERS is set, return the positions as markers."
6679 (when (eq (overlay-get o
'invisible
) 'outline
)
6680 (setq beg
(overlay-start o
)
6681 end
(overlay-end o
))
6682 (and beg end
(> end beg
)
6684 (cons (move-marker (make-marker) beg
)
6685 (move-marker (make-marker) end
))
6687 (overlays-in (point-min) (point-max))))))))
6689 (defun org-set-outline-overlay-data (data)
6690 "Create visibility overlays for all positions in DATA.
6691 DATA should have been made by `org-outline-overlay-data'."
6698 (outline-flag-region (car c
) (cdr c
) t
))
6701 ;;; Folding of blocks
6703 (defvar org-hide-block-overlays nil
6704 "Overlays hiding blocks.")
6705 (make-variable-buffer-local 'org-hide-block-overlays
)
6707 (defun org-block-map (function &optional start end
)
6708 "Call FUNCTION at the head of all source blocks in the current buffer.
6709 Optional arguments START and END can be used to limit the range."
6710 (let ((start (or start
(point-min)))
6711 (end (or end
(point-max))))
6714 (while (and (< (point) end
) (re-search-forward org-block-regexp end t
))
6717 (goto-char (match-beginning 0))
6718 (funcall function
)))))))
6720 (defun org-hide-block-toggle-all ()
6721 "Toggle the visibility of all blocks in the current buffer."
6722 (org-block-map #'org-hide-block-toggle
))
6724 (defun org-hide-block-all ()
6725 "Fold all blocks in the current buffer."
6727 (org-show-block-all)
6728 (org-block-map #'org-hide-block-toggle-maybe
))
6730 (defun org-show-block-all ()
6731 "Unfold all blocks in the current buffer."
6733 (mapc 'delete-overlay org-hide-block-overlays
)
6734 (setq org-hide-block-overlays nil
))
6736 (defun org-hide-block-toggle-maybe ()
6737 "Toggle visibility of block at point."
6739 (let ((case-fold-search t
))
6741 (beginning-of-line 1)
6742 (looking-at org-block-regexp
))
6743 (progn (org-hide-block-toggle)
6744 t
) ;; to signal that we took action
6745 nil
))) ;; to signal that we did not
6747 (defun org-hide-block-toggle (&optional force
)
6748 "Toggle the visibility of the current block."
6752 (if (re-search-forward org-block-regexp nil t
)
6753 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6754 (end (match-end 0)) ;; end of entire body
6756 (if (memq t
(mapcar (lambda (overlay)
6757 (eq (overlay-get overlay
'invisible
)
6759 (overlays-at start
)))
6760 (if (or (not force
) (eq force
'off
))
6762 (when (member ov org-hide-block-overlays
)
6763 (setq org-hide-block-overlays
6764 (delq ov org-hide-block-overlays
)))
6765 (when (eq (overlay-get ov
'invisible
)
6767 (delete-overlay ov
)))
6768 (overlays-at start
)))
6769 (setq ov
(make-overlay start end
))
6770 (overlay-put ov
'invisible
'org-hide-block
)
6771 ;; make the block accessible to isearch
6773 ov
'isearch-open-invisible
6775 (when (member ov org-hide-block-overlays
)
6776 (setq org-hide-block-overlays
6777 (delq ov org-hide-block-overlays
)))
6778 (when (eq (overlay-get ov
'invisible
)
6780 (delete-overlay ov
))))
6781 (push ov org-hide-block-overlays
)))
6782 (error "Not looking at a source block"))))
6784 ;; org-tab-after-check-for-cycling-hook
6785 (add-hook 'org-tab-first-hook
'org-hide-block-toggle-maybe
)
6786 ;; Remove overlays when changing major mode
6787 (add-hook 'org-mode-hook
6788 (lambda () (org-add-hook 'change-major-mode-hook
6789 'org-show-block-all
'append
'local
)))
6793 (defvar org-goto-window-configuration nil
)
6794 (defvar org-goto-marker nil
)
6795 (defvar org-goto-map
6796 (let ((map (make-sparse-keymap)))
6797 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur
)) cmd
)
6798 (while (setq cmd
(pop cmds
))
6799 (substitute-key-definition cmd cmd map global-map
)))
6800 (suppress-keymap map
)
6801 (org-defkey map
"\C-m" 'org-goto-ret
)
6802 (org-defkey map
[(return)] 'org-goto-ret
)
6803 (org-defkey map
[(left)] 'org-goto-left
)
6804 (org-defkey map
[(right)] 'org-goto-right
)
6805 (org-defkey map
[(control ?g
)] 'org-goto-quit
)
6806 (org-defkey map
"\C-i" 'org-cycle
)
6807 (org-defkey map
[(tab)] 'org-cycle
)
6808 (org-defkey map
[(down)] 'outline-next-visible-heading
)
6809 (org-defkey map
[(up)] 'outline-previous-visible-heading
)
6810 (if org-goto-auto-isearch
6811 (if (fboundp 'define-key-after
)
6812 (define-key-after map
[t] 'org-goto-local-auto-isearch)
6814 (org-defkey map "q" 'org-goto-quit)
6815 (org-defkey map "n" 'outline-next-visible-heading)
6816 (org-defkey map "p" 'outline-previous-visible-heading)
6817 (org-defkey map "f" 'outline-forward-same-level)
6818 (org-defkey map "b" 'outline-backward-same-level)
6819 (org-defkey map "u" 'outline-up-heading))
6820 (org-defkey map "/" 'org-occur)
6821 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6822 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6823 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6824 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6825 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6828 (defconst org-goto-help
6829 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6830 RET=jump to location [Q]uit and return to previous location
6831 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6833 (defvar org-goto-start-pos) ; dynamically scoped parameter
6835 ;; FIXME: Docstring does not mention both interfaces
6836 (defun org-goto (&optional alternative-interface)
6837 "Look up a different location in the current file, keeping current visibility.
6839 When you want look-up or go to a different location in a
6840 document, the fastest way is often to fold the entire buffer and
6841 then dive into the tree. This method has the disadvantage, that
6842 the previous location will be folded, which may not be what you
6845 This command works around this by showing a copy of the current
6846 buffer in an indirect buffer, in overview mode. You can dive
6847 into the tree in that copy, use org-occur and incremental search
6848 to find a location. When pressing RET or `Q', the command
6849 returns to the original buffer in which the visibility is still
6850 unchanged. After RET it will also jump to the location selected
6851 in the indirect buffer and expose the headline hierarchy above.
6853 With a prefix argument, use the alternative interface: e.g. if
6854 `org-goto-interface' is 'outline use 'outline-path-completion."
6856 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6857 (org-refile-use-outline-path t)
6858 (org-refile-target-verify-function nil)
6860 (if (not alternative-interface)
6862 (if (eq org-goto-interface 'outline)
6863 'outline-path-completion
6865 (org-goto-start-pos (point))
6867 (if (eq interface 'outline)
6868 (car (org-get-location (current-buffer) org-goto-help))
6869 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6870 (org-refile-check-position pa)
6874 (org-mark-ring-push org-goto-start-pos)
6875 (goto-char selected-point)
6876 (if (or (outline-invisible-p) (org-invisible-p2))
6877 (org-show-context 'org-goto)))
6880 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6881 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6882 (defvar org-goto-local-auto-isearch-map) ; defined below
6884 (defun org-get-location (buf help)
6885 "Let the user select a location in the Org-mode buffer BUF.
6886 This function uses a recursive edit. It returns the selected position
6888 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6889 (isearch-hide-immediately nil)
6890 (isearch-search-fun-function
6891 (lambda () 'org-goto-local-search-headings))
6892 (org-goto-selected-point org-goto-exit-command)
6894 (special-display-buffer-names nil)
6895 (special-display-regexps nil)
6896 (special-display-function nil))
6898 (save-window-excursion
6899 (delete-other-windows)
6900 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6901 (org-pop-to-buffer-same-window
6903 (make-indirect-buffer (current-buffer) "*org-goto*")
6904 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6905 (with-output-to-temp-buffer "*Help*"
6907 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6908 (setq buffer-read-only nil)
6909 (let ((org-startup-truncated t)
6910 (org-startup-folded nil)
6911 (org-startup-align-all-tables nil))
6914 (setq buffer-read-only t)
6915 (if (and (boundp 'org-goto-start-pos)
6916 (integer-or-marker-p org-goto-start-pos))
6917 (let ((org-show-hierarchy-above t)
6918 (org-show-siblings t)
6919 (org-show-following-heading t))
6920 (goto-char org-goto-start-pos)
6921 (and (outline-invisible-p) (org-show-context)))
6922 (goto-char (point-min)))
6923 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6924 (message "Select location and press RET")
6925 (use-local-map org-goto-map)
6928 (kill-buffer "*org-goto*")
6929 (cons org-goto-selected-point org-goto-exit-command)))
6931 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6932 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6933 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6934 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6936 (defun org-goto-local-search-headings (string bound noerror)
6937 "Search and make sure that any matches are in headlines."
6939 (while (if isearch-forward
6940 (search-forward string bound noerror)
6941 (search-backward string bound noerror))
6942 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6943 (and (member :headline context)
6944 (not (member :tags context))))
6945 (throw 'return (point))))))
6947 (defun org-goto-local-auto-isearch ()
6950 (goto-char (point-min))
6951 (let ((keys (this-command-keys)))
6952 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6954 (isearch-process-search-char (string-to-char keys)))))
6956 (defun org-goto-ret (&optional arg)
6957 "Finish `org-goto' by going to the new location."
6959 (setq org-goto-selected-point (point)
6960 org-goto-exit-command 'return)
6963 (defun org-goto-left ()
6964 "Finish `org-goto' by going to the new location."
6966 (if (org-at-heading-p)
6968 (beginning-of-line 1)
6969 (setq org-goto-selected-point (point)
6970 org-goto-exit-command 'left)
6972 (error "Not on a heading")))
6974 (defun org-goto-right ()
6975 "Finish `org-goto' by going to the new location."
6977 (if (org-at-heading-p)
6979 (setq org-goto-selected-point (point)
6980 org-goto-exit-command 'right)
6982 (error "Not on a heading")))
6984 (defun org-goto-quit ()
6985 "Finish `org-goto' without cursor motion."
6987 (setq org-goto-selected-point nil)
6988 (setq org-goto-exit-command 'quit)
6991 ;;; Indirect buffer display of subtrees
6993 (defvar org-indirect-dedicated-frame nil
6994 "This is the frame being used for indirect tree display.")
6995 (defvar org-last-indirect-buffer nil)
6997 (defun org-tree-to-indirect-buffer (&optional arg)
6998 "Create indirect buffer and narrow it to current subtree.
6999 With a numerical prefix ARG, go up to this level and then take that tree.
7000 If ARG is negative, go up that many levels.
7002 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7003 indirect buffer previously made with this command, to avoid proliferation of
7004 indirect buffers. However, when you call the command with a \
7005 \\[universal-argument] prefix, or
7006 when `org-indirect-buffer-display' is `new-frame', the last buffer
7007 is kept so that you can work with several indirect buffers at the same time.
7008 If `org-indirect-buffer-display' is `dedicated-frame', the \
7009 \\[universal-argument] prefix also
7010 requests that a new frame be made for the new buffer, so that the dedicated
7011 frame is not changed."
7013 (let ((cbuf (current-buffer))
7014 (cwin (selected-window))
7016 beg end level heading ibuf)
7018 (org-back-to-heading t)
7020 (setq level (org-outline-level))
7021 (if (< arg 0) (setq arg (+ level arg)))
7022 (while (> (setq level (org-outline-level)) arg)
7023 (org-up-heading-safe)))
7025 heading (org-get-heading))
7026 (org-end-of-subtree t t)
7027 (if (org-at-heading-p) (backward-char 1))
7029 (if (and (buffer-live-p org-last-indirect-buffer)
7030 (not (eq org-indirect-buffer-display 'new-frame))
7032 (kill-buffer org-last-indirect-buffer))
7033 (setq ibuf (org-get-indirect-buffer cbuf)
7034 org-last-indirect-buffer ibuf)
7036 ((or (eq org-indirect-buffer-display 'new-frame)
7037 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7038 (select-frame (make-frame))
7039 (delete-other-windows)
7040 (org-pop-to-buffer-same-window ibuf)
7041 (org-set-frame-title heading))
7042 ((eq org-indirect-buffer-display 'dedicated-frame)
7044 (select-frame (or (and org-indirect-dedicated-frame
7045 (frame-live-p org-indirect-dedicated-frame)
7046 org-indirect-dedicated-frame)
7047 (setq org-indirect-dedicated-frame (make-frame)))))
7048 (delete-other-windows)
7049 (org-pop-to-buffer-same-window ibuf)
7050 (org-set-frame-title (concat "Indirect: " heading)))
7051 ((eq org-indirect-buffer-display 'current-window)
7052 (org-pop-to-buffer-same-window ibuf))
7053 ((eq org-indirect-buffer-display 'other-window)
7054 (pop-to-buffer ibuf))
7055 (t (error "Invalid value")))
7056 (if (featurep 'xemacs)
7057 (save-excursion (org-mode) (turn-on-font-lock)))
7058 (narrow-to-region beg end)
7061 (run-hook-with-args 'org-cycle-hook 'all)
7062 (and (window-live-p cwin) (select-window cwin))))
7064 (defun org-get-indirect-buffer (&optional buffer)
7065 (setq buffer (or buffer (current-buffer)))
7066 (let ((n 1) (base (buffer-name buffer)) bname)
7067 (while (buffer-live-p
7068 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7071 (make-indirect-buffer buffer bname 'clone)
7072 (error (make-indirect-buffer buffer bname)))))
7074 (defun org-set-frame-title (title)
7075 "Set the title of the current frame to the string TITLE."
7076 ;; FIXME: how to name a single frame in XEmacs???
7077 (unless (featurep 'xemacs)
7078 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7080 ;;;; Structure editing
7082 ;;; Inserting headlines
7084 (defun org-previous-line-empty-p ()
7087 (or (beginning-of-line 0) t)
7089 (looking-at "[ \t]*$")))))
7091 (defun org-insert-heading (&optional force-heading invisible-ok)
7092 "Insert a new heading or item with same depth at point.
7093 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7094 If point is at the beginning of a headline, insert a sibling before the
7095 current headline. If point is not at the beginning, split the line,
7096 create the new headline with the text in the current line after point
7097 \(but see also the variable `org-M-RET-may-split-line').
7099 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7100 This is important for non-interactive uses of the command."
7102 (if (or (= (buffer-size) 0)
7103 (and (not (save-excursion
7104 (and (ignore-errors (org-back-to-heading invisible-ok))
7105 (org-at-heading-p))))
7106 (or force-heading (not (org-in-item-p)))))
7109 (run-hooks 'org-insert-heading-hook))
7110 (when (or force-heading (not (org-insert-item)))
7111 (let* ((empty-line-p nil)
7113 (on-heading (org-at-heading-p))
7114 (head (save-excursion
7117 (org-back-to-heading invisible-ok)
7118 (when (and (not on-heading)
7119 (featurep 'org-inlinetask)
7120 (integerp org-inlinetask-min-level)
7121 (>= (length (match-string 0))
7122 org-inlinetask-min-level))
7123 ;; Find a heading level before the inline task
7124 (while (and (setq level (org-up-heading-safe))
7125 (>= level org-inlinetask-min-level)))
7126 (if (org-at-heading-p)
7127 (org-back-to-heading invisible-ok)
7128 (error "This should not happen")))
7129 (setq empty-line-p (org-previous-line-empty-p))
7132 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7133 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7134 pos hide-previous previous-pos)
7136 ((and (org-at-heading-p) (bolp)
7138 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7139 ;; insert before the current line
7140 (open-line (if blank 2 1)))
7142 (not org-insert-heading-respect-content)
7145 (backward-char 1) (not (outline-invisible-p)))))
7146 ;; insert right here
7149 ;; somewhere in the line
7151 (setq previous-pos (point-at-bol))
7153 (setq hide-previous (outline-invisible-p)))
7154 (and org-insert-heading-respect-content (org-show-subtree))
7156 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7159 (goto-char (point-at-bol))
7160 (and (looking-at org-complex-heading-regexp)
7162 (> p (match-beginning 4)))))))
7165 (org-insert-heading-respect-content
7166 (org-end-of-subtree nil t)
7167 (when (featurep 'org-inlinetask)
7168 (while (and (not (eobp))
7169 (looking-at "\\(\\*+\\)[ \t]+")
7170 (>= (length (match-string 1))
7171 org-inlinetask-min-level))
7172 (org-end-of-subtree nil t)))
7173 (or (bolp) (newline))
7174 (or (org-previous-line-empty-p)
7175 (and blank (newline)))
7181 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7182 (setq tags (and (match-end 2) (match-string 2)))
7184 (delete-region (match-beginning 1) (match-end 1)))
7185 (setq pos (point-at-bol))
7186 (or split (end-of-line 1))
7187 (delete-horizontal-space)
7188 (if (string-match "\\`\\*+\\'"
7189 (buffer-substring (point-at-bol) (point)))
7191 (newline (if blank 2 1))
7197 (org-set-tags nil 'align))))
7199 (or split (end-of-line 1))
7200 (newline (if blank 2 1)))))))
7201 (insert head) (just-one-space)
7204 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7205 (when (and org-insert-heading-respect-content hide-previous)
7207 (goto-char previous-pos)
7209 (run-hooks 'org-insert-heading-hook)))))
7211 (defun org-get-heading (&optional no-tags no-todo)
7212 "Return the heading of the current entry, without the stars.
7213 When NO-TAGS is non-nil, don't include tags.
7214 When NO-TODO is non-nil, don't include TODO keywords."
7216 (org-back-to-heading t)
7218 ((and no-tags no-todo)
7219 (looking-at org-complex-heading-regexp)
7222 (looking-at (concat org-outline-regexp
7224 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7227 (looking-at org-todo-line-regexp)
7229 (t (looking-at org-heading-regexp)
7230 (match-string 2)))))
7232 (defun org-heading-components ()
7233 "Return the components of the current heading.
7234 This is a list with the following elements:
7235 - the level as an integer
7236 - the reduced level, different if `org-odd-levels-only' is set.
7237 - the TODO keyword, or nil
7238 - the priority character, like ?A, or nil if no priority is given
7239 - the headline text itself, or the tags string if no headline text
7240 - the tags string, or nil."
7242 (org-back-to-heading t)
7243 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7244 (list (length (match-string 1))
7245 (org-reduced-level (length (match-string 1)))
7246 (org-match-string-no-properties 2)
7247 (and (match-end 3) (aref (match-string 3) 2))
7248 (org-match-string-no-properties 4)
7249 (org-match-string-no-properties 5)))))
7251 (defun org-get-entry ()
7252 "Get the entry text, after heading, entire subtree."
7254 (org-back-to-heading t)
7255 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7257 (defun org-insert-heading-after-current ()
7258 "Insert a new heading with same level as current, after current subtree."
7260 (org-back-to-heading)
7261 (org-insert-heading)
7262 (org-move-subtree-down)
7265 (defun org-insert-heading-respect-content ()
7267 (let ((org-insert-heading-respect-content t))
7268 (org-insert-heading t)))
7270 (defun org-insert-todo-heading-respect-content (&optional force-state)
7272 (let ((org-insert-heading-respect-content t))
7273 (org-insert-todo-heading force-state t)))
7275 (defun org-insert-todo-heading (arg &optional force-heading)
7276 "Insert a new heading with the same level and TODO state as current heading.
7277 If the heading has no TODO state, or if the state is DONE, use the first
7278 state (TODO by default). Also with prefix arg, force first state."
7280 (when (or force-heading (not (org-insert-item 'checkbox)))
7281 (org-insert-heading force-heading)
7283 (org-back-to-heading)
7284 (outline-previous-heading)
7285 (looking-at org-todo-line-regexp))
7289 (not (match-beginning 2))
7290 (member (match-string 2) org-done-keywords))
7291 (car org-todo-keywords-1)
7295 (run-hook-with-args-until-success
7296 'org-todo-get-default-hook new-mark-x nil)
7298 (beginning-of-line 1)
7299 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7300 (if org-treat-insert-todo-heading-as-state-change
7302 (insert new-mark " "))))
7303 (when org-provide-todo-statistics
7304 (org-update-parent-todo-statistics))))
7306 (defun org-insert-subheading (arg)
7307 "Insert a new subheading and demote it.
7308 Works for outline headings and for plain lists alike."
7310 (org-insert-heading arg)
7312 ((org-at-heading-p) (org-do-demote))
7313 ((org-at-item-p) (org-indent-item))))
7315 (defun org-insert-todo-subheading (arg)
7316 "Insert a new subheading with TODO keyword or checkbox and demote it.
7317 Works for outline headings and for plain lists alike."
7319 (org-insert-todo-heading arg)
7321 ((org-at-heading-p) (org-do-demote))
7322 ((org-at-item-p) (org-indent-item))))
7324 ;;; Promotion and Demotion
7326 (defvar org-after-demote-entry-hook nil
7327 "Hook run after an entry has been demoted.
7328 The cursor will be at the beginning of the entry.
7329 When a subtree is being demoted, the hook will be called for each node.")
7331 (defvar org-after-promote-entry-hook nil
7332 "Hook run after an entry has been promoted.
7333 The cursor will be at the beginning of the entry.
7334 When a subtree is being promoted, the hook will be called for each node.")
7336 (defun org-promote-subtree ()
7337 "Promote the entire subtree.
7338 See also `org-promote'."
7341 (org-with-limited-levels (org-map-tree 'org-promote)))
7342 (org-fix-position-after-promote))
7344 (defun org-demote-subtree ()
7345 "Demote the entire subtree. See `org-demote'.
7346 See also `org-promote'."
7349 (org-with-limited-levels (org-map-tree 'org-demote)))
7350 (org-fix-position-after-promote))
7353 (defun org-do-promote ()
7354 "Promote the current heading higher up the tree.
7355 If the region is active in `transient-mark-mode', promote all headings
7359 (if (org-region-active-p)
7360 (org-map-region 'org-promote (region-beginning) (region-end))
7362 (org-fix-position-after-promote))
7364 (defun org-do-demote ()
7365 "Demote the current heading lower down the tree.
7366 If the region is active in `transient-mark-mode', demote all headings
7370 (if (org-region-active-p)
7371 (org-map-region 'org-demote (region-beginning) (region-end))
7373 (org-fix-position-after-promote))
7375 (defun org-fix-position-after-promote ()
7376 "Make sure that after pro/demotion cursor position is right."
7377 (let ((pos (point)))
7378 (when (save-excursion
7379 (beginning-of-line 1)
7380 (looking-at org-todo-line-regexp)
7381 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7382 (cond ((eobp) (insert " "))
7383 ((eolp) (insert " "))
7384 ((equal (char-after) ?\ ) (forward-char 1))))))
7386 (defun org-current-level ()
7387 "Return the level of the current entry, or nil if before the first headline.
7388 The level is the number of stars at the beginning of the headline."
7390 (org-with-limited-levels
7391 (if (ignore-errors (org-back-to-heading t))
7392 (funcall outline-level)))))
7394 (defun org-get-previous-line-level ()
7395 "Return the outline depth of the last headline before the current line.
7396 Returns 0 for the first headline in the buffer, and nil if before the
7398 (let ((current-level (org-current-level))
7399 (prev-level (when (> (line-number-at-pos) 1)
7401 (beginning-of-line 0)
7402 (org-current-level)))))
7403 (cond ((null current-level) nil) ; Before first headline
7404 ((null prev-level) 0) ; At first headline
7407 (defun org-reduced-level (l)
7408 "Compute the effective level of a heading.
7409 This takes into account the setting of `org-odd-levels-only'."
7412 (org-odd-levels-only (1+ (floor (/ l 2))))
7415 (defun org-level-increment ()
7416 "Return the number of stars that will be added or removed at a
7417 time to headlines when structure editing, based on the value of
7418 `org-odd-levels-only'."
7419 (if org-odd-levels-only 2 1))
7421 (defun org-get-valid-level (level &optional change)
7422 "Rectify a level change under the influence of `org-odd-levels-only'
7423 LEVEL is a current level, CHANGE is by how much the level should be
7424 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7425 even level numbers will become the next higher odd number."
7426 (if org-odd-levels-only
7427 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7428 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7429 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7430 (max 1 (+ level (or change 0)))))
7432 (if (boundp 'define-obsolete-function-alias)
7433 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7434 (define-obsolete-function-alias 'org-get-legal-level
7435 'org-get-valid-level)
7436 (define-obsolete-function-alias 'org-get-legal-level
7437 'org-get-valid-level "23.1")))
7439 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7440 ;; ̀org-with-limited-levels'
7441 (defun org-promote ()
7442 "Promote the current heading higher up the tree.
7443 If the region is active in `transient-mark-mode', promote all headings
7445 (org-back-to-heading t)
7446 (let* ((level (save-match-data (funcall outline-level)))
7447 (after-change-functions (remove 'flyspell-after-change-function
7448 after-change-functions))
7449 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7450 (diff (abs (- level (length up-head) -1))))
7451 (cond ((and (= level 1) org-called-with-limited-levels
7452 org-allow-promoting-top-level-subtree)
7453 (replace-match "# " nil t))
7455 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7456 (t (replace-match up-head nil t)))
7457 ;; Fixup tag positioning
7459 (and org-auto-align-tags (org-set-tags nil t))
7460 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7461 (run-hooks 'org-after-promote-entry-hook)))
7463 (defun org-demote ()
7464 "Demote the current heading lower down the tree.
7465 If the region is active in `transient-mark-mode', demote all headings
7467 (org-back-to-heading t)
7468 (let* ((level (save-match-data (funcall outline-level)))
7469 (after-change-functions (remove 'flyspell-after-change-function
7470 after-change-functions))
7471 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7472 (diff (abs (- level (length down-head) -1))))
7473 (replace-match down-head nil t)
7474 ;; Fixup tag positioning
7475 (and org-auto-align-tags (org-set-tags nil t))
7476 (if org-adapt-indentation (org-fixup-indentation diff))
7477 (run-hooks 'org-after-demote-entry-hook)))
7479 (defun org-cycle-level ()
7480 "Cycle the level of an empty headline through possible states.
7481 This goes first to child, then to parent, level, then up the hierarchy.
7482 After top level, it switches back to sibling level."
7484 (let ((org-adapt-indentation nil))
7485 (when (org-point-at-end-of-empty-headline)
7486 (setq this-command 'org-cycle-level) ; Only needed for caching
7487 (let ((cur-level (org-current-level))
7488 (prev-level (org-get-previous-line-level)))
7490 ;; If first headline in file, promote to top-level.
7492 (loop repeat (/ (- cur-level 1) (org-level-increment))
7493 do (org-do-promote)))
7494 ;; If same level as prev, demote one.
7495 ((= prev-level cur-level)
7497 ;; If parent is top-level, promote to top level if not already.
7499 (loop repeat (/ (- cur-level 1) (org-level-increment))
7500 do (org-do-promote)))
7501 ;; If top-level, return to prev-level.
7503 (loop repeat (/ (- prev-level 1) (org-level-increment))
7504 do (org-do-demote)))
7505 ;; If less than prev-level, promote one.
7506 ((< cur-level prev-level)
7508 ;; If deeper than prev-level, promote until higher than
7510 ((> cur-level prev-level)
7511 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7512 do (org-do-promote))))
7515 (defun org-map-tree (fun)
7516 "Call FUN for every heading underneath the current one."
7517 (org-back-to-heading)
7518 (let ((level (funcall outline-level)))
7522 (outline-next-heading)
7523 (> (funcall outline-level) level))
7527 (defun org-map-region (fun beg end)
7528 "Call FUN for every heading between BEG and END."
7529 (let ((org-ignore-region t))
7531 (setq end (copy-marker end))
7533 (if (and (re-search-forward org-outline-regexp-bol nil t)
7537 (outline-next-heading)
7542 (defvar org-property-end-re) ; silence byte-compiler
7543 (defun org-fixup-indentation (diff)
7544 "Change the indentation in the current entry by DIFF.
7545 However, if any line in the current entry has no indentation, or if it
7546 would end up with no indentation after the change, nothing at all is done."
7548 (let ((end (save-excursion (outline-next-heading)
7550 (prohibit (if (> diff 0)
7552 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7554 (unless (save-excursion (end-of-line 1)
7555 (re-search-forward prohibit end t))
7556 (while (and (< (point) end)
7557 (re-search-forward "^[ \t]+" end t))
7558 (goto-char (match-end 0))
7559 (setq col (current-column))
7560 (if (< diff 0) (replace-match ""))
7561 (org-indent-to-column (+ diff col))))
7562 (move-marker end nil))))
7564 (defun org-convert-to-odd-levels ()
7565 "Convert an org-mode file with all levels allowed to one with odd levels.
7566 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7569 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7570 (let ((outline-level 'org-outline-level)
7571 (org-odd-levels-only nil) n)
7573 (goto-char (point-min))
7574 (while (re-search-forward "^\\*\\*+ " nil t)
7575 (setq n (- (length (match-string 0)) 2))
7576 (while (>= (setq n (1- n)) 0)
7578 (end-of-line 1))))))
7580 (defun org-convert-to-oddeven-levels ()
7581 "Convert an org-mode file with only odd levels to one with odd/even levels.
7582 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7583 file contains a section with an even level, conversion would
7584 destroy the structure of the file. An error is signaled in this
7587 (goto-char (point-min))
7588 ;; First check if there are no even levels
7589 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7590 (org-show-context t)
7591 (error "Not all levels are odd in this file. Conversion not possible"))
7592 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7593 (let ((outline-regexp org-outline-regexp)
7594 (outline-level 'org-outline-level)
7595 (org-odd-levels-only nil) n)
7597 (goto-char (point-min))
7598 (while (re-search-forward "^\\*\\*+ " nil t)
7599 (setq n (/ (1- (length (match-string 0))) 2))
7600 (while (>= (setq n (1- n)) 0)
7602 (end-of-line 1))))))
7604 (defun org-tr-level (n)
7605 "Make N odd if required."
7606 (if org-odd-levels-only (1+ (/ n 2)) n))
7608 ;;; Vertical tree motion, cutting and pasting of subtrees
7610 (defun org-move-subtree-up (&optional arg)
7611 "Move the current subtree up past ARG headlines of the same level."
7613 (org-move-subtree-down (- (prefix-numeric-value arg))))
7615 (defun org-move-subtree-down (&optional arg)
7616 "Move the current subtree down past ARG headlines of the same level."
7618 (setq arg (prefix-numeric-value arg))
7619 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7620 'org-get-last-sibling))
7621 (ins-point (make-marker))
7623 (col (current-column))
7624 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7626 (org-back-to-heading)
7629 (setq ne-beg (org-back-over-empty-lines))
7632 (save-excursion (outline-end-of-heading)
7633 (setq folded (outline-invisible-p)))
7634 (outline-end-of-subtree))
7635 (outline-next-heading)
7636 (setq ne-end (org-back-over-empty-lines))
7639 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7640 ;; include less whitespace
7643 (forward-line (- ne-beg ne-end))
7644 (setq beg (point))))
7645 ;; Find insertion point, with error handling
7647 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7648 (progn (goto-char beg0)
7649 (error "Cannot move past superior level or buffer limit")))
7650 (setq cnt (1- cnt)))
7652 ;; Moving forward - still need to move over subtree
7653 (progn (org-end-of-subtree t t)
7655 (org-back-over-empty-lines)
7656 (or (bolp) (newline)))))
7657 (setq ne-ins (org-back-over-empty-lines))
7658 (move-marker ins-point (point))
7659 (setq txt (buffer-substring beg end))
7660 (org-save-markers-in-region beg end)
7661 (delete-region beg end)
7662 (org-remove-empty-overlays-at beg)
7663 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7664 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7665 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7666 (let ((bbb (point)))
7667 (insert-before-markers txt)
7668 (org-reinstall-markers-in-region bbb)
7669 (move-marker ins-point bbb))
7670 (or (bolp) (insert "\n"))
7671 (setq ins-end (point))
7672 (goto-char ins-point)
7673 (org-skip-whitespace)
7674 (when (and (< arg 0)
7675 (org-first-sibling-p)
7677 ;; Move whitespace back to beginning
7680 (let ((kill-whole-line t))
7681 (kill-line (- ne-ins ne-beg)) (point)))
7682 (insert (make-string (- ne-ins ne-beg) ?\n)))
7683 (move-marker ins-point nil)
7688 (org-cycle-hide-drawers 'children))
7689 (org-clean-visibility-after-subtree-move)
7690 ;; move back to the initial column we were at
7691 (move-to-column col)))
7693 (defvar org-subtree-clip ""
7694 "Clipboard for cut and paste of subtrees.
7695 This is actually only a copy of the kill, because we use the normal kill
7696 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7698 (defvar org-subtree-clip-folded nil
7699 "Was the last copied subtree folded?
7700 This is used to fold the tree back after pasting.")
7702 (defun org-cut-subtree (&optional n)
7703 "Cut the current subtree into the clipboard.
7704 With prefix arg N, cut this many sequential subtrees.
7705 This is a short-hand for marking the subtree and then cutting it."
7707 (org-copy-subtree n 'cut))
7709 (defun org-copy-subtree (&optional n cut force-store-markers)
7710 "Cut the current subtree into the clipboard.
7711 With prefix arg N, cut this many sequential subtrees.
7712 This is a short-hand for marking the subtree and then copying it.
7713 If CUT is non-nil, actually cut the subtree.
7714 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7715 of some markers in the region, even if CUT is non-nil. This is
7716 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7718 (let (beg end folded (beg0 (point)))
7719 (if (org-called-interactively-p 'any)
7720 (org-back-to-heading nil) ; take what looks like a subtree
7721 (org-back-to-heading t)) ; take what is really there
7722 (org-back-over-empty-lines)
7724 (skip-chars-forward " \t\r\n")
7726 (save-excursion (outline-end-of-heading)
7727 (setq folded (outline-invisible-p)))
7729 (org-forward-heading-same-level (1- n) t)
7731 (org-end-of-subtree t t))
7732 (org-back-over-empty-lines)
7736 (setq org-subtree-clip-folded folded)
7737 (when (or cut force-store-markers)
7738 (org-save-markers-in-region beg end))
7739 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7740 (setq org-subtree-clip (current-kill 0))
7741 (message "%s: Subtree(s) with %d characters"
7742 (if cut "Cut" "Copied")
7743 (length org-subtree-clip)))))
7745 (defun org-paste-subtree (&optional level tree for-yank)
7746 "Paste the clipboard as a subtree, with modification of headline level.
7747 The entire subtree is promoted or demoted in order to match a new headline
7750 If the cursor is at the beginning of a headline, the same level as
7751 that headline is used to paste the tree
7753 If not, the new level is derived from the *visible* headings
7754 before and after the insertion point, and taken to be the inferior headline
7755 level of the two. So if the previous visible heading is level 3 and the
7756 next is level 4 (or vice versa), level 4 will be used for insertion.
7757 This makes sure that the subtree remains an independent subtree and does
7758 not swallow low level entries.
7760 You can also force a different level, either by using a numeric prefix
7761 argument, or by inserting the heading marker by hand. For example, if the
7762 cursor is after \"*****\", then the tree will be shifted to level 5.
7764 If optional TREE is given, use this text instead of the kill ring.
7766 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7767 move back over whitespace before inserting, and move point to the end of
7768 the inserted text when done."
7770 (setq tree (or tree (and kill-ring (current-kill 0))))
7771 (unless (org-kill-is-subtree-p tree)
7773 (substitute-command-keys
7774 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7775 (org-with-limited-levels
7776 (let* ((visp (not (outline-invisible-p)))
7778 (^re_ "\\(\\*+\\)[ \t]*")
7779 (old-level (if (string-match org-outline-regexp-bol txt)
7780 (- (match-end 0) (match-beginning 0) 1)
7782 (force-level (cond (level (prefix-numeric-value level))
7783 ((and (looking-at "[ \t]*$")
7785 "^\\*+$" (buffer-substring
7786 (point-at-bol) (point))))
7787 (- (match-end 1) (match-beginning 1)))
7789 (looking-at org-outline-regexp))
7790 (- (match-end 0) (point) 1))))
7791 (previous-level (save-excursion
7794 (outline-previous-visible-heading 1)
7795 (if (looking-at ^re_)
7796 (- (match-end 0) (match-beginning 0) 1)
7799 (next-level (save-excursion
7802 (or (looking-at org-outline-regexp)
7803 (outline-next-visible-heading 1))
7804 (if (looking-at ^re_)
7805 (- (match-end 0) (match-beginning 0) 1)
7808 (new-level (or force-level (max previous-level next-level)))
7809 (shift (if (or (= old-level -1)
7811 (= old-level new-level))
7813 (- new-level old-level)))
7814 (delta (if (> shift 0) -1 1))
7815 (func (if (> shift 0) 'org-demote 'org-promote))
7816 (org-odd-levels-only nil)
7818 ;; Remove the forced level indicator
7820 (delete-region (point-at-bol) (point)))
7822 (beginning-of-line (if (bolp) 1 2))
7823 (unless for-yank (org-back-over-empty-lines))
7825 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7826 (insert-before-markers txt)
7827 (unless (string-match "\n\\'" txt) (insert "\n"))
7828 (setq newend (point))
7829 (org-reinstall-markers-in-region beg)
7832 (skip-chars-forward " \t\n\r")
7834 (if (and (outline-invisible-p) visp)
7835 (save-excursion (outline-show-heading)))
7836 ;; Shift if necessary
7839 (narrow-to-region beg end)
7840 (while (not (= shift 0))
7841 (org-map-region func (point-min) (point-max))
7842 (setq shift (+ delta shift)))
7843 (goto-char (point-min))
7844 (setq newend (point-max))))
7845 (when (or (org-called-interactively-p 'interactive) for-yank)
7846 (message "Clipboard pasted as level %d subtree" new-level))
7847 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7849 (eq org-subtree-clip (current-kill 0))
7850 org-subtree-clip-folded)
7851 ;; The tree was folded before it was killed/copied
7853 (and for-yank (goto-char newend)))))
7855 (defun org-kill-is-subtree-p (&optional txt)
7856 "Check if the current kill is an outline subtree, or a set of trees.
7857 Returns nil if kill does not start with a headline, or if the first
7858 headline level is not the largest headline level in the tree.
7859 So this will actually accept several entries of equal levels as well,
7860 which is OK for `org-paste-subtree'.
7861 If optional TXT is given, check this string instead of the current kill."
7862 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7863 (re (org-get-limited-outline-regexp))
7864 (^re (concat "^" re))
7865 (start-level (and kill
7867 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7869 (- (match-end 2) (match-beginning 2) 1)))
7870 (start (1+ (or (match-beginning 2) -1))))
7871 (if (not start-level)
7873 nil) ;; does not even start with a heading
7875 (while (setq start (string-match ^re kill (1+ start)))
7876 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7880 (defvar org-markers-to-move nil
7881 "Markers that should be moved with a cut-and-paste operation.
7882 Those markers are stored together with their positions relative to
7883 the start of the region.")
7885 (defun org-save-markers-in-region (beg end)
7886 "Check markers in region.
7887 If these markers are between BEG and END, record their position relative
7888 to BEG, so that after moving the block of text, we can put the markers back
7890 This function gets called just before an entry or tree gets cut from the
7891 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7892 called immediately, to move the markers with the entries."
7893 (setq org-markers-to-move nil)
7894 (when (featurep 'org-clock)
7895 (org-clock-save-markers-for-cut-and-paste beg end))
7896 (when (featurep 'org-agenda)
7897 (org-agenda-save-markers-for-cut-and-paste beg end)))
7899 (defun org-check-and-save-marker (marker beg end)
7900 "Check if MARKER is between BEG and END.
7901 If yes, remember the marker and the distance to BEG."
7902 (when (and (marker-buffer marker)
7903 (equal (marker-buffer marker) (current-buffer)))
7904 (if (and (>= marker beg) (< marker end))
7905 (push (cons marker (- marker beg)) org-markers-to-move))))
7907 (defun org-reinstall-markers-in-region (beg)
7908 "Move all remembered markers to their position relative to BEG."
7910 (move-marker (car x) (+ beg (cdr x))))
7911 org-markers-to-move)
7912 (setq org-markers-to-move nil))
7914 (defun org-narrow-to-subtree ()
7915 "Narrow buffer to the current subtree."
7919 (org-with-limited-levels
7921 (progn (org-back-to-heading t) (point))
7922 (progn (org-end-of-subtree t t)
7923 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
7926 (defun org-narrow-to-block ()
7927 "Narrow buffer to the current block."
7929 (let* ((case-fold-search t)
7930 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
7931 "^[ \t]*#\\+end_.*")))
7933 (narrow-to-region (car blockp) (cdr blockp))
7934 (error "Not in a block"))))
7937 (defvar org-property-drawer-re))
7939 (defvar org-property-start-re) ;; defined below
7940 (defun org-clone-subtree-with-time-shift (n &optional shift)
7941 "Clone the task (subtree) at point N times.
7942 The clones will be inserted as siblings.
7944 In interactive use, the user will be prompted for the number of
7945 clones to be produced, and for a time SHIFT, which may be a
7946 repeater as used in time stamps, for example `+3d'.
7948 When a valid repeater is given and the entry contains any time
7949 stamps, the clones will become a sequence in time, with time
7950 stamps in the subtree shifted for each clone produced. If SHIFT
7951 is nil or the empty string, time stamps will be left alone. The
7952 ID property of the original subtree is removed.
7954 If the original subtree did contain time stamps with a repeater,
7955 the following will happen:
7956 - the repeater will be removed in each clone
7957 - an additional clone will be produced, with the current, unshifted
7958 date(s) in the entry.
7959 - the original entry will be placed *after* all the clones, with
7961 - the start days in the repeater in the original entry will be shifted
7962 to past the last clone.
7963 In this way you can spell out a number of instances of a repeating task,
7964 and still retain the repeater to cover future instances of the task."
7965 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7966 (let (beg end template task idprop
7967 shift-n shift-what doshift nmin nmax (n-no-remove -1)
7968 (drawer-re org-drawer-regexp))
7969 (if (not (and (integerp n) (> n 0)))
7970 (error "Invalid number of replications %s" n))
7971 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7972 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
7974 (error "Invalid shift specification %s" shift))
7976 (setq shift-n (string-to-number (match-string 1 shift))
7977 shift-what (cdr (assoc (match-string 2 shift)
7978 '(("d" . day) ("w" . week)
7979 ("m" . month) ("y" . year))))))
7980 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7981 (setq nmin 1 nmax n)
7982 (org-back-to-heading t)
7984 (setq idprop (org-entry-get nil "ID"))
7985 (org-end-of-subtree t t)
7986 (or (bolp) (insert "\n"))
7988 (setq template (buffer-substring beg end))
7990 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
7991 (delete-region beg end)
7993 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7995 (loop for n from nmin to nmax do
8000 (goto-char (point-min))
8002 (and idprop (if org-clone-delete-id
8003 (org-entry-delete nil "ID")
8004 (org-id-get-create t)))
8006 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8008 (goto-char (point-min))
8009 (while (re-search-forward drawer-re nil t)
8011 (org-remove-empty-drawer-at d (point))) org-drawers)))
8012 (goto-char (point-min))
8014 (while (re-search-forward org-ts-regexp-both nil t)
8015 (org-timestamp-change (* n shift-n) shift-what))
8016 (unless (= n n-no-remove)
8017 (goto-char (point-min))
8018 (while (re-search-forward org-ts-regexp nil t)
8020 (goto-char (match-beginning 0))
8021 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8022 (delete-region (match-beginning 1) (match-end 1)))))))
8023 (setq task (buffer-string)))
8029 (defun org-sort (with-case)
8030 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8031 Optional argument WITH-CASE means sort case-sensitively."
8034 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8035 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8037 (org-call-with-arg 'org-sort-entries with-case))))
8039 (defun org-sort-remove-invisible (s)
8040 (remove-text-properties 0 (length s) org-rm-props s)
8041 (while (string-match org-bracket-link-regexp s)
8042 (setq s (replace-match (if (match-end 2)
8044 (match-string 1 s)) t t s)))
8047 (defvar org-priority-regexp) ; defined later in the file
8049 (defvar org-after-sorting-entries-or-items-hook nil
8050 "Hook that is run after a bunch of entries or items have been sorted.
8051 When children are sorted, the cursor is in the parent line when this
8052 hook gets called. When a region or a plain list is sorted, the cursor
8053 will be in the first entry of the sorted region/list.")
8055 (defun org-sort-entries
8056 (&optional with-case sorting-type getkey-func compare-func property)
8057 "Sort entries on a certain level of an outline tree.
8058 If there is an active region, the entries in the region are sorted.
8059 Else, if the cursor is before the first entry, sort the top-level items.
8060 Else, the children of the entry at point are sorted.
8062 Sorting can be alphabetically, numerically, by date/time as given by
8063 a time stamp, by a property or by priority.
8065 The command prompts for the sorting type unless it has been given to the
8066 function through the SORTING-TYPE argument, which needs to be a character,
8067 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8068 precise meaning of each character:
8070 n Numerically, by converting the beginning of the entry/item to a number.
8071 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8072 t By date/time, either the first active time stamp in the entry, or, if
8073 none exist, by the first inactive one.
8074 s By the scheduled date/time.
8075 d By deadline date/time.
8076 c By creation time, which is assumed to be the first inactive time stamp
8077 at the beginning of a line.
8078 p By priority according to the cookie.
8079 r By the value of a property.
8081 Capital letters will reverse the sort order.
8083 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8084 called with point at the beginning of the record. It must return either
8085 a string or a number that should serve as the sorting key for that record.
8087 Comparing entries ignores case by default. However, with an optional argument
8088 WITH-CASE, the sorting considers case as well."
8090 (let ((case-func (if with-case 'identity 'downcase))
8091 start beg end stars re re2
8093 ;; Find beginning and end of region to sort
8095 ((org-region-active-p)
8096 ;; we will sort the region
8097 (setq end (region-end)
8099 (goto-char (region-beginning))
8100 (if (not (org-at-heading-p)) (outline-next-heading))
8101 (setq start (point)))
8102 ((or (org-at-heading-p)
8103 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8104 ;; we will sort the children of the current headline
8105 (org-back-to-heading)
8107 end (progn (org-end-of-subtree t t)
8108 (or (bolp) (insert "\n"))
8109 (org-back-over-empty-lines)
8114 (outline-next-heading))
8116 ;; we will sort the top-level entries in this file
8117 (goto-char (point-min))
8118 (or (org-at-heading-p) (outline-next-heading))
8119 (setq start (point))
8120 (goto-char (point-max))
8121 (beginning-of-line 1)
8122 (when (looking-at ".*?\\S-")
8123 ;; File ends in a non-white line
8126 (setq end (point-max))
8127 (setq what "top-level")
8132 (if (>= beg end) (error "Nothing to sort"))
8134 (looking-at "\\(\\*+\\)")
8135 (setq stars (match-string 1)
8136 re (concat "^" (regexp-quote stars) " +")
8137 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8138 txt (buffer-substring beg end))
8139 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8140 (if (and (not (equal stars "*")) (string-match re2 txt))
8141 (error "Region to sort contains a level above the first entry"))
8143 (unless sorting-type
8145 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8146 [t]ime
[s]cheduled [d]eadline [c]reated
8147 A/N/T/S/D/C/P/O/F means reversed:"
8149 (setq sorting-type (read-char-exclusive))
8152 (and (= (downcase sorting-type) ?f)
8154 (org-icompleting-read "Sort using function: "
8155 obarray 'fboundp t nil nil))
8156 (setq getkey-func (intern getkey-func))))
8158 (and (= (downcase sorting-type) ?r)
8161 (org-icompleting-read "Property: "
8162 (mapcar 'list (org-buffer-property-keys t))
8165 (message "Sorting entries...")
8168 (narrow-to-region start end)
8169 (let ((dcst (downcase sorting-type))
8170 (case-fold-search nil)
8171 (now (current-time)))
8173 (/= dcst sorting-type)
8174 ;; This function moves to the beginning character of the "record" to
8177 (if (re-search-forward re nil t)
8178 (goto-char (match-beginning 0))
8179 (goto-char (point-max))))
8180 ;; This function moves to the last character of the "record" being
8185 (outline-forward-same-level 1)
8187 (goto-char (point-max))))))
8188 ;; This function returns the value that gets sorted against.
8192 (if (looking-at org-complex-heading-regexp)
8193 (string-to-number (match-string 4))
8196 (if (looking-at org-complex-heading-regexp)
8197 (funcall case-func (match-string 4))
8200 (let ((end (save-excursion (outline-next-heading) (point))))
8201 (if (or (re-search-forward org-ts-regexp end t)
8202 (re-search-forward org-ts-regexp-both end t))
8203 (org-time-string-to-seconds (match-string 0))
8204 (org-float-time now))))
8206 (let ((end (save-excursion (outline-next-heading) (point))))
8207 (if (re-search-forward
8208 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8210 (org-time-string-to-seconds (match-string 0))
8211 (org-float-time now))))
8213 (let ((end (save-excursion (outline-next-heading) (point))))
8214 (if (re-search-forward org-scheduled-time-regexp end t)
8215 (org-time-string-to-seconds (match-string 1))
8216 (org-float-time now))))
8218 (let ((end (save-excursion (outline-next-heading) (point))))
8219 (if (re-search-forward org-deadline-time-regexp end t)
8220 (org-time-string-to-seconds (match-string 1))
8221 (org-float-time now))))
8223 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8224 (string-to-char (match-string 2))
8225 org-default-priority))
8227 (or (org-entry-get nil property) ""))
8229 (if (looking-at org-complex-heading-regexp)
8230 (- 9999 (length (member (match-string 2)
8231 org-todo-keywords-1)))))
8235 (setq tmp (funcall getkey-func))
8236 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8238 (error "Invalid key function `%s'" getkey-func)))
8239 (t (error "Invalid sorting type `%c'" sorting-type))))
8242 ((= dcst ?a) 'string<)
8243 ((= dcst ?f) compare-func)
8244 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8245 (run-hooks 'org-after-sorting-entries-or-items-hook)
8246 (message "Sorting entries...done")))
8248 (defun org-do-sort (table what &optional with-case sorting-type)
8249 "Sort TABLE of WHAT according to SORTING-TYPE.
8250 The user will be prompted for the SORTING-TYPE if the call to this
8251 function does not specify it. WHAT is only for the prompt, to indicate
8252 what is being sorted. The sorting key will be extracted from
8253 the car of the elements of the table.
8254 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8255 (unless sorting-type
8257 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8259 (setq sorting-type (read-char-exclusive)))
8260 (let ((dcst (downcase sorting-type))
8261 extractfun comparefun)
8262 ;; Define the appropriate functions
8265 (setq extractfun 'string-to-number
8266 comparefun (if (= dcst sorting-type) '< '>)))
8268 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8269 (lambda(x) (downcase (org-sort-remove-invisible x))))
8270 comparefun (if (= dcst sorting-type)
8272 (lambda (a b) (and (not (string< a b))
8273 (not (string= a b)))))))
8277 (if (or (string-match org-ts-regexp x)
8278 (string-match org-ts-regexp-both x))
8280 (org-time-string-to-time (match-string 0 x)))
8282 comparefun (if (= dcst sorting-type) '< '>)))
8283 (t (error "Invalid sorting type `%c'" sorting-type)))
8285 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8287 (lambda (a b) (funcall comparefun (car a) (car b))))))
8290 ;;; The orgstruct minor mode
8292 ;; Define a minor mode which can be used in other modes in order to
8293 ;; integrate the org-mode structure editing commands.
8295 ;; This is really a hack, because the org-mode structure commands use
8296 ;; keys which normally belong to the major mode. Here is how it
8297 ;; works: The minor mode defines all the keys necessary to operate the
8298 ;; structure commands, but wraps the commands into a function which
8299 ;; tests if the cursor is currently at a headline or a plain list
8300 ;; item. If that is the case, the structure command is used,
8301 ;; temporarily setting many Org-mode variables like regular
8302 ;; expressions for filling etc. However, when any of those keys is
8303 ;; used at a different location, function uses `key-binding' to look
8304 ;; up if the key has an associated command in another currently active
8305 ;; keymap (minor modes, major mode, global), and executes that
8306 ;; command. There might be problems if any of the keys is otherwise
8307 ;; used as a prefix key.
8309 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8310 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8311 ;; addresses this by checking explicitly for both bindings.
8313 (defvar orgstruct-mode-map (make-sparse-keymap)
8314 "Keymap for the minor `orgstruct-mode'.")
8316 (defvar org-local-vars nil
8317 "List of local variables, for use by `orgstruct-mode'.")
8320 (define-minor-mode orgstruct-mode
8321 "Toggle the minor mode `orgstruct-mode'.
8322 This mode is for using Org-mode structure commands in other
8323 modes. The following keys behave as if Org-mode were active, if
8324 the cursor is on a headline, or on a plain list item (both as
8325 defined by Org-mode).
8327 M-up Move entry/item up
8328 M-down Move entry/item down
8331 M-S-up Move entry/item up
8332 M-S-down Move entry/item down
8333 M-S-left Promote subtree
8334 M-S-right Demote subtree
8335 M-q Fill paragraph and items like in Org-mode
8337 C-c - Cycle list bullet
8338 TAB Cycle item visibility
8339 M-RET Insert new heading/item
8340 S-M-RET Insert new TODO heading / Checkbox item
8341 C-c C-c Set tags / toggle checkbox"
8342 nil " OrgStruct" nil
8343 (org-load-modules-maybe)
8344 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8347 (defun turn-on-orgstruct ()
8348 "Unconditionally turn on `orgstruct-mode'."
8351 (defvar org-fb-vars nil)
8352 (make-variable-buffer-local 'org-fb-vars)
8353 (defun orgstruct++-mode (&optional arg)
8354 "Toggle `orgstruct-mode', the enhanced version of it.
8355 In addition to setting orgstruct-mode, this also exports all
8356 indentation and autofilling variables from org-mode into the
8357 buffer. It will also recognize item context in multiline items."
8359 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8361 (progn (orgstruct-mode -1)
8363 (org-set-local (car v)
8364 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8367 (setq org-fb-vars nil)
8372 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8373 (symbol-name (car x)))
8374 (setq var (car x) val (nth 1 x))
8375 (push (list var `(quote ,(eval var))) org-fb-vars)
8376 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8378 (org-set-local 'orgstruct-is-++ t))))
8380 (defvar orgstruct-is-++ nil
8381 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8382 (make-variable-buffer-local 'orgstruct-is-++)
8385 (defun turn-on-orgstruct++ ()
8386 "Unconditionally turn on `orgstruct++-mode'."
8387 (orgstruct++-mode 1))
8389 (defun orgstruct-error ()
8390 "Error when there is no default binding for a structure key."
8392 (error "This key has no function outside structure elements"))
8394 (defun orgstruct-setup ()
8395 "Setup orgstruct keymaps."
8399 '([(meta up)] org-metaup)
8400 '([(meta down)] org-metadown)
8401 '([(meta left)] org-metaleft)
8402 '([(meta right)] org-metaright)
8403 '([(meta shift up)] org-shiftmetaup)
8404 '([(meta shift down)] org-shiftmetadown)
8405 '([(meta shift left)] org-shiftmetaleft)
8406 '([(meta shift right)] org-shiftmetaright)
8407 '([?\e (up)] org-metaup)
8408 '([?\e (down)] org-metadown)
8409 '([?\e (left)] org-metaleft)
8410 '([?\e (right)] org-metaright)
8411 '([?\e (shift up)] org-shiftmetaup)
8412 '([?\e (shift down)] org-shiftmetadown)
8413 '([?\e (shift left)] org-shiftmetaleft)
8414 '([?\e (shift right)] org-shiftmetaright)
8415 '([(shift up)] org-shiftup)
8416 '([(shift down)] org-shiftdown)
8417 '([(shift left)] org-shiftleft)
8418 '([(shift right)] org-shiftright)
8419 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8420 '("\M-q" fill-paragraph)
8422 '("\C-c-" org-cycle-list-bullet)))
8424 (while (setq elt (pop bindings))
8425 (setq nfunc (1+ nfunc))
8426 (setq key (org-key (car elt))
8428 cmd (orgstruct-make-binding fun nfunc key))
8429 (org-defkey orgstruct-mode-map key cmd))
8431 ;; Prevent an error for users who forgot to make autoloads
8432 (require 'org-element)
8434 ;; Special treatment needed for TAB and RET
8435 (org-defkey orgstruct-mode-map [(tab)]
8436 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8437 (org-defkey orgstruct-mode-map "\C-i"
8438 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8440 (org-defkey orgstruct-mode-map "\M-\C-m"
8441 (orgstruct-make-binding 'org-insert-heading 105
8442 "\M-\C-m" [(meta return)]))
8443 (org-defkey orgstruct-mode-map [(meta return)]
8444 (orgstruct-make-binding 'org-insert-heading 106
8445 [(meta return)] "\M-\C-m"))
8447 (org-defkey orgstruct-mode-map [(shift meta return)]
8448 (orgstruct-make-binding 'org-insert-todo-heading 107
8449 [(meta return)] "\M-\C-m"))
8451 (org-defkey orgstruct-mode-map "\e\C-m"
8452 (orgstruct-make-binding 'org-insert-heading 108
8453 "\e\C-m" [?\e (return)]))
8454 (org-defkey orgstruct-mode-map [?\e (return)]
8455 (orgstruct-make-binding 'org-insert-heading 109
8456 [?\e (return)] "\e\C-m"))
8457 (org-defkey orgstruct-mode-map [?\e (shift return)]
8458 (orgstruct-make-binding 'org-insert-todo-heading 110
8459 [?\e (return)] "\e\C-m"))
8461 (unless org-local-vars
8462 (setq org-local-vars (org-get-local-variables)))
8466 (defun orgstruct-make-binding (fun n &rest keys)
8467 "Create a function for binding in the structure minor mode.
8468 FUN is the command to call inside a table. N is used to create a unique
8469 command name. KEYS are keys that should be checked in for a command
8470 to execute outside of tables."
8473 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8475 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8476 "Outside of structure, run the binding of `"
8477 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8481 `(org-context-p 'headline 'item
8482 (and orgstruct-is-++
8483 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8485 (list 'org-run-like-in-org-mode (list 'quote fun))
8486 (list 'let '(orgstruct-mode)
8487 (list 'call-interactively
8490 (list 'key-binding k))
8492 '('orgstruct-error))))))))
8494 (defun org-contextualize-keys (alist contexts)
8495 "Return valid elements in ALIST depending on CONTEXTS.
8497 `org-agenda-custom-commands' or `org-capture-templates' are the
8498 values used for ALIST, and `org-agenda-custom-commands-contexts'
8499 or `org-capture-templates-contexts' are the associated contexts
8502 ;; normalize contexts
8504 (lambda(c) (cond ((listp (cadr c))
8505 (list (car c) (car c) (cadr c)))
8506 ((string= "" (cadr c))
8507 (list (car c) (car c) (caddr c)))
8510 ;; loop over all commands or templates
8511 (while (setq c (pop a))
8514 ((not (assoc (car c) contexts))
8516 ((and (assoc (car c) contexts)
8517 (setq vrules (org-contextualize-validate-key
8520 (when (not (equal (car vr) (cadr vr)))
8521 (setq repl vr))) vrules)
8522 (if (not repl) (push c r)
8523 (push (cadr repl) s)
8526 (cdr (or (assoc (cadr repl) alist)
8527 (error "Undefined key `%s' as contextual replacement for `%s'"
8528 (cadr repl) (car c)))))
8530 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8535 (let ((tpl (car x)))
8539 (equal y tpl)) s))) x)))
8542 (defun org-contextualize-validate-key (key contexts)
8543 "Check CONTEXTS for agenda or capture KEY."
8545 (while (setq r (pop contexts))
8549 (and (equal key (car r))
8550 (if (functionp rr) (funcall rr)
8551 (or (and (eq (car rr) 'in-file)
8553 (string-match (cdr rr) (buffer-file-name)))
8554 (and (eq (car rr) 'in-mode)
8555 (string-match (cdr rr) (symbol-name major-mode)))
8556 (when (and (eq (car rr) 'not-in-file)
8558 (not (string-match (cdr rr) (buffer-file-name))))
8559 (when (eq (car rr) 'not-in-mode)
8560 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8563 (delete-dups (delq nil res))))
8565 (defun org-context-p (&rest contexts)
8566 "Check if local context is any of CONTEXTS.
8567 Possible values in the list of contexts are `table', `headline', and `item'."
8568 (let ((pos (point)))
8569 (goto-char (point-at-bol))
8570 (prog1 (or (and (memq 'table contexts)
8571 (looking-at "[ \t]*|"))
8572 (and (memq 'headline contexts)
8573 (looking-at org-outline-regexp))
8574 (and (memq 'item contexts)
8575 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8576 (and (memq 'item-body contexts)
8580 (defun org-get-local-variables ()
8581 "Return a list of all local variables in an Org mode buffer."
8583 (with-current-buffer (get-buffer-create "*Org tmp*")
8586 (setq varlist (buffer-local-variables)))
8587 (kill-buffer "*Org tmp*")
8594 (list (car x) (list 'quote (cdr x)))))
8596 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8597 (symbol-name (car x)))
8601 (defun org-clone-local-variables (from-buffer &optional regexp)
8602 "Clone local variables from FROM-BUFFER.
8603 Optional argument REGEXP selects variables to clone."
8606 (and (symbolp (car pair))
8608 (string-match regexp (symbol-name (car pair))))
8609 (set (make-local-variable (car pair))
8611 (buffer-local-variables from-buffer)))
8614 (defun org-run-like-in-org-mode (cmd)
8615 "Run a command, pretending that the current buffer is in Org-mode.
8616 This will temporarily bind local variables that are typically bound in
8617 Org-mode to the values they have in Org-mode, and then interactively
8619 (org-load-modules-maybe)
8620 (unless org-local-vars
8621 (setq org-local-vars (org-get-local-variables)))
8622 (eval (list 'let org-local-vars
8623 (list 'call-interactively (list 'quote cmd)))))
8627 (defun org-get-category (&optional pos force-refresh)
8628 "Get the category applying to position POS."
8630 (if force-refresh (org-refresh-category-properties))
8631 (let ((pos (or pos (point))))
8632 (or (get-text-property pos 'org-category)
8633 (progn (org-refresh-category-properties)
8634 (get-text-property pos 'org-category))))))
8636 (defun org-refresh-category-properties ()
8637 "Refresh category text properties in the buffer."
8638 (let ((case-fold-search t)
8639 (inhibit-read-only t)
8641 ((null org-category)
8642 (if buffer-file-name
8643 (file-name-sans-extension
8644 (file-name-nondirectory buffer-file-name))
8646 ((symbolp org-category) (symbol-name org-category))
8648 beg end cat pos optionp)
8653 (goto-char (point-min))
8654 (put-text-property (point) (point-max) 'org-category def-cat)
8655 (while (re-search-forward
8656 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8657 (setq pos (match-end 0)
8658 optionp (equal (char-after (match-beginning 0)) ?#)
8659 cat (org-trim (match-string 2)))
8661 (setq beg (point-at-bol) end (point-max))
8662 (org-back-to-heading t)
8663 (setq beg (point) end (org-end-of-subtree t t)))
8664 (put-text-property beg end 'org-category cat)
8665 (put-text-property beg end 'org-category-position beg)
8666 (goto-char pos)))))))
8671 ;;; Link abbreviations
8673 (defun org-link-expand-abbrev (link)
8674 "Apply replacements as defined in `org-link-abbrev-alist'."
8675 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8676 (let* ((key (match-string 1 link))
8677 (as (or (assoc key org-link-abbrev-alist-local)
8678 (assoc key org-link-abbrev-alist)))
8679 (tag (and (match-end 2) (match-string 3 link)))
8685 ((symbolp rpl) (funcall rpl tag))
8686 ((string-match "%(\\([^)]+\\))" rpl)
8687 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8688 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8689 ((string-match "%h" rpl)
8690 (replace-match (url-hexify-string (or tag "")) t t rpl))
8691 (t (concat rpl tag)))))
8694 ;;; Storing and inserting links
8696 (defvar org-insert-link-history nil
8697 "Minibuffer history for links inserted with `org-insert-link'.")
8699 (defvar org-stored-links nil
8700 "Contains the links stored with `org-store-link'.")
8702 (defvar org-store-link-plist nil
8703 "Plist with info about the most recently link created with `org-store-link'.")
8705 (defvar org-link-protocols nil
8706 "Link protocols added to Org-mode using `org-add-link-type'.")
8708 (defvar org-store-link-functions nil
8709 "List of functions that are called to create and store a link.
8710 Each function will be called in turn until one returns a non-nil
8711 value. Each function should check if it is responsible for creating
8712 this link (for example by looking at the major mode).
8713 If not, it must exit and return nil.
8714 If yes, it should return a non-nil value after a calling
8715 `org-store-link-props' with a list of properties and values.
8716 Special properties are:
8718 :type The link prefix, like \"http\". This must be given.
8719 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8720 This is obligatory as well.
8721 :description Optional default description for the second pair
8722 of brackets in an Org-mode link. The user can still change
8723 this when inserting this link into an Org-mode buffer.
8725 In addition to these, any additional properties can be specified
8726 and then used in capture templates.")
8728 (defun org-add-link-type (type &optional follow export)
8729 "Add TYPE to the list of `org-link-types'.
8730 Re-compute all regular expressions depending on `org-link-types'
8732 FOLLOW and EXPORT are two functions.
8734 FOLLOW should take the link path as the single argument and do whatever
8735 is necessary to follow the link, for example find a file or display
8738 EXPORT should format the link path for export to one of the export formats.
8739 It should be a function accepting three arguments:
8741 path the path of the link, the text after the prefix (like \"http:\")
8742 desc the description of the link, if any, or a description added by
8743 org-export-normalize-links if there is none
8744 format the export format, a symbol like `html' or `latex' or `ascii'..
8746 The function may use the FORMAT information to return different values
8747 depending on the format. The return value will be put literally into
8748 the exported file. If the return value is nil, this means Org should
8749 do what it normally does with links which do not have EXPORT defined.
8751 Org-mode has a built-in default for exporting links. If you are happy with
8752 this default, there is no need to define an export function for the link
8753 type. For a simple example of an export function, see `org-bbdb.el'."
8754 (add-to-list 'org-link-types type t)
8755 (org-make-link-regexps)
8756 (if (assoc type org-link-protocols)
8757 (setcdr (assoc type org-link-protocols) (list follow export))
8758 (push (list type follow export) org-link-protocols)))
8760 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8761 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8764 (defun org-store-link (arg)
8765 "\\<org-mode-map>Store an org-link to the current location.
8766 This link is added to `org-stored-links' and can later be inserted
8767 into an org-buffer with \\[org-insert-link].
8769 For some link types, a prefix arg is interpreted:
8770 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8771 For file links, arg negates `org-context-in-file-links'."
8773 (org-load-modules-maybe)
8774 (setq org-store-link-plist nil) ; reset
8775 (org-with-limited-levels
8776 (let (link cpltxt desc description search txt custom-id agenda-link)
8779 ((run-hook-with-args-until-success 'org-store-link-functions)
8780 (setq link (plist-get org-store-link-plist :link)
8781 desc (or (plist-get org-store-link-plist :description) link)))
8783 ((org-src-edit-buffer-p)
8785 (while (or (not label)
8789 (goto-char (point-min))
8791 (regexp-quote (format org-coderef-label-format label))
8793 (when label (message "Label exists already") (sit-for 2))
8794 (setq label (read-string "Code line label: " label)))
8796 (setq link (format org-coderef-label-format label))
8797 (setq gc (- 79 (length link)))
8798 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8800 (setq link (concat "(" label ")") desc nil)))
8802 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8803 ;; We are in the agenda, link to referenced location
8804 (let ((m (or (get-text-property (point) 'org-hd-marker)
8805 (get-text-property (point) 'org-marker))))
8807 (org-with-point-at m
8809 (if (org-called-interactively-p 'any)
8810 (call-interactively 'org-store-link)
8811 (org-store-link nil)))))))
8813 ((eq major-mode 'calendar-mode)
8814 (let ((cd (calendar-cursor-to-date)))
8817 (car org-time-stamp-formats)
8819 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8821 (org-store-link-props :type "calendar" :date cd)))
8823 ((eq major-mode 'help-mode)
8824 (setq link (concat "help:" (save-excursion
8825 (goto-char (point-min))
8826 (looking-at "^[^ ]+")
8828 (org-store-link-props :type "help"))
8830 ((eq major-mode 'w3-mode)
8831 (setq cpltxt (if (and (buffer-name)
8832 (not (string-match "Untitled" (buffer-name))))
8835 link (url-view-url t))
8836 (org-store-link-props :type "w3" :url (url-view-url t)))
8838 ((eq major-mode 'w3m-mode)
8839 (setq cpltxt (or w3m-current-title w3m-current-url)
8840 link w3m-current-url)
8841 (org-store-link-props :type "w3m" :url (url-view-url t)))
8843 ((setq search (run-hook-with-args-until-success
8844 'org-create-file-search-functions))
8845 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8847 (setq cpltxt (or description link)))
8849 ((eq major-mode 'image-mode)
8850 (setq cpltxt (concat "file:"
8851 (abbreviate-file-name buffer-file-name))
8853 (org-store-link-props :type "image" :file buffer-file-name))
8855 ((eq major-mode 'dired-mode)
8856 ;; link to the file in the current line
8857 (let ((file (dired-get-filename nil t)))
8859 (abbreviate-file-name
8860 (expand-file-name (dired-get-filename nil t)))
8861 ;; otherwise, no file so use current directory.
8863 (setq cpltxt (concat "file:" file)
8866 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8867 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8869 ((org-in-regexp "<<\\(.*?\\)>>")
8872 (abbreviate-file-name
8873 (buffer-file-name (buffer-base-buffer)))
8874 "::" (match-string 1))
8876 ((and (featurep 'org-id)
8877 (or (eq org-link-to-org-use-id t)
8878 (and (org-called-interactively-p 'any)
8879 (or (eq org-link-to-org-use-id 'create-if-interactive)
8880 (and (eq org-link-to-org-use-id
8881 'create-if-interactive-and-no-custom-id)
8883 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8884 ;; We can make a link using the ID.
8885 (setq link (condition-case nil
8886 (prog1 (org-id-store-link)
8887 (setq desc (plist-get org-store-link-plist :description)))
8889 ;; probably before first headline, link to file only
8891 (abbreviate-file-name
8892 (buffer-file-name (buffer-base-buffer))))))))
8894 ;; Just link to current headline
8895 (setq cpltxt (concat "file:"
8896 (abbreviate-file-name
8897 (buffer-file-name (buffer-base-buffer)))))
8898 ;; Add a context search string
8899 (when (org-xor org-context-in-file-links arg)
8901 ((org-at-heading-p) nil)
8902 ((org-region-active-p)
8903 (buffer-substring (region-beginning) (region-end)))))
8904 (when (or (null txt) (string-match "\\S-" txt))
8908 (org-make-org-heading-search-string txt)
8910 desc (or (nth 4 (ignore-errors
8911 (org-heading-components))) "NONE"))))
8912 (if (string-match "::\\'" cpltxt)
8913 (setq cpltxt (substring cpltxt 0 -2)))
8914 (setq link cpltxt))))
8916 ((buffer-file-name (buffer-base-buffer))
8917 ;; Just link to this file here.
8918 (setq cpltxt (concat "file:"
8919 (abbreviate-file-name
8920 (buffer-file-name (buffer-base-buffer)))))
8921 ;; Add a context string
8922 (when (org-xor org-context-in-file-links arg)
8923 (setq txt (if (org-region-active-p)
8924 (buffer-substring (region-beginning) (region-end))
8925 (buffer-substring (point-at-bol) (point-at-eol))))
8926 ;; Only use search option if there is some text.
8927 (when (string-match "\\S-" txt)
8929 (concat cpltxt "::" (org-make-org-heading-search-string txt))
8933 ((org-called-interactively-p 'interactive)
8934 (error "Cannot link to a buffer which is not visiting a file"))
8936 (t (setq link nil)))
8938 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8939 (setq link (or link cpltxt)
8940 desc (or desc cpltxt))
8941 (if (equal desc "NONE") (setq desc nil))
8943 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
8945 (setq org-stored-links
8946 (cons (list link desc) org-stored-links))
8947 (message "Stored: %s" (or desc link))
8949 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
8951 (setq org-stored-links
8952 (cons (list link desc) org-stored-links))))
8953 (or agenda-link (and link (org-make-link-string link desc)))))))
8955 (defun org-store-link-props (&rest plist)
8956 "Store link properties, extract names and addresses."
8958 (when (setq x (plist-get plist :from))
8959 (setq adr (mail-extract-address-components x))
8960 (setq plist (plist-put plist :fromname (car adr)))
8961 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
8962 (when (setq x (plist-get plist :to))
8963 (setq adr (mail-extract-address-components x))
8964 (setq plist (plist-put plist :toname (car adr)))
8965 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
8966 (let ((from (plist-get plist :from))
8967 (to (plist-get plist :to)))
8968 (when (and from to org-from-is-user-regexp)
8970 (plist-put plist :fromto
8971 (if (string-match org-from-is-user-regexp from)
8973 (concat "from %f"))))))
8974 (setq org-store-link-plist plist))
8976 (defun org-add-link-props (&rest plist)
8977 "Add these properties to the link property list."
8980 (setq key (pop plist) value (pop plist))
8981 (setq org-store-link-plist
8982 (plist-put org-store-link-plist key value)))))
8984 (defun org-email-link-description (&optional fmt)
8985 "Return the description part of an email link.
8986 This takes information from `org-store-link-plist' and formats it
8987 according to FMT (default from `org-email-link-description-format')."
8988 (setq fmt (or fmt org-email-link-description-format))
8989 (let* ((p org-store-link-plist)
8990 (to (plist-get p :toaddress))
8991 (from (plist-get p :fromaddress))
8994 (cons "%c" (plist-get p :fromto))
8995 (cons "%F" (plist-get p :from))
8996 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
8997 (cons "%T" (plist-get p :to))
8998 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
8999 (cons "%s" (plist-get p :subject))
9000 (cons "%d" (plist-get p :date))
9001 (cons "%m" (plist-get p :message-id)))))
9002 (when (string-match "%c" fmt)
9003 ;; Check if the user wrote this message
9004 (if (and org-from-is-user-regexp from to
9005 (save-match-data (string-match org-from-is-user-regexp from)))
9006 (setq fmt (replace-match "to %t" t t fmt))
9007 (setq fmt (replace-match "from %f" t t fmt))))
9008 (org-replace-escapes fmt table)))
9010 (defun org-make-org-heading-search-string (&optional string heading)
9011 "Make search string for STRING or current headline."
9013 (let ((s (or string (org-get-heading)))
9014 (lines org-context-in-file-links))
9015 (unless (and string (not heading))
9016 ;; We are using a headline, clean up garbage in there.
9017 (if (string-match org-todo-regexp s)
9018 (setq s (replace-match "" t t s)))
9019 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9020 (setq s (replace-match "" t t s)))
9021 (setq s (org-trim s))
9022 (if (string-match (concat "^\\(" org-quote-string "\\|"
9023 org-comment-string "\\)") s)
9024 (setq s (replace-match "" t t s)))
9025 (while (string-match org-ts-regexp s)
9026 (setq s (replace-match "" t t s))))
9027 (or string (setq s (concat "*" s))) ; Add * for headlines
9028 (when (and string (integerp lines) (> lines 0))
9029 (let ((slines (org-split-string s "\n")))
9030 (when (< lines (length slines))
9033 (reverse (nthcdr (- (length slines) lines)
9034 (reverse slines))) "\n")))))
9035 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9037 (defun org-make-link-string (link &optional description)
9038 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9039 (unless (string-match "\\S-" link)
9040 (error "Empty link"))
9041 (when (and description
9042 (stringp description)
9043 (not (string-match "\\S-" description)))
9044 (setq description nil))
9045 (when (stringp description)
9046 ;; Remove brackets from the description, they are fatal.
9047 (while (string-match "\\[" description)
9048 (setq description (replace-match "{" t t description)))
9049 (while (string-match "\\]" description)
9050 (setq description (replace-match "}" t t description))))
9051 (when (equal link description)
9052 ;; No description needed, it is identical
9053 (setq description nil))
9054 (when (and (not description)
9055 (not (string-match (org-image-file-name-regexp) link))
9056 (not (equal link (org-link-escape link))))
9057 (setq description (org-extract-attributes link)))
9059 (cond ((string-match (org-image-file-name-regexp) link) link)
9060 ((string-match org-link-types-re link)
9061 (concat (match-string 1 link)
9062 (org-link-escape (substring link (match-end 1)))))
9063 (t (org-link-escape link))))
9064 (concat "[[" link "]"
9065 (if description (concat "[" description "]") "")
9068 (defconst org-link-escape-chars
9069 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9070 "List of characters that should be escaped in link.
9071 This is the list that is used for internal purposes.")
9073 (defconst org-link-escape-chars-browser
9075 "List of escapes for characters that are problematic in links.
9076 This is the list that is used before handing over to the browser.")
9078 (defun org-link-escape (text &optional table merge)
9079 "Return percent escaped representation of TEXT.
9080 TEXT is a string with the text to escape.
9081 Optional argument TABLE is a list with characters that should be
9082 escaped. When nil, `org-link-escape-chars' is used.
9083 If optional argument MERGE is set, merge TABLE into
9084 `org-link-escape-chars'."
9087 (mapc (lambda (defchr)
9088 (unless (member defchr table)
9089 (setq table (cons defchr table)))) org-link-escape-chars))
9091 (setq table org-link-escape-chars)))
9094 (if (or (member char table)
9095 (and (or (< char 32) (= char 37) (> char 126))
9097 (mapconcat (lambda (sequence-element)
9098 (format "%%%.2X" sequence-element))
9099 (or (encode-coding-char char 'utf-8)
9100 (error "Unable to percent escape character: %s"
9101 (char-to-string char))) "")
9102 (char-to-string char))) text ""))
9104 (defun org-link-unescape (str)
9105 "Unhex hexified Unicode strings as returned from the JavaScript function
9106 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9107 (unless (and (null str) (string= "" str))
9108 (let ((pos 0) (case-fold-search t) unhexed)
9109 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9110 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9111 (setq str (replace-match unhexed t t str))
9112 (setq pos (+ pos (length unhexed))))))
9115 (defun org-link-unescape-compound (hex)
9116 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9117 Note: this function also decodes single byte encodings like
9118 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9120 (let* ((bytes (cdr (split-string hex "%")))
9125 (let* ((val (string-to-number (pop bytes) 16))
9129 ((>= val 252) (cons 6 252))
9130 ((>= val 248) (cons 5 248))
9131 ((>= val 240) (cons 4 240))
9132 ((>= val 224) (cons 3 224))
9133 ((>= val 192) (cons 2 192))
9136 (if (>= val 192) (setq eat (car shift-xor)))
9137 (setq val (logxor val (cdr shift-xor)))
9138 (setq sum (+ (lsh sum (car shift-xor)) val))
9139 (if (> eat 0) (setq eat (- eat 1)))
9141 ((= 0 eat) ;multi byte
9142 (setq ret (concat ret (org-char-to-string sum)))
9144 ((not bytes) ; single byte(s)
9145 (setq ret (org-link-unescape-single-byte-sequence hex))))
9146 )) ;; end (while bytes
9149 (defun org-link-unescape-single-byte-sequence (hex)
9150 "Unhexify hex-encoded single byte character sequences."
9151 (mapconcat (lambda (byte)
9152 (char-to-string (string-to-number byte 16)))
9153 (cdr (split-string hex "%")) ""))
9155 (defun org-xor (a b)
9159 (defun org-fixup-message-id-for-http (s)
9160 "Replace special characters in a message id, so it can be used in an http query."
9161 (when (string-match "%" s)
9162 (setq s (mapconcat (lambda (c)
9165 (char-to-string c)))
9167 (while (string-match "<" s)
9168 (setq s (replace-match "%3C" t t s)))
9169 (while (string-match ">" s)
9170 (setq s (replace-match "%3E" t t s)))
9171 (while (string-match "@" s)
9172 (setq s (replace-match "%40" t t s)))
9175 (defun org-link-prettify (link)
9176 "Return a human-readable representation of LINK.
9177 The car of LINK must be a raw link the cdr of LINK must be either
9178 a link description or nil."
9179 (let ((desc (or (cadr link) "<no description>")))
9180 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9181 "<" (car link) ">")))
9184 (defun org-insert-link-global ()
9185 "Insert a link like Org-mode does.
9186 This command can be called in any mode to insert a link in Org-mode syntax."
9188 (org-load-modules-maybe)
9189 (org-run-like-in-org-mode 'org-insert-link))
9191 (defun org-insert-all-links (&optional keep)
9192 "Insert all links in `org-stored-links'."
9194 (let ((links (copy-sequence org-stored-links)) l)
9195 (while (setq l (if keep (pop links) (pop org-stored-links)))
9197 (org-insert-link nil (car l) (cadr l))
9200 (defun org-link-fontify-links-to-this-file ()
9201 "Fontify links to the current file in `org-stored-links'."
9202 (let ((f (buffer-file-name)) a b)
9203 (setq a (mapcar (lambda(l)
9205 (when (and (string-match "^file:\\(.+\\)::" ll)
9206 (equal f (expand-file-name (match-string 1 ll))))
9209 (when (featurep 'org-id)
9210 (setq b (mapcar (lambda(l)
9212 (when (and (string-match "^id:\\(.+\\)$" ll)
9213 (equal f (expand-file-name
9214 (or (org-id-find-id-file
9215 (match-string 1 ll)) ""))))
9219 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9220 (delq nil (append a b)))))
9222 (defvar org-link-links-in-this-file nil)
9223 (defun org-insert-link (&optional complete-file link-location default-description)
9224 "Insert a link. At the prompt, enter the link.
9226 Completion can be used to insert any of the link protocol prefixes like
9229 The history can be used to select a link previously stored with
9230 `org-store-link'. When the empty string is entered (i.e. if you just
9231 press RET at the prompt), the link defaults to the most recently
9232 stored link. As SPC triggers completion in the minibuffer, you need to
9233 use M-SPC or C-q SPC to force the insertion of a space character.
9235 You will also be prompted for a description, and if one is given, it will
9236 be displayed in the buffer instead of the link.
9238 If there is already a link at point, this command will allow you to edit link
9239 and description parts.
9241 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9242 be selected using completion. The path to the file will be relative to the
9243 current directory if the file is in the current directory or a subdirectory.
9244 Otherwise, the link will be the absolute path as completed in the minibuffer
9245 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9246 option `org-link-file-path-type'.
9248 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9249 the current directory or below.
9251 With three \\[universal-argument] prefixes, negate the meaning of
9252 `org-keep-stored-link-after-insertion'.
9254 If `org-make-link-description-function' is non-nil, this function will be
9255 called with the link target, and the result will be the default
9258 If the LINK-LOCATION parameter is non-nil, this value will be
9259 used as the link location instead of reading one interactively.
9261 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9262 be used as the default description."
9264 (let* ((wcf (current-window-configuration))
9265 (origbuf (current-buffer))
9266 (region (if (org-region-active-p)
9267 (buffer-substring (region-beginning) (region-end))))
9268 (remove (and region (list (region-beginning) (region-end))))
9270 tmphist ; byte-compile incorrectly complains about this
9271 (link link-location)
9272 (abbrevs org-link-abbrev-alist-local)
9273 entry file all-prefixes auto-desc)
9275 (link-location) ; specified by arg, just use it.
9276 ((org-in-regexp org-bracket-link-regexp 1)
9277 ;; We do have a link at point, and we are going to edit it.
9278 (setq remove (list (match-beginning 0) (match-end 0)))
9279 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9280 (setq link (read-string "Link: "
9282 (org-match-string-no-properties 1)))))
9283 ((or (org-in-regexp org-angle-link-re)
9284 (org-in-regexp org-plain-link-re))
9285 ;; Convert to bracket link
9286 (setq remove (list (match-beginning 0) (match-end 0))
9287 link (read-string "Link: "
9288 (org-remove-angle-brackets (match-string 0)))))
9289 ((member complete-file '((4) (16)))
9290 ;; Completing read for file names.
9291 (setq link (org-file-complete-link complete-file)))
9293 ;; Read link, with completion for stored links.
9294 (org-link-fontify-links-to-this-file)
9295 (org-switch-to-buffer-other-window "*Org Links*")
9296 (with-current-buffer "*Org Links*"
9298 (insert "Insert a link.
9299 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9300 (when org-stored-links
9301 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9302 (insert (mapconcat 'org-link-prettify
9303 (reverse org-stored-links) "\n")))
9304 (goto-char (point-min)))
9305 (let ((cw (selected-window)))
9306 (select-window (get-buffer-window "*Org Links*" 'visible))
9307 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9308 (unless (pos-visible-in-window-p (point-max))
9309 (org-fit-window-to-buffer))
9310 (and (window-live-p cw) (select-window cw)))
9311 ;; Fake a link history, containing the stored links.
9312 (setq tmphist (append (mapcar 'car org-stored-links)
9313 org-insert-link-history))
9314 (setq all-prefixes (append (mapcar 'car abbrevs)
9315 (mapcar 'car org-link-abbrev-alist)
9320 (let ((org-completion-use-ido nil)
9321 (org-completion-use-iswitchb nil))
9322 (org-completing-read
9325 (mapcar (lambda (x) (list (concat x ":")))
9327 (mapcar 'car org-stored-links)
9328 (mapcar 'cadr org-stored-links))
9331 (caar org-stored-links))))
9332 (if (not (string-match "\\S-" link))
9333 (error "No link selected"))
9335 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9337 (if (or (member link all-prefixes)
9338 (and (equal ":" (substring link -1))
9339 (member (substring link 0 -1) all-prefixes)
9340 (setq link (substring link 0 -1))))
9341 (setq link (with-current-buffer origbuf
9342 (org-link-try-special-completion link)))))
9343 (set-window-configuration wcf)
9344 (kill-buffer "*Org Links*"))
9345 (setq entry (assoc link org-stored-links))
9346 (or entry (push link org-insert-link-history))
9347 (setq desc (or desc (nth 1 entry)))))
9349 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9350 (not org-keep-stored-link-after-insertion))
9351 (setq org-stored-links (delq (assoc link org-stored-links)
9354 (if (string-match org-plain-link-re link)
9355 ;; URL-like link, normalize the use of angular brackets.
9356 (setq link (org-remove-angle-brackets link)))
9358 ;; Check if we are linking to the current file with a search option
9359 ;; If yes, simplify the link by using only the search option.
9360 (when (and buffer-file-name
9361 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9362 (let* ((path (match-string 1 link))
9363 (case-fold-search nil)
9364 (search (match-string 2 link)))
9366 (if (equal (file-truename buffer-file-name) (file-truename path))
9367 ;; We are linking to this same file, with a search option
9368 (setq link search)))))
9370 ;; Check if we can/should use a relative path. If yes, simplify the link
9371 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9372 (let* ((type (match-string 1 link))
9373 (path (match-string 2 link))
9375 (case-fold-search nil))
9377 ((or (eq org-link-file-path-type 'absolute)
9378 (equal complete-file '(16)))
9379 (setq path (abbreviate-file-name (expand-file-name path))))
9380 ((eq org-link-file-path-type 'noabbrev)
9381 (setq path (expand-file-name path)))
9382 ((eq org-link-file-path-type 'relative)
9383 (setq path (file-relative-name path)))
9386 (if (string-match (concat "^" (regexp-quote
9388 (file-name-as-directory
9389 default-directory))))
9390 (expand-file-name path))
9391 ;; We are linking a file with relative path name.
9392 (setq path (substring (expand-file-name path)
9394 (setq path (abbreviate-file-name (expand-file-name path)))))))
9395 (setq link (concat type path))
9396 (if (equal desc origpath)
9399 (if org-make-link-description-function
9401 (or (condition-case nil
9402 (funcall org-make-link-description-function link desc)
9403 (error (progn (message "Can't get link description from `%s'"
9404 (symbol-name org-make-link-description-function))
9406 (read-string "Description: " default-description)))
9407 (if default-description (setq desc default-description)
9408 (setq desc (or (and auto-desc desc)
9409 (read-string "Description: " desc)))))
9411 (unless (string-match "\\S-" desc) (setq desc nil))
9412 (if remove (apply 'delete-region remove))
9413 (insert (org-make-link-string link desc))))
9415 (defun org-link-try-special-completion (type)
9416 "If there is completion support for link type TYPE, offer it."
9417 (let ((fun (intern (concat "org-" type "-complete-link"))))
9420 (read-string "Link (no completion support): " (concat type ":")))))
9422 (defun org-file-complete-link (&optional arg)
9423 "Create a file link using completion."
9425 (setq file (read-file-name "File: "))
9426 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9427 (pwd1 (file-name-as-directory (abbreviate-file-name
9428 (expand-file-name ".")))))
9433 (abbreviate-file-name (expand-file-name file)))))
9434 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9435 (setq link (concat "file:" (match-string 1 file))))
9436 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9437 (expand-file-name file))
9439 "file:" (match-string 1 (expand-file-name file)))))
9440 (t (setq link (concat "file:" file)))))
9443 (defun org-completing-read (&rest args)
9444 "Completing-read with SPACE being a normal character."
9445 (let ((enable-recursive-minibuffers t)
9446 (minibuffer-local-completion-map
9447 (copy-keymap minibuffer-local-completion-map)))
9448 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9449 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9450 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9451 (apply 'org-icompleting-read args)))
9453 (defun org-completing-read-no-i (&rest args)
9454 (let (org-completion-use-ido org-completion-use-iswitchb)
9455 (apply 'org-completing-read args)))
9457 (defun org-iswitchb-completing-read (prompt choices &rest args)
9458 "Use iswitch as a completing-read replacement to choose from choices.
9459 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9461 (let* ((iswitchb-use-virtual-buffers nil)
9462 (iswitchb-make-buflist-hook
9464 (setq iswitchb-temp-buflist choices))))
9465 (iswitchb-read-buffer prompt)))
9467 (defun org-icompleting-read (&rest args)
9468 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9469 (org-without-partial-completion
9470 (if (and org-completion-use-ido
9471 (fboundp 'ido-completing-read)
9472 (boundp 'ido-mode) ido-mode
9473 (listp (second args)))
9474 (let ((ido-enter-matching-directory nil))
9475 (apply 'ido-completing-read (concat (car args))
9476 (if (consp (car (nth 1 args)))
9477 (mapcar 'car (nth 1 args))
9480 (if (and org-completion-use-iswitchb
9481 (boundp 'iswitchb-mode) iswitchb-mode
9482 (listp (second args)))
9483 (apply 'org-iswitchb-completing-read (concat (car args))
9484 (if (consp (car (nth 1 args)))
9485 (mapcar 'car (nth 1 args))
9488 (apply 'completing-read args)))))
9490 (defun org-extract-attributes (s)
9491 "Extract the attributes cookie from a string and set as text property."
9492 (let (a attr (start 0) key value)
9494 (when (string-match "{{\\([^}]+\\)}}$" s)
9495 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9496 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9497 (setq key (match-string 1 a) value (match-string 2 a)
9499 attr (plist-put attr (intern key) value))))
9500 (org-add-props s nil 'org-attr attr))
9503 (defun org-extract-attributes-from-string (tag)
9504 (let (key value attr)
9505 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9506 (setq key (match-string 1 tag) value (match-string 2 tag)
9507 tag (replace-match "" t t tag)
9508 attr (plist-put attr (intern key) value)))
9511 (defun org-attributes-to-string (plist)
9512 "Format a property list into an HTML attribute list."
9513 (let ((s "") key value)
9515 (setq key (pop plist) value (pop plist))
9517 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9520 ;;; Opening/following a link
9522 (defvar org-link-search-failed nil)
9524 (defvar org-open-link-functions nil
9525 "Hook for functions finding a plain text link.
9526 These functions must take a single argument, the link content.
9527 They will be called for links that look like [[link text][description]]
9528 when LINK TEXT does not have a protocol like \"http:\" and does not look
9529 like a filename (e.g. \"./blue.png\").
9531 These functions will be called *before* Org attempts to resolve the
9532 link by doing text searches in the current buffer - so if you want a
9533 link \"[[target]]\" to still find \"<<target>>\", your function should
9534 handle this as a special case.
9536 When the function does handle the link, it must return a non-nil value.
9537 If it decides that it is not responsible for this link, it must return
9538 nil to indicate that that Org-mode can continue with other options
9539 like exact and fuzzy text search.")
9541 (defun org-next-link ()
9542 "Move forward to the next link.
9543 If the link is in hidden text, expose it."
9545 (when (and org-link-search-failed (eq this-command last-command))
9546 (goto-char (point-min))
9547 (message "Link search wrapped back to beginning of buffer"))
9548 (setq org-link-search-failed nil)
9549 (let* ((pos (point))
9551 (a (assoc :link ct)))
9552 (if a (goto-char (nth 2 a)))
9553 (if (re-search-forward org-any-link-re nil t)
9555 (goto-char (match-beginning 0))
9556 (if (outline-invisible-p) (org-show-context)))
9558 (setq org-link-search-failed t)
9559 (error "No further link found"))))
9561 (defun org-previous-link ()
9562 "Move backward to the previous link.
9563 If the link is in hidden text, expose it."
9565 (when (and org-link-search-failed (eq this-command last-command))
9566 (goto-char (point-max))
9567 (message "Link search wrapped back to end of buffer"))
9568 (setq org-link-search-failed nil)
9569 (let* ((pos (point))
9571 (a (assoc :link ct)))
9572 (if a (goto-char (nth 1 a)))
9573 (if (re-search-backward org-any-link-re nil t)
9575 (goto-char (match-beginning 0))
9576 (if (outline-invisible-p) (org-show-context)))
9578 (setq org-link-search-failed t)
9579 (error "No further link found"))))
9581 (defun org-translate-link (s)
9582 "Translate a link string if a translation function has been defined."
9583 (if (and org-link-translation-function
9584 (fboundp org-link-translation-function)
9585 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9587 (setq s (funcall org-link-translation-function
9588 (match-string 1 s) (match-string 2 s)))
9589 (concat (car s) ":" (cdr s)))
9592 (defun org-translate-link-from-planner (type path)
9593 "Translate a link from Emacs Planner syntax so that Org can follow it.
9594 This is still an experimental function, your mileage may vary."
9596 ((member type '("http" "https" "news" "ftp"))
9597 ;; standard Internet links are the same.
9599 ((and (equal type "irc") (string-match "^//" path))
9600 ;; Planner has two / at the beginning of an irc link, we have 1.
9601 ;; We should have zero, actually....
9602 (setq path (substring path 1)))
9603 ((and (equal type "lisp") (string-match "^/" path))
9604 ;; Planner has a slash, we do not.
9605 (setq type "elisp" path (substring path 1)))
9606 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9607 ;; A typical message link. Planner has the id after the final slash,
9608 ;; we separate it with a hash mark
9609 (setq path (concat (match-string 1 path) "#"
9610 (org-remove-angle-brackets (match-string 2 path)))))
9614 (defun org-find-file-at-mouse (ev)
9615 "Open file link or URL at mouse."
9617 (mouse-set-point ev)
9618 (org-open-at-point 'in-emacs))
9620 (defun org-open-at-mouse (ev)
9621 "Open file link or URL at mouse.
9622 See the docstring of `org-open-file' for details."
9624 (mouse-set-point ev)
9625 (if (eq major-mode 'org-agenda-mode)
9626 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9627 (org-open-at-point))
9629 (defvar org-window-config-before-follow-link nil
9630 "The window configuration before following a link.
9631 This is saved in case the need arises to restore it.")
9633 (defvar org-open-link-marker (make-marker)
9634 "Marker pointing to the location where `org-open-at-point; was called.")
9637 (defun org-open-at-point-global ()
9638 "Follow a link like Org-mode does.
9639 This command can be called in any mode to follow a link that has
9642 (org-run-like-in-org-mode 'org-open-at-point))
9645 (defun org-open-link-from-string (s &optional arg reference-buffer)
9646 "Open a link in the string S, as if it was in Org-mode."
9647 (interactive "sLink: \nP")
9648 (let ((reference-buffer (or reference-buffer (current-buffer))))
9650 (let ((org-inhibit-startup (not reference-buffer)))
9653 (goto-char (point-min))
9654 (when reference-buffer
9655 (setq org-link-abbrev-alist-local
9656 (with-current-buffer reference-buffer
9657 org-link-abbrev-alist-local)))
9658 (org-open-at-point arg reference-buffer)))))
9660 (defvar org-open-at-point-functions nil
9661 "Hook that is run when following a link at point.
9663 Functions in this hook must return t if they identify and follow
9664 a link at point. If they don't find anything interesting at point,
9665 they must return nil.")
9667 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9668 (defun org-open-at-point (&optional arg reference-buffer)
9669 "Open link at or after point.
9670 If there is no link at point, this function will search forward up to
9671 the end of the current line.
9672 Normally, files will be opened by an appropriate application. If the
9673 optional prefix argument ARG is non-nil, Emacs will visit the file.
9674 With a double prefix argument, try to open outside of Emacs, in the
9675 application the system uses for this file type."
9677 ;; if in a code block, then open the block's results
9678 (unless (call-interactively #'org-babel-open-src-block-result)
9679 (org-load-modules-maybe)
9680 (move-marker org-open-link-marker (point))
9681 (setq org-window-config-before-follow-link (current-window-configuration))
9682 (org-remove-occur-highlights nil nil t)
9684 ((and (org-at-heading-p)
9685 (not (org-at-timestamp-p t))
9687 (concat org-plain-link-re "\\|"
9688 org-bracket-link-regexp "\\|"
9689 org-angle-link-re "\\|"
9690 "[ \t]:[^ \t\n]+:[ \t]*$")))
9691 (not (get-text-property (point) 'org-linked-text)))
9692 (or (org-offer-links-in-entry arg)
9693 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9694 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9695 ((and (org-at-timestamp-p t)
9696 (not (org-in-regexp org-bracket-link-regexp)))
9697 (org-follow-timestamp-link))
9698 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9699 (not (org-in-regexp org-bracket-link-regexp)))
9700 (org-footnote-action))
9702 (let (type path link line search (pos (point)))
9705 (skip-chars-forward "^]\n\r")
9706 (when (org-in-regexp org-bracket-link-regexp 1)
9707 (setq link (org-extract-attributes
9708 (org-link-unescape (org-match-string-no-properties 1))))
9709 (while (string-match " *\n *" link)
9710 (setq link (replace-match " " t t link)))
9711 (setq link (org-link-expand-abbrev link))
9713 ((or (file-name-absolute-p link)
9714 (string-match "^\\.\\.?/" link))
9715 (setq type "file" path link))
9716 ((string-match org-link-re-with-space3 link)
9717 (setq type (match-string 1 link) path (match-string 2 link)))
9718 ((string-match "^help:+\\(.+\\)" link)
9719 (setq type "help" path (match-string 1 link)))
9720 (t (setq type "thisfile" path link)))
9723 (when (get-text-property (point) 'org-linked-text)
9724 (setq type "thisfile"
9725 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9726 (1+ (point)) (point))
9727 path (buffer-substring
9728 (or (previous-single-property-change pos 'org-linked-text)
9730 (or (next-single-property-change pos 'org-linked-text)
9735 (when (or (org-in-regexp org-angle-link-re)
9736 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9737 (save-match-data (not (looking-back "\\[\\[")))))
9738 (setq type (match-string 1)
9739 path (org-link-unescape (match-string 2)))
9742 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9744 path (match-string 1))
9745 (while (string-match ":" path)
9746 (setq path (replace-match "+" t t path)))
9748 (when (org-in-regexp "<\\([^><\n]+\\)>")
9749 (setq type "tree-match"
9750 path (match-string 1))
9753 (error "No link found"))
9755 ;; switch back to reference buffer
9756 ;; needed when if called in a temporary buffer through
9757 ;; org-open-link-from-string
9758 (with-current-buffer (or reference-buffer (current-buffer))
9760 ;; Remove any trailing spaces in path
9761 (if (string-match " +\\'" path)
9762 (setq path (replace-match "" t t path)))
9763 (if (and org-link-translation-function
9764 (fboundp org-link-translation-function))
9765 ;; Check if we need to translate the link
9766 (let ((tmp (funcall org-link-translation-function type path)))
9767 (setq type (car tmp) path (cdr tmp))))
9771 ((assoc type org-link-protocols)
9772 (funcall (nth 1 (assoc type org-link-protocols)) path))
9774 ((equal type "help")
9775 (let ((f-or-v (intern path)))
9776 (cond ((fboundp f-or-v)
9777 (describe-function f-or-v))
9779 (describe-variable f-or-v))
9780 (t (error "Not a known function or variable")))))
9782 ((equal type "mailto")
9783 (let ((cmd (car org-link-mailto-program))
9784 (args (cdr org-link-mailto-program)) args1
9785 (address path) (subject "") a)
9786 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9787 (setq address (match-string 1 path)
9788 subject (org-link-escape (match-string 2 path))))
9791 ((not (stringp (car args))) (push (pop args) args1))
9792 (t (setq a (pop args))
9793 (if (string-match "%a" a)
9794 (setq a (replace-match address t t a)))
9795 (if (string-match "%s" a)
9796 (setq a (replace-match subject t t a)))
9798 (apply cmd (nreverse args1))))
9800 ((member type '("http" "https" "ftp" "news"))
9801 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9803 path org-link-escape-chars-browser)
9806 ((string= type "doi")
9807 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9809 path org-link-escape-chars-browser)
9812 ((member type '("message"))
9813 (browse-url (concat type ":" path)))
9815 ((string= type "tags")
9816 (org-tags-view arg path))
9818 ((string= type "tree-match")
9819 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9821 ((string= type "file")
9822 (if (string-match "::\\([0-9]+\\)\\'" path)
9823 (setq line (string-to-number (match-string 1 path))
9824 path (substring path 0 (match-beginning 0)))
9825 (if (string-match "::\\(.+\\)\\'" path)
9826 (setq search (match-string 1 path)
9827 path (substring path 0 (match-beginning 0)))))
9828 (if (string-match "[*?{]" (file-name-nondirectory path))
9830 (org-open-file path arg line search)))
9832 ((string= type "shell")
9833 (let ((buf (generate-new-buffer "*Org Shell Output"))
9835 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9836 (string-match org-confirm-shell-link-not-regexp cmd))
9837 (not org-confirm-shell-link-function)
9838 (funcall org-confirm-shell-link-function
9839 (format "Execute \"%s\" in shell? "
9840 (org-add-props cmd nil
9841 'face 'org-warning))))
9843 (message "Executing %s" cmd)
9844 (shell-command cmd buf)
9845 (if (featurep 'midnight)
9846 (setq clean-buffer-list-kill-buffer-names
9847 (cons buf clean-buffer-list-kill-buffer-names))))
9850 ((string= type "elisp")
9852 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9853 (string-match org-confirm-elisp-link-not-regexp cmd))
9854 (not org-confirm-elisp-link-function)
9855 (funcall org-confirm-elisp-link-function
9856 (format "Execute \"%s\" as elisp? "
9857 (org-add-props cmd nil
9858 'face 'org-warning))))
9859 (message "%s => %s" cmd
9860 (if (equal (string-to-char cmd) ?\()
9862 (call-interactively (read cmd))))
9865 ((and (string= type "thisfile")
9866 (run-hook-with-args-until-success
9867 'org-open-link-functions path)))
9869 ((string= type "thisfile")
9871 (switch-to-buffer-other-window
9872 (org-get-buffer-for-internal-link (current-buffer)))
9873 (org-mark-ring-push))
9874 (let ((cmd `(org-link-search
9876 ,(cond ((equal arg '(4)) ''occur)
9877 ((equal arg '(16)) ''org-occur))
9879 (condition-case nil (let ((org-link-search-inhibit-query t))
9881 (error (progn (widen) (eval cmd))))))
9883 (t (browse-url-at-point)))))))
9884 (move-marker org-open-link-marker nil)
9885 (run-hook-with-args 'org-follow-link-hook)))
9887 (defun org-offer-links-in-entry (&optional nth zero)
9888 "Offer links in the current entry and follow the selected link.
9889 If there is only one link, follow it immediately as well.
9890 If NTH is an integer, immediately pick the NTH link found.
9891 If ZERO is a string, check also this string for a link, and if
9892 there is one, offer it as link number zero."
9893 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9894 "\\(" org-angle-link-re "\\)\\|"
9895 "\\(" org-plain-link-re "\\)"))
9897 (in-emacs (if (integerp nth) nil nth))
9898 have-zero end links link c)
9899 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9900 (push (match-string 0 zero) links)
9901 (setq cnt (1- cnt) have-zero t))
9903 (org-back-to-heading t)
9904 (setq end (save-excursion (outline-next-heading) (point)))
9905 (while (re-search-forward re end t)
9906 (push (match-string 0) links))
9907 (setq links (org-uniquify (reverse links))))
9911 (message "No links"))
9912 ((equal (length links) 1)
9913 (setq link (list (car links))))
9914 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
9915 (setq link (list (nth (if have-zero nth (1- nth)) links))))
9916 (t ; we have to select a link
9918 (save-window-excursion
9919 (delete-other-windows)
9920 (with-output-to-temp-buffer "*Select Link*"
9922 (if (not (string-match org-bracket-link-regexp l))
9923 (princ (format "[%c] %s\n" (incf cnt)
9924 (org-remove-angle-brackets l)))
9926 (princ (format "[%c] %s (%s)\n" (incf cnt)
9927 (match-string 3 l) (match-string 1 l)))
9928 (princ (format "[%c] %s\n" (incf cnt)
9929 (match-string 1 l))))))
9931 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
9932 (message "Select link to open, RET to open all:")
9933 (setq c (read-char-exclusive))
9934 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
9935 (when (equal c ?q) (error "Abort"))
9939 (if have-zero (setq nth (1+ nth)))
9940 (unless (and (integerp nth) (>= (length links) nth))
9941 (error "Invalid link selection"))
9942 (setq link (list (nth (1- nth) links))))))
9944 (let ((buf (current-buffer)))
9946 (org-open-link-from-string l in-emacs buf))
9950 ;; Add special file links that specify the way of opening
9952 (org-add-link-type "file+sys" 'org-open-file-with-system)
9953 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
9954 (defun org-open-file-with-system (path)
9955 "Open file at PATH using the system way of opening it."
9956 (org-open-file path 'system))
9957 (defun org-open-file-with-emacs (path)
9958 "Open file at PATH in Emacs."
9959 (org-open-file path 'emacs))
9960 (defun org-remove-file-link-modifiers ()
9961 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
9962 (goto-char (point-min))
9963 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
9965 (replace-match "file:" t t))))
9966 (eval-after-load "org-exp"
9967 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
9968 'org-remove-file-link-modifiers))
9972 (defun org-get-effort (&optional pom)
9973 "Get the effort estimate for the current entry."
9974 (org-entry-get pom org-effort-property))
9978 (defvar org-create-file-search-functions nil
9979 "List of functions to construct the right search string for a file link.
9980 These functions are called in turn with point at the location to
9981 which the link should point.
9983 A function in the hook should first test if it would like to
9984 handle this file type, for example by checking the `major-mode'
9985 or the file extension. If it decides not to handle this file, it
9986 should just return nil to give other functions a chance. If it
9987 does handle the file, it must return the search string to be used
9988 when following the link. The search string will be part of the
9989 file link, given after a double colon, and `org-open-at-point'
9990 will automatically search for it. If special measures must be
9991 taken to make the search successful, another function should be
9992 added to the companion hook `org-execute-file-search-functions',
9995 A function in this hook may also use `setq' to set the variable
9996 `description' to provide a suggestion for the descriptive text to
9997 be used for this link when it gets inserted into an Org-mode
9998 buffer with \\[org-insert-link].")
10000 (defvar org-execute-file-search-functions nil
10001 "List of functions to execute a file search triggered by a link.
10003 Functions added to this hook must accept a single argument, the
10004 search string that was part of the file link, the part after the
10005 double colon. The function must first check if it would like to
10006 handle this search, for example by checking the `major-mode' or
10007 the file extension. If it decides not to handle this search, it
10008 should just return nil to give other functions a chance. If it
10009 does handle the search, it must return a non-nil value to keep
10010 other functions from trying.
10012 Each function can access the current prefix argument through the
10013 variable `current-prefix-argument'. Note that a single prefix is
10014 used to force opening a link in Emacs, so it may be good to only
10015 use a numeric or double prefix to guide the search function.
10017 In case this is needed, a function in this hook can also restore
10018 the window configuration before `org-open-at-point' was called using:
10020 (set-window-configuration org-window-config-before-follow-link)")
10022 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10023 (defun org-link-search (s &optional type avoid-pos stealth)
10024 "Search for a link search option.
10025 If S is surrounded by forward slashes, it is interpreted as a
10026 regular expression. In org-mode files, this will create an `org-occur'
10027 sparse tree. In ordinary files, `occur' will be used to list matches.
10028 If the current buffer is in `dired-mode', grep will be used to search
10029 in all files. If AVOID-POS is given, ignore matches near that position.
10031 When optional argument STEALTH is non-nil, do not modify
10032 visibility around point, thus ignoring
10033 `org-show-hierarchy-above', `org-show-following-heading' and
10034 `org-show-siblings' variables."
10035 (let ((case-fold-search t)
10036 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10037 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10038 (append '(("") (" ") ("\t") ("\n"))
10039 org-emphasis-alist)
10042 (pre nil) (post nil)
10043 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10045 ;; First check if there are any special search functions
10046 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10047 ;; Now try the builtin stuff
10048 ((and (equal (string-to-char s0) ?#)
10051 (goto-char (point-min))
10054 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10055 (setq type 'dedicated
10056 pos (match-beginning 0))))
10057 ;; There is an exact target for this
10059 (org-back-to-heading t)))
10061 (goto-char (point-min))
10064 (concat "<<" (regexp-quote s0) ">>") nil t)
10065 (setq type 'dedicated
10066 pos (match-beginning 0))))
10067 ;; There is an exact target for this
10070 (goto-char (point-min))
10073 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10074 (setq type 'dedicated pos (match-beginning 0))))
10075 ;; Found an invisible target.
10078 (goto-char (point-min))
10081 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10082 (setq type 'dedicated pos (match-beginning 0))))
10083 ;; Found an element with a matching #+name affiliated keyword.
10085 ((and (string-match "^(\\(.*\\))$" s0)
10087 (goto-char (point-min))
10090 (concat "[^[]" (regexp-quote
10091 (format org-coderef-label-format
10092 (match-string 1 s0))))
10094 (setq type 'dedicated
10095 pos (1+ (match-beginning 0))))))
10096 ;; There is a coderef target for this
10098 ((string-match "^/\\(.*\\)/$" s)
10099 ;; A regular expression
10101 ((derived-mode-p 'org-mode)
10102 (org-occur (match-string 1 s)))
10103 ;;((eq major-mode 'dired-mode)
10104 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10105 (t (org-do-occur (match-string 1 s)))))
10106 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10107 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10108 (goto-char (point-min))
10110 ((let (case-fold-search)
10111 (re-search-forward (format org-complex-heading-regexp-format
10114 ;; OK, found a match
10115 (setq type 'dedicated)
10116 (goto-char (match-beginning 0)))
10117 ((and (not org-link-search-inhibit-query)
10118 (eq org-link-search-must-match-exact-headline 'query-to-create)
10119 (y-or-n-p "No match - create this as a new heading? "))
10120 (goto-char (point-max))
10121 (or (bolp) (newline))
10122 (insert "* " s "\n")
10123 (beginning-of-line 0))
10126 (error "No match"))))
10128 ;; A normal search string
10129 (when (equal (string-to-char s) ?*)
10130 ;; Anchor on headlines, post may include tags.
10131 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10132 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10133 s (substring s 1)))
10134 (remove-text-properties
10136 '(face nil mouse-face nil keymap nil fontified nil) s)
10137 ;; Make a series of regular expressions to find a match
10138 (setq words (org-split-string s "[ \n\r\t]+")
10140 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10141 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10143 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10144 re2a (concat "[ \t\r\n]" re2a_)
10145 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10146 re4 (concat "[^a-zA-Z_]" re4_)
10148 re1 (concat pre re2 post)
10149 re3 (concat pre (if pre re4_ re4) post)
10150 re5 (concat pre ".*" re4)
10151 re2 (concat pre re2)
10152 re2a (concat pre (if pre re2a_ re2a))
10153 re4 (concat pre (if pre re4_ re4))
10154 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10155 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10159 ((eq type 'org-occur) (org-occur reall))
10160 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10161 (t (goto-char (point-min))
10163 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10164 (org-search-not-self 1 re1 nil t)
10165 (org-search-not-self 1 re2 nil t)
10166 (org-search-not-self 1 re2a nil t)
10167 (org-search-not-self 1 re3 nil t)
10168 (org-search-not-self 1 re4 nil t)
10169 (org-search-not-self 1 re5 nil t)
10171 (goto-char (match-beginning 1))
10173 (error "No match"))))))
10174 (and (derived-mode-p 'org-mode)
10176 (org-show-context 'link-search))
10179 (defun org-search-not-self (group &rest args)
10180 "Execute `re-search-forward', but only accept matches that do not
10181 enclose the position of `org-open-link-marker'."
10182 (let ((m org-open-link-marker))
10184 (while (apply 're-search-forward args)
10185 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10186 (goto-char (match-end group))
10187 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10188 (> (match-beginning 0) (marker-position m))
10189 (< (match-end 0) (marker-position m)))
10191 (or (not (org-in-regexp
10192 org-bracket-link-analytic-regexp 1))
10193 (not (match-end 4)) ; no description
10194 (and (<= (match-beginning 4) (point))
10195 (>= (match-end 4) (point))))))
10196 (throw 'exit (point))))))))
10198 (defun org-get-buffer-for-internal-link (buffer)
10199 "Return a buffer to be used for displaying the link target of internal links."
10201 ((not org-display-internal-link-with-indirect-buffer)
10203 ((string-match "(Clone)$" (buffer-name buffer))
10204 (message "Buffer is already a clone, not making another one")
10205 ;; we also do not modify visibility in this case
10207 (t ; make a new indirect buffer for displaying the link
10208 (let* ((bn (buffer-name buffer))
10209 (ibn (concat bn "(Clone)"))
10210 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10211 (with-current-buffer ib (org-overview))
10214 (defun org-do-occur (regexp &optional cleanup)
10215 "Call the Emacs command `occur'.
10216 If CLEANUP is non-nil, remove the printout of the regular expression
10217 in the *Occur* buffer. This is useful if the regex is long and not useful
10221 (let ((cwin (selected-window)) win beg end)
10222 (when (setq win (get-buffer-window "*Occur*"))
10223 (select-window win))
10224 (goto-char (point-min))
10225 (when (re-search-forward "match[a-z]+" nil t)
10226 (setq beg (match-end 0))
10227 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10228 (setq end (1- (match-beginning 0)))))
10229 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10230 (goto-char (point-min))
10231 (select-window cwin))))
10233 ;;; The mark ring for links jumps
10235 (defvar org-mark-ring nil
10236 "Mark ring for positions before jumps in Org-mode.")
10237 (defvar org-mark-ring-last-goto nil
10238 "Last position in the mark ring used to go back.")
10239 ;; Fill and close the ring
10240 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10241 (loop for i from 1 to org-mark-ring-length do
10242 (push (make-marker) org-mark-ring))
10243 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10246 (defun org-mark-ring-push (&optional pos buffer)
10247 "Put the current position or POS into the mark ring and rotate it."
10249 (setq pos (or pos (point)))
10250 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10251 (move-marker (car org-mark-ring)
10253 (or buffer (current-buffer)))
10255 (substitute-command-keys
10256 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10258 (defun org-mark-ring-goto (&optional n)
10259 "Jump to the previous position in the mark ring.
10260 With prefix arg N, jump back that many stored positions. When
10261 called several times in succession, walk through the entire ring.
10262 Org-mode commands jumping to a different position in the current file,
10263 or to another Org-mode file, automatically push the old position
10267 (if (eq last-command this-command)
10268 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10269 (setq p org-mark-ring))
10270 (setq org-mark-ring-last-goto p)
10272 (org-pop-to-buffer-same-window (marker-buffer m))
10274 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10276 (defun org-remove-angle-brackets (s)
10277 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10278 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10280 (defun org-add-angle-brackets (s)
10281 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10282 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10284 (defun org-remove-double-quotes (s)
10285 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10286 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10289 ;;; Following specific links
10291 (defun org-follow-timestamp-link ()
10292 "Open an agenda view for the time-stamp date/range at point."
10294 ((org-at-date-range-p t)
10295 (let ((org-agenda-start-on-weekday)
10296 (t1 (match-string 1))
10297 (t2 (match-string 2)) tt1 tt2)
10298 (setq tt1 (time-to-days (org-time-string-to-time t1))
10299 tt2 (time-to-days (org-time-string-to-time t2)))
10300 (let ((org-agenda-buffer-tmp-name
10301 (format "*Org Agenda(a:%s)"
10302 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10303 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10304 ((org-at-timestamp-p t)
10305 (let ((org-agenda-buffer-tmp-name
10306 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10307 (org-agenda-list nil (time-to-days (org-time-string-to-time
10308 (substring (match-string 1) 0 10)))
10310 (t (error "This should not happen"))))
10313 ;;; Following file links
10314 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10315 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10316 (declare-function mailcap-mime-info
10317 "mailcap" (string &optional request no-decode))
10318 (defvar org-wait nil)
10319 (defun org-open-file (path &optional in-emacs line search)
10320 "Open the file at PATH.
10321 First, this expands any special file name abbreviations. Then the
10322 configuration variable `org-file-apps' is checked if it contains an
10323 entry for this file type, and if yes, the corresponding command is launched.
10325 If no application is found, Emacs simply visits the file.
10327 With optional prefix argument IN-EMACS, Emacs will visit the file.
10328 With a double \\[universal-argument] \\[universal-argument] \
10329 prefix arg, Org tries to avoid opening in Emacs
10330 and to use an external application to visit the file.
10332 Optional LINE specifies a line to go to, optional SEARCH a string
10333 to search for. If LINE or SEARCH is given, the file will be
10334 opened in Emacs, unless an entry from org-file-apps that makes
10335 use of groups in a regexp matches.
10337 If you want to change the way frames are used when following a
10338 link, please customize `org-link-frame-setup'.
10340 If the file does not exist, an error is thrown."
10341 (let* ((file (if (equal path "")
10343 (substitute-in-file-name (expand-file-name path))))
10344 (file-apps (append org-file-apps (org-default-apps)))
10345 (apps (org-remove-if
10346 'org-file-apps-entry-match-against-dlink-p file-apps))
10347 (apps-dlink (org-remove-if-not
10348 'org-file-apps-entry-match-against-dlink-p file-apps))
10349 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10350 (dirp (if remp nil (file-directory-p file)))
10351 (file (if (and dirp org-open-directory-means-index-dot-org)
10352 (concat (file-name-as-directory file) "index.org")
10354 (a-m-a-p (assq 'auto-mode apps))
10355 (dfile (downcase file))
10356 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10357 (link (cond ((and (eq line nil)
10361 (concat file "::" (number-to-string line)))
10363 (concat file "::" search))))
10364 (dlink (downcase link))
10365 (old-buffer (current-buffer))
10367 (old-mode major-mode)
10368 ext cmd link-match-data)
10369 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10370 (setq ext (match-string 1 dfile))
10371 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10372 (setq ext (match-string 1 dfile))))
10374 ((member in-emacs '((16) system))
10375 (setq cmd (cdr (assoc 'system apps))))
10376 (in-emacs (setq cmd 'emacs))
10378 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10379 (and dirp (cdr (assoc 'directory apps)))
10380 ; first, try matching against apps-dlink
10381 ; if we get a match here, store the match data for later
10382 (let ((match (assoc-default dlink apps-dlink
10385 (progn (setq link-match-data (match-data))
10387 (progn (setq in-emacs (or in-emacs line search))
10388 nil))) ; if we have no match in apps-dlink,
10389 ; always open the file in emacs if line or search
10390 ; is given (for backwards compatibility)
10391 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10393 (cdr (assoc ext apps))
10394 (cdr (assoc t apps))))))
10395 (when (eq cmd 'system)
10396 (setq cmd (cdr (assoc 'system apps))))
10397 (when (eq cmd 'default)
10398 (setq cmd (cdr (assoc t apps))))
10399 (when (eq cmd 'mailcap)
10401 (mailcap-parse-mailcaps)
10402 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10403 (command (mailcap-mime-info mime-type)))
10404 (if (stringp command)
10406 (setq cmd 'emacs))))
10407 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10408 (not (file-exists-p file))
10409 (not org-open-non-existing-files))
10410 (error "No such file: %s" file))
10412 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10413 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10414 (while (string-match "['\"]%s['\"]" cmd)
10415 (setq cmd (replace-match "%s" t t cmd)))
10416 (while (string-match "%s" cmd)
10417 (setq cmd (replace-match
10419 (shell-quote-argument
10420 (convert-standard-filename file)))
10423 ;; Replace "%1", "%2" etc. in command with group matches from regex
10425 (let ((match-index 1)
10426 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10427 (set-match-data link-match-data)
10428 (while (<= match-index number-of-groups)
10429 (let ((regex (concat "%" (number-to-string match-index)))
10430 (replace-with (match-string match-index dlink)))
10431 (while (string-match regex cmd)
10432 (setq cmd (replace-match replace-with t t cmd))))
10433 (setq match-index (+ match-index 1)))))
10435 (save-window-excursion
10436 (message "Running %s...done" cmd)
10437 (start-process-shell-command cmd nil cmd)
10438 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10441 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10443 (if line (org-goto-line line)
10444 (if search (org-link-search search))))
10446 (let ((file (convert-standard-filename file)))
10448 (set-match-data link-match-data)
10450 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10451 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10452 (or (not (equal old-buffer (current-buffer)))
10453 (not (equal old-pos (point))))
10454 (org-mark-ring-push old-pos old-buffer))))
10456 (defun org-file-apps-entry-match-against-dlink-p (entry)
10457 "This function returns non-nil if `entry' uses a regular
10458 expression which should be matched against the whole link by
10461 It assumes that is the case when the entry uses a regular
10462 expression which has at least one grouping construct and the
10463 action is either a lisp form or a command string containing
10464 '%1', i.e. using at least one subexpression match as a
10466 (let ((selector (car entry))
10467 (action (cdr entry)))
10468 (if (stringp selector)
10469 (and (> (regexp-opt-depth selector) 0)
10470 (or (and (stringp action)
10471 (string-match "%[0-9]" action))
10475 (defun org-default-apps ()
10476 "Return the default applications for this operating system."
10478 ((eq system-type 'darwin)
10479 org-file-apps-defaults-macosx)
10480 ((eq system-type 'windows-nt)
10481 org-file-apps-defaults-windowsnt)
10482 (t org-file-apps-defaults-gnu)))
10484 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10485 "Convert extensions to regular expressions in the cars of LIST.
10486 Also, weed out any non-string entries, because the return value is used
10487 only for regexp matching.
10488 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10489 point to the symbol `emacs', indicating that the file should
10490 be opened in Emacs."
10493 (mapcar (lambda (x)
10494 (if (not (stringp (car x)))
10496 (if (string-match "\\W" (car x))
10498 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10501 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10503 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10504 (defun org-file-remote-p (file)
10505 "Test whether FILE specifies a location on a remote system.
10506 Return non-nil if the location is indeed remote.
10508 For example, the filename \"/user@host:/foo\" specifies a location
10509 on the system \"/user@host:\"."
10510 (cond ((fboundp 'file-remote-p)
10511 (file-remote-p file))
10512 ((fboundp 'tramp-handle-file-remote-p)
10513 (tramp-handle-file-remote-p file))
10514 ((and (boundp 'ange-ftp-name-format)
10515 (string-match (car ange-ftp-name-format) file))
10521 (defun org-get-org-file ()
10522 "Read a filename, with default directory `org-directory'."
10523 (let ((default (or org-default-notes-file remember-data-file)))
10524 (read-file-name (format "File name [%s]: " default)
10525 (file-name-as-directory org-directory)
10528 (defun org-notes-order-reversed-p ()
10529 "Check if the current file should receive notes in reversed order."
10531 ((not org-reverse-note-order) nil)
10532 ((eq t org-reverse-note-order) t)
10533 ((not (listp org-reverse-note-order)) nil)
10535 (let ((all org-reverse-note-order)
10537 (while (setq entry (pop all))
10538 (if (string-match (car entry) buffer-file-name)
10539 (throw 'exit (cdr entry))))
10542 (defvar org-refile-target-table nil
10543 "The list of refile targets, created by `org-refile'.")
10545 (defvar org-agenda-new-buffers nil
10546 "Buffers created to visit agenda files.")
10548 (defvar org-refile-cache nil
10549 "Cache for refile targets.")
10551 (defvar org-refile-markers nil
10552 "All the markers used for caching refile locations.")
10554 (defun org-refile-marker (pos)
10555 "Get a new refile marker, but only if caching is in use."
10556 (if (not org-refile-use-cache)
10558 (let ((m (make-marker)))
10559 (move-marker m pos)
10560 (push m org-refile-markers)
10563 (defun org-refile-cache-clear ()
10564 "Clear the refile cache and disable all the markers."
10565 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10566 (setq org-refile-markers nil)
10567 (setq org-refile-cache nil)
10568 (message "Refile cache has been cleared"))
10570 (defun org-refile-cache-check-set (set)
10571 "Check if all the markers in the cache still have live buffers."
10574 (while (and set (setq marker (nth 3 (pop set))))
10575 ;; if org-refile-use-outline-path is 'file, marker may be nil
10576 (when (and marker (null (marker-buffer marker)))
10577 (message "not found") (sit-for 3)
10578 (throw 'exit nil)))
10581 (defun org-refile-cache-put (set &rest identifiers)
10582 "Push the refile targets SET into the cache, under IDENTIFIERS."
10583 (let* ((key (sha1 (prin1-to-string identifiers)))
10584 (entry (assoc key org-refile-cache)))
10587 (push (cons key set) org-refile-cache))))
10589 (defun org-refile-cache-get (&rest identifiers)
10590 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10592 ((not org-refile-cache) nil)
10593 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10595 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10596 org-refile-cache))))
10597 (and set (org-refile-cache-check-set set) set)))))
10599 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10600 "Produce a table with refile targets."
10601 (let ((case-fold-search nil)
10602 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10603 (entries (or org-refile-targets '((nil . (:level . 1)))))
10604 targets tgs txt re files f desc descre fast-path-p level pos0)
10605 (message "Getting targets...")
10606 (with-current-buffer (or default-buffer (current-buffer))
10607 (while (setq entry (pop entries))
10608 (setq files (car entry) desc (cdr entry))
10609 (setq fast-path-p nil)
10611 ((null files) (setq files (list (current-buffer))))
10612 ((eq files 'org-agenda-files)
10613 (setq files (org-agenda-files 'unrestricted)))
10614 ((and (symbolp files) (fboundp files))
10615 (setq files (funcall files)))
10616 ((and (symbolp files) (boundp files))
10617 (setq files (symbol-value files))))
10618 (if (stringp files) (setq files (list files)))
10620 ((eq (car desc) :tag)
10621 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10622 ((eq (car desc) :todo)
10623 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10624 ((eq (car desc) :regexp)
10625 (setq descre (cdr desc)))
10626 ((eq (car desc) :level)
10627 (setq descre (concat "^\\*\\{" (number-to-string
10628 (if org-odd-levels-only
10629 (1- (* 2 (cdr desc)))
10632 ((eq (car desc) :maxlevel)
10633 (setq fast-path-p t)
10634 (setq descre (concat "^\\*\\{1," (number-to-string
10635 (if org-odd-levels-only
10636 (1- (* 2 (cdr desc)))
10639 (t (error "Bad refiling target description %s" desc)))
10640 (while (setq f (pop files))
10641 (with-current-buffer
10642 (if (bufferp f) f (org-get-agenda-file-buffer f))
10644 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10646 (if (bufferp f) (setq f (buffer-file-name
10647 (buffer-base-buffer f))))
10648 (setq f (and f (expand-file-name f)))
10649 (if (eq org-refile-use-outline-path 'file)
10650 (push (list (file-name-nondirectory f) f nil nil) tgs))
10654 (goto-char (point-min))
10655 (while (re-search-forward descre nil t)
10656 (goto-char (setq pos0 (point-at-bol)))
10658 (when org-refile-target-verify-function
10660 (or (funcall org-refile-target-verify-function)
10662 (when (and (looking-at org-complex-heading-regexp)
10663 (not (member (match-string 4) excluded-entries))
10665 (setq level (org-reduced-level
10666 (- (match-end 1) (match-beginning 1)))
10667 txt (org-link-display-format (match-string 4))
10668 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10669 re (format org-complex-heading-regexp-format
10670 (regexp-quote (match-string 4))))
10671 (when org-refile-use-outline-path
10672 (setq txt (mapconcat
10675 (if (eq org-refile-use-outline-path
10677 (list (file-name-nondirectory
10679 (buffer-base-buffer))))
10680 (if (eq org-refile-use-outline-path
10682 (list (buffer-file-name
10683 (buffer-base-buffer)))))
10684 (org-get-outline-path fast-path-p
10688 (push (list txt f re (org-refile-marker (point)))
10690 (when (= (point) pos0)
10691 ;; verification function has not moved point
10692 (goto-char (point-at-eol))))))))
10693 (when org-refile-use-cache
10694 (org-refile-cache-put tgs (buffer-file-name) descre))
10695 (setq targets (append tgs targets))
10697 (message "Getting targets...done")
10698 (nreverse targets)))
10700 (defun org-protect-slash (s)
10701 (while (string-match "/" s)
10702 (setq s (replace-match "\\" t t s)))
10705 (defvar org-olpa (make-vector 20 nil))
10707 (defun org-get-outline-path (&optional fastp level heading)
10708 "Return the outline path to the current entry, as a list.
10710 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10711 routine which makes outline path derivations for an entire file,
10712 avoiding backtracing. Refile target collection makes use of that."
10716 (error "Outline path failure, more than 19 levels"))
10717 (loop for i from level upto 19 do
10718 (aset org-olpa i nil))
10720 (delq nil (append org-olpa nil))
10721 (aset org-olpa level heading)))
10722 (let (rtn case-fold-search)
10726 (while (org-up-heading-safe)
10727 (when (looking-at org-complex-heading-regexp)
10728 (push (org-match-string-no-properties 4) rtn)))
10731 (defun org-format-outline-path (path &optional width prefix separator)
10732 "Format the outline path PATH for display.
10733 WIDTH is the maximum number of characters that is available.
10734 PREFIX is a prefix to be included in the returned string,
10735 such as the file name.
10736 SEPARATOR is inserted between the different parts of the path,
10737 the default is \"/\"."
10738 (setq width (or width 79))
10739 (if prefix (setq width (- width (length prefix))))
10742 (let* ((nsteps (length path))
10743 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10744 (maxwidth (if (<= total-width width)
10745 10000 ;; everything fits
10746 ;; we need to shorten the level headings
10747 (/ (- width nsteps) nsteps)))
10748 (org-odd-levels-only nil)
10750 (total (1+ (length prefix))))
10751 (setq maxwidth (max maxwidth 10))
10753 (if prefix (or separator "/"))
10757 (if (and (= n nsteps) (< maxwidth 10000))
10758 (setq maxwidth (- total-width total)))
10759 (if (< (length h) maxwidth)
10760 (progn (setq total (+ total (length h) 1)) h)
10761 (setq h (substring h 0 (- maxwidth 2))
10762 total (+ total maxwidth 1))
10763 (if (string-match "[ \t]+\\'" h)
10764 (setq h (substring h 0 (match-beginning 0))))
10765 (setq h (concat h "..")))
10766 (org-add-props h nil 'face
10767 (nth (% (1- n) org-n-level-faces)
10770 path (or separator "/"))))))
10772 (defun org-display-outline-path (&optional file current separator just-return-string)
10773 "Display the current outline path in the echo area.
10775 If FILE is non-nil, prepend the output with the file name.
10776 If CURRENT is non-nil, append the current heading to the output.
10777 SEPARATOR is passed through to `org-format-outline-path'. It separates
10778 the different parts of the path and defaults to \"/\".
10779 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10781 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10782 (case-fold-search nil)
10783 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10785 (if current (setq path (append path
10787 (org-back-to-heading t)
10788 (if (looking-at org-complex-heading-regexp)
10789 (list (match-string 4)))))))
10791 (org-format-outline-path
10794 (and file bfn (concat (file-name-nondirectory bfn) separator))
10796 (if just-return-string
10797 (org-no-properties res)
10798 (message "%s" res))))
10800 (defvar org-refile-history nil
10801 "History for refiling operations.")
10803 (defvar org-after-refile-insert-hook nil
10804 "Hook run after `org-refile' has inserted its stuff at the new location.
10805 Note that this is still *before* the stuff will be removed from
10806 the *old* location.")
10808 (defvar org-capture-last-stored-marker)
10809 (defvar org-refile-keep nil
10810 "Non-nil means `org-refile' will copy instead of refile.")
10813 "Like `org-refile', but copy."
10815 (let ((org-refile-keep t))
10816 (funcall 'org-refile nil nil nil "Copy")))
10818 (defun org-refile (&optional goto default-buffer rfloc msg)
10819 "Move the entry or entries at point to another heading.
10820 The list of target headings is compiled using the information in
10821 `org-refile-targets', which see.
10823 At the target location, the entry is filed as a subitem of the target
10824 heading. Depending on `org-reverse-note-order', the new subitem will
10825 either be the first or the last subitem.
10827 If there is an active region, all entries in that region will be moved.
10828 However, the region must fulfill the requirement that the first heading
10829 is the first one sets the top-level of the moved text - at most siblings
10830 below it are allowed.
10832 With prefix arg GOTO, the command will only visit the target location
10833 and not actually move anything.
10835 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10836 go to the location where the last refiling operation has put the subtree.
10837 With a prefix argument of `2', refile to the running clock.
10839 RFLOC can be a refile location obtained in a different way.
10841 MSG is a string to replace \"Refile\" in the default prompt with
10842 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10844 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10846 If you are using target caching (see `org-refile-use-cache'),
10847 you have to clear the target cache in order to find new targets.
10848 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10849 prefix argument (`C-u C-u C-u C-c C-w')."
10852 (if (member goto '(0 (64)))
10853 (org-refile-cache-clear)
10854 (let* ((actionmsg (or msg "Refile"))
10855 (cbuf (current-buffer))
10856 (regionp (org-region-active-p))
10857 (region-start (and regionp (region-beginning)))
10858 (region-end (and regionp (region-end)))
10859 (region-length (and regionp (- region-end region-start)))
10860 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10861 pos it nbuf file re level reversed)
10862 (setq last-command nil)
10864 (goto-char region-start)
10865 (or (bolp) (goto-char (point-at-bol)))
10866 (setq region-start (point))
10867 (unless (or (org-kill-is-subtree-p
10868 (buffer-substring region-start region-end))
10869 (prog1 org-refile-active-region-within-subtree
10870 (org-toggle-heading)))
10871 (error "The region is not a (sequence of) subtree(s)")))
10872 (if (equal goto '(16))
10873 (org-refile-goto-last-stored)
10875 (and (equal goto 2)
10876 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10878 (setq it (list (or org-clock-heading "running clock")
10880 (marker-buffer org-clock-hd-marker))
10882 (marker-position org-clock-hd-marker)))
10885 (let (heading-text)
10888 (org-back-to-heading t)
10890 (nth 4 (org-heading-components))))
10892 (org-refile-get-location
10893 (cond (goto "Goto")
10894 (regionp (concat actionmsg " region to"))
10895 (t (concat actionmsg " subtree \""
10896 heading-text "\" to")))
10898 (and (not (equal '(4) goto))
10899 org-refile-allow-creating-parent-nodes)
10901 (setq file (nth 1 it)
10904 (if (and (not goto)
10906 (equal (buffer-file-name) file)
10908 (and (>= pos region-start)
10909 (<= pos region-end))
10910 (and (>= pos (point))
10911 (< pos (save-excursion
10912 (org-end-of-subtree t t))))))
10913 (error "Cannot refile to position inside the tree or region"))
10915 (setq nbuf (or (find-buffer-visiting file)
10916 (find-file-noselect file)))
10919 (org-pop-to-buffer-same-window nbuf)
10921 (org-show-context 'org-goto))
10924 (org-kill-new (buffer-substring region-start region-end))
10925 (org-save-markers-in-region region-start region-end))
10926 (org-copy-subtree 1 nil t))
10927 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10928 (find-file-noselect file)))
10929 (setq reversed (org-notes-order-reversed-p))
10936 (looking-at org-outline-regexp)
10937 (setq level (org-get-valid-level (funcall outline-level) 1))
10940 (or (outline-next-heading) (point-max))
10941 (or (save-excursion (org-get-next-sibling))
10942 (org-end-of-subtree t t)
10946 (goto-char (point-max))
10947 (goto-char (point-min))
10948 (or (outline-next-heading) (goto-char (point-max)))))
10949 (if (not (bolp)) (newline))
10950 (org-paste-subtree level)
10951 (when org-log-refile
10952 (org-add-log-setup 'refile nil nil 'findpos
10954 (unless (eq org-log-refile 'note)
10955 (save-excursion (org-add-log-note))))
10956 (and org-auto-align-tags
10957 (let ((org-loop-over-headlines-in-active-region nil))
10958 (org-set-tags nil t)))
10959 (bookmark-set "org-refile-last-stored")
10960 ;; If we are refiling for capture, make sure that the
10961 ;; last-capture pointers point here
10962 (when (org-bound-and-true-p org-refile-for-capture)
10963 (bookmark-set "org-capture-last-stored-marker")
10964 (move-marker org-capture-last-stored-marker (point)))
10965 (if (fboundp 'deactivate-mark) (deactivate-mark))
10966 (run-hooks 'org-after-refile-insert-hook))))
10967 (unless org-refile-keep
10969 (delete-region (point) (+ (point) region-length))
10970 (org-cut-subtree)))
10971 (when (featurep 'org-inlinetask)
10972 (org-inlinetask-remove-END-maybe))
10973 (setq org-markers-to-move nil)
10974 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
10976 (defun org-refile-goto-last-stored ()
10977 "Go to the location where the last refile was stored."
10979 (bookmark-jump "org-refile-last-stored")
10980 (message "This is the location of the last refile"))
10982 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
10984 "Prompt the user for a refile location, using PROMPT.
10985 PROMPT should not be suffixed with a colon and a space, because
10986 this function appends the default value from
10987 `org-refile-history' automatically, if that is not empty.
10988 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
10989 this is used for the GOTO interface."
10990 (let ((org-refile-targets org-refile-targets)
10991 (org-refile-use-outline-path org-refile-use-outline-path)
10993 (when (and (derived-mode-p 'org-mode)
10994 (not org-refile-use-cache)
10998 (setq excluded-entries
10999 (append excluded-entries (list (org-get-heading t t)))))))
11000 (setq org-refile-target-table
11001 (org-refile-get-targets default-buffer excluded-entries)))
11002 (unless org-refile-target-table
11003 (error "No refile targets"))
11004 (let* ((cbuf (current-buffer))
11005 (partial-completion-mode nil)
11006 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11007 (cfunc (if (and org-refile-use-outline-path
11008 org-outline-path-complete-in-steps)
11009 'org-olpath-completing-read
11010 'org-icompleting-read))
11011 (extra (if org-refile-use-outline-path "/" ""))
11012 (cbnex (concat (buffer-name) extra))
11013 (filename (and cfn (expand-file-name cfn)))
11016 (if (and (not (member org-refile-use-outline-path
11017 '(file full-file-path)))
11018 (not (equal filename (nth 1 x))))
11019 (cons (concat (car x) extra " ("
11020 (file-name-nondirectory (nth 1 x)) ")")
11022 (cons (concat (car x) extra) (cdr x))))
11023 org-refile-target-table))
11024 (completion-ignore-case t)
11026 (prompt (concat prompt
11027 (or (and (car org-refile-history)
11028 (concat " (default " (car org-refile-history) ")"))
11029 (and (assoc cbnex tbl) (setq cdef cbnex)
11030 (concat " (default " cbnex ")"))) ": "))
11031 pa answ parent-target child parent old-hist)
11032 (setq old-hist org-refile-history)
11033 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11034 nil 'org-refile-history (or cdef (car org-refile-history))))
11035 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11036 (org-refile-check-position pa)
11039 (when (or (not org-refile-history)
11040 (not (eq old-hist org-refile-history))
11041 (not (equal (car pa) (car org-refile-history))))
11042 (setq org-refile-history
11043 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11045 (cdr org-refile-history))))
11046 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11047 (pop org-refile-history)))
11049 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11051 (setq parent (match-string 1 answ)
11052 child (match-string 2 answ))
11053 (setq parent-target (or (assoc parent tbl)
11054 (assoc (concat parent "/") tbl)))
11055 (when (and parent-target
11056 (or (eq new-nodes t)
11057 (and (eq new-nodes 'confirm)
11058 (y-or-n-p (format "Create new node \"%s\"? "
11060 (org-refile-new-child parent-target child)))
11061 (error "Invalid target location")))))
11063 (declare-function org-string-nw-p "org-macs" (s))
11064 (defun org-refile-check-position (refile-pointer)
11065 "Check if the refile pointer matches the readline to which it points."
11066 (let* ((file (nth 1 refile-pointer))
11067 (re (nth 2 refile-pointer))
11068 (pos (nth 3 refile-pointer))
11070 (when (org-string-nw-p re)
11071 (setq buffer (if (markerp pos)
11072 (marker-buffer pos)
11073 (or (find-buffer-visiting file)
11074 (find-file-noselect file))))
11075 (with-current-buffer buffer
11080 (beginning-of-line 1)
11081 (unless (org-looking-at-p re)
11082 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11084 (defun org-refile-new-child (parent-target child)
11085 "Use refile target PARENT-TARGET to add new CHILD below it."
11086 (unless parent-target
11087 (error "Cannot find parent for new node"))
11088 (let ((file (nth 1 parent-target))
11089 (pos (nth 3 parent-target))
11091 (with-current-buffer (or (find-buffer-visiting file)
11092 (find-file-noselect file))
11098 (goto-char (point-max))
11099 (if (not (bolp)) (newline)))
11100 (when (looking-at org-outline-regexp)
11101 (setq level (funcall outline-level))
11102 (org-end-of-subtree t t))
11103 (org-back-over-empty-lines)
11104 (insert "\n" (make-string
11105 (if pos (org-get-valid-level level 1) 1) ?*)
11107 (beginning-of-line 0)
11108 (list (concat (car parent-target) "/" child) file "" (point)))))))
11110 (defun org-olpath-completing-read (prompt collection &rest args)
11111 "Read an outline path like a file name."
11112 (let ((thetable collection)
11113 (org-completion-use-ido nil) ; does not work with ido.
11114 (org-completion-use-iswitchb nil)) ; or iswitchb
11116 'org-icompleting-read prompt
11117 (lambda (string predicate &optional flag)
11118 (let (rtn r f (l (length string)))
11122 (try-completion string thetable))
11125 (setq rtn (all-completions string thetable predicate))
11128 (setq r (substring x l))
11129 (if (string-match " ([^)]*)$" x)
11130 (setq f (match-string 0 x))
11132 (if (string-match "/" r)
11133 (concat string (substring r 0 (match-end 0)) f)
11138 (assoc string thetable)))))
11141 ;;;; Dynamic blocks
11143 (defun org-find-dblock (name)
11144 "Find the first dynamic block with name NAME in the buffer.
11145 If not found, stay at current position and return nil."
11146 (let ((case-fold-search t) pos)
11148 (goto-char (point-min))
11149 (setq pos (and (re-search-forward
11150 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11151 (match-beginning 0))))
11152 (if pos (goto-char pos))
11155 (defconst org-dblock-start-re
11156 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11157 "Matches the start line of a dynamic block, with parameters.")
11159 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11160 "Matches the end of a dynamic block.")
11162 (defun org-create-dblock (plist)
11163 "Create a dynamic block section, with parameters taken from PLIST.
11164 PLIST must contain a :name entry which is used as name of the block."
11165 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11168 (let ((col (current-column))
11169 (name (plist-get plist :name)))
11170 (insert "#+BEGIN: " name)
11172 (if (eq (car plist) :name)
11173 (setq plist (cddr plist))
11174 (insert " " (prin1-to-string (pop plist)))))
11175 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11176 (beginning-of-line -2)))
11178 (defun org-prepare-dblock ()
11179 "Prepare dynamic block for refresh.
11180 This empties the block, puts the cursor at the insert position and returns
11181 the property list including an extra property :name with the block name."
11182 (unless (looking-at org-dblock-start-re)
11183 (error "Not at a dynamic block"))
11184 (let* ((begdel (1+ (match-end 0)))
11185 (name (org-no-properties (match-string 1)))
11186 (params (append (list :name name)
11187 (read (concat "(" (match-string 3) ")")))))
11189 (beginning-of-line 1)
11190 (skip-chars-forward " \t")
11191 (setq params (plist-put params :indentation-column (current-column))))
11192 (unless (re-search-forward org-dblock-end-re nil t)
11193 (error "Dynamic block not terminated"))
11196 (list :content (buffer-substring
11197 begdel (match-beginning 0)))))
11198 (delete-region begdel (match-beginning 0))
11203 (defun org-map-dblocks (&optional command)
11204 "Apply COMMAND to all dynamic blocks in the current buffer.
11205 If COMMAND is not given, use `org-update-dblock'."
11206 (let ((cmd (or command 'org-update-dblock)))
11208 (goto-char (point-min))
11209 (while (re-search-forward org-dblock-start-re nil t)
11210 (goto-char (match-beginning 0))
11212 (condition-case nil
11214 (error (message "Error during update of dynamic block"))))
11215 (unless (re-search-forward org-dblock-end-re nil t)
11216 (error "Dynamic block not terminated"))))))
11218 (defun org-dblock-update (&optional arg)
11219 "User command for updating dynamic blocks.
11220 Update the dynamic block at point. With prefix ARG, update all dynamic
11221 blocks in the buffer."
11224 (org-update-all-dblocks)
11225 (or (looking-at org-dblock-start-re)
11226 (org-beginning-of-dblock))
11227 (org-update-dblock)))
11229 (defun org-update-dblock ()
11230 "Update the dynamic block at point.
11231 This means to empty the block, parse for parameters and then call
11232 the correct writing function."
11234 (save-window-excursion
11235 (let* ((pos (point))
11236 (line (org-current-line))
11237 (params (org-prepare-dblock))
11238 (name (plist-get params :name))
11239 (indent (plist-get params :indentation-column))
11240 (cmd (intern (concat "org-dblock-write:" name))))
11241 (message "Updating dynamic block `%s' at line %d..." name line)
11242 (funcall cmd params)
11243 (message "Updating dynamic block `%s' at line %d...done" name line)
11245 (when (and indent (> indent 0))
11246 (setq indent (make-string indent ?\ ))
11248 (org-beginning-of-dblock)
11250 (while (not (looking-at org-dblock-end-re))
11252 (beginning-of-line 2))
11253 (when (looking-at org-dblock-end-re)
11254 (and (looking-at "[ \t]+")
11255 (replace-match ""))
11256 (insert indent)))))))
11258 (defun org-beginning-of-dblock ()
11259 "Find the beginning of the dynamic block at point.
11260 Error if there is no such block at point."
11261 (let ((pos (point))
11264 (if (and (re-search-backward org-dblock-start-re nil t)
11265 (setq beg (match-beginning 0))
11266 (re-search-forward org-dblock-end-re nil t)
11267 (> (match-end 0) pos))
11270 (error "Not in a dynamic block"))))
11272 (defun org-update-all-dblocks ()
11273 "Update all dynamic blocks in the buffer.
11274 This function can be used in a hook."
11276 (when (derived-mode-p 'org-mode)
11277 (org-map-dblocks 'org-update-dblock)))
11282 (defconst org-additional-option-like-keywords
11283 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11284 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11285 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11286 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11288 "ORGTBL" "TBLFM:" "TBLNAME:"
11289 "BEGIN_EXAMPLE" "END_EXAMPLE"
11290 "BEGIN_VERBATIM" "END_VERBATIM"
11291 "BEGIN_QUOTE" "END_QUOTE"
11292 "BEGIN_VERSE" "END_VERSE"
11293 "BEGIN_CENTER" "END_CENTER"
11294 "BEGIN_SRC" "END_SRC"
11295 "BEGIN_RESULT" "END_RESULT"
11296 "BEGIN_lstlisting" "END_lstlisting"
11298 "HEADER:" "HEADERS:"
11299 "COLUMNS:" "PROPERTY:"
11300 "CAPTION:" "LABEL:"
11306 (defconst org-options-keywords
11307 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11308 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11309 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11310 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11311 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11312 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11313 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11315 (defconst org-additional-option-like-keywords-for-flyspell
11318 (mapconcat (lambda(k)
11319 (replace-regexp-in-string
11321 (concat k " " (downcase k) " " (upcase k))))
11322 (append org-options-keywords org-additional-option-like-keywords)
11326 (defcustom org-structure-template-alist
11328 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11329 "<src lang=\"?\">\n\n</src>")
11330 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11331 "<example>\n?\n</example>")
11332 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11333 "<quote>\n?\n</quote>")
11334 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11335 "<verse>\n?\n</verse>")
11336 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11337 "<center>\n?\n</center>")
11338 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11339 "<literal style=\"latex\">\n?\n</literal>")
11341 "<literal style=\"latex\">?</literal>")
11342 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11343 "<literal style=\"html\">\n?\n</literal>")
11345 "<literal style=\"html\">?</literal>")
11346 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11350 ("I" "#+INCLUDE: %file ?"
11351 "<include file=%file markup=\"?\">")
11353 "Structure completion elements.
11354 This is a list of abbreviation keys and values. The value gets inserted
11355 if you type `<' followed by the key and then press the completion key,
11356 usually `M-TAB'. %file will be replaced by a file name after prompting
11357 for the file using completion. The cursor will be placed at the position
11358 of the `?` in the template.
11359 There are two templates for each key, the first uses the original Org syntax,
11360 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11361 the default when the /org-mtags.el/ module has been loaded. See also the
11362 variable `org-mtags-prefer-muse-templates'."
11363 :group 'org-completion
11365 (string :tag "Key")
11366 (string :tag "Template")
11367 (string :tag "Muse Template")))
11369 (defun org-try-structure-completion ()
11370 "Try to complete a structure template before point.
11371 This looks for strings like \"<e\" on an otherwise empty line and
11373 (let ((l (buffer-substring (point-at-bol) (point)))
11375 (when (and (looking-at "[ \t]*$")
11376 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11377 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11378 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11379 (match-beginning 1)) a)
11382 (defun org-complete-expand-structure-template (start cell)
11383 "Expand a structure template."
11384 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11385 (rpl (nth (if musep 2 1) cell))
11387 (delete-region start (point))
11388 (when (string-match "\\`#\\+" rpl)
11391 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11392 (setq ind (buffer-substring (point-at-bol) (point))))
11394 (setq start (point))
11395 (if (string-match "%file" rpl)
11396 (setq rpl (replace-match
11400 (abbreviate-file-name (read-file-name "Include file: ")))
11403 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11404 (concat "\n" ind)))
11406 (if (re-search-backward "\\?" start t) (delete-char 1))))
11408 ;;;; TODO, DEADLINE, Comments
11410 (defun org-toggle-comment ()
11411 "Change the COMMENT state of an entry."
11414 (org-back-to-heading)
11415 (let (case-fold-search)
11417 ((looking-at (format org-heading-keyword-regexp-format
11418 org-comment-string))
11419 (goto-char (match-end 1))
11420 (looking-at (concat " +" org-comment-string))
11421 (replace-match "" t t)
11422 (when (eolp) (insert " ")))
11423 ((looking-at org-outline-regexp)
11424 (goto-char (match-end 0))
11425 (insert org-comment-string " "))))))
11427 (defvar org-last-todo-state-is-todo nil
11428 "This is non-nil when the last TODO state change led to a TODO state.
11429 If the last change removed the TODO tag or switched to DONE, then
11432 (defvar org-setting-tags nil) ; dynamically skipped
11434 (defvar org-todo-setup-filter-hook nil
11435 "Hook for functions that pre-filter todo specs.
11436 Each function takes a todo spec and returns either nil or the spec
11437 transformed into canonical form." )
11439 (defvar org-todo-get-default-hook nil
11440 "Hook for functions that get a default item for todo.
11441 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11442 nil or a string to be used for the todo mark." )
11444 (defvar org-agenda-headline-snapshot-before-repeat)
11446 (defun org-current-effective-time ()
11447 "Return current time adjusted for `org-extend-today-until' variable."
11448 (let* ((ct (org-current-time))
11449 (dct (decode-time ct))
11452 (org-use-last-clock-out-time-as-effective-time
11453 (or (org-clock-get-last-clock-out-time) ct))
11454 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11455 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11459 (defun org-todo-yesterday (&optional arg)
11460 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11462 (if (eq major-mode 'org-agenda-mode)
11463 (apply 'org-agenda-todo-yesterday arg)
11464 (let* ((hour (third (decode-time
11465 (org-current-time))))
11466 (org-extend-today-until (1+ hour)))
11469 (defun org-todo (&optional arg)
11470 "Change the TODO state of an item.
11471 The state of an item is given by a keyword at the start of the heading,
11473 *** TODO Write paper
11476 The different keywords are specified in the variable `org-todo-keywords'.
11477 By default the available states are \"TODO\" and \"DONE\".
11478 So for this example: when the item starts with TODO, it is changed to DONE.
11479 When it starts with DONE, the DONE is removed. And when neither TODO nor
11480 DONE are present, add TODO at the beginning of the heading.
11482 With \\[universal-argument] prefix arg, use completion to determine the new \
11484 With numeric prefix arg, switch to that state.
11485 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11486 keywords (nextset).
11487 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11488 With a numeric prefix arg of 0, inhibit note taking for the change.
11490 For calling through lisp, arg is also interpreted in the following way:
11491 'none -> empty state
11492 \"\"(empty string) -> switch to empty state
11493 'done -> switch to DONE
11494 'nextset -> switch to the next set of keywords
11495 'previousset -> switch to the previous set of keywords
11496 \"WAITING\" -> switch to the specified keyword, but only if it
11497 really is a member of `org-todo-keywords'."
11499 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11500 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11501 'region-start-level 'region))
11502 org-loop-over-headlines-in-active-region)
11505 org-loop-over-headlines-in-active-region
11506 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11507 (if (equal arg '(16)) (setq arg 'nextset))
11508 (let ((org-blocker-hook org-blocker-hook)
11509 (case-fold-search nil))
11510 (when (equal arg '(64))
11511 (setq arg nil org-blocker-hook nil))
11512 (when (and org-blocker-hook
11513 (or org-inhibit-blocking
11514 (org-entry-get nil "NOBLOCKING")))
11515 (setq org-blocker-hook nil))
11518 (org-back-to-heading t)
11519 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11520 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11521 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11522 (let* ((match-data (match-data))
11523 (startpos (point-at-bol))
11524 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11525 (org-log-done org-log-done)
11526 (org-log-repeat org-log-repeat)
11527 (org-todo-log-states org-todo-log-states)
11528 (org-inhibit-logging
11530 (progn (setq arg nil) 'note) org-inhibit-logging))
11531 (this (match-string 1))
11532 (hl-pos (match-beginning 0))
11533 (head (org-get-todo-sequence-head this))
11534 (ass (assoc head org-todo-kwd-alist))
11535 (interpret (nth 1 ass))
11536 (done-word (nth 3 ass))
11537 (final-done-word (nth 4 ass))
11538 (org-last-state (or this ""))
11539 (completion-ignore-case t)
11540 (member (member this org-todo-keywords-1))
11541 (tail (cdr member))
11543 ((and org-todo-key-trigger
11544 (or (and (equal arg '(4))
11545 (eq org-use-fast-todo-selection 'prefix))
11546 (and (not arg) org-use-fast-todo-selection
11547 (not (eq org-use-fast-todo-selection
11549 ;; Use fast selection
11550 (org-fast-todo-selection))
11551 ((and (equal arg '(4))
11552 (or (not org-use-fast-todo-selection)
11553 (not org-todo-key-trigger)))
11554 ;; Read a state with completion
11555 (org-icompleting-read
11556 "State: " (mapcar (lambda(x) (list x))
11557 org-todo-keywords-1)
11561 (if tail (car tail) nil)
11562 (car org-todo-keywords-1)))
11564 (if (equal member org-todo-keywords-1)
11567 (nth (- (length org-todo-keywords-1)
11569 org-todo-keywords-1)
11570 (org-last org-todo-keywords-1))))
11571 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11572 (setq arg nil))) ; hack to fall back to cycling
11574 ;; user or caller requests a specific state
11576 ((equal arg "") nil)
11577 ((eq arg 'none) nil)
11578 ((eq arg 'done) (or done-word (car org-done-keywords)))
11580 (or (car (cdr (member head org-todo-heads)))
11581 (car org-todo-heads)))
11582 ((eq arg 'previousset)
11583 (let ((org-todo-heads (reverse org-todo-heads)))
11584 (or (car (cdr (member head org-todo-heads)))
11585 (car org-todo-heads))))
11586 ((car (member arg org-todo-keywords-1)))
11588 (error "State `%s' not valid in this file" arg))
11589 ((nth (1- (prefix-numeric-value arg))
11590 org-todo-keywords-1))))
11591 ((null member) (or head (car org-todo-keywords-1)))
11592 ((equal this final-done-word) nil) ;; -> make empty
11593 ((null tail) nil) ;; -> first entry
11594 ((memq interpret '(type priority))
11595 (if (eq this-command last-command)
11597 (if (> (length tail) 0)
11598 (or done-word (car org-done-keywords))
11603 (run-hook-with-args-until-success
11604 'org-todo-get-default-hook org-state org-last-state)
11606 (next (if org-state (concat " " org-state " ") " "))
11607 (change-plist (list :type 'todo-state-change :from this :to org-state
11608 :position startpos))
11610 (when org-blocker-hook
11611 (setq org-last-todo-state-is-todo
11612 (not (member this org-done-keywords)))
11613 (unless (save-excursion
11615 (org-with-wide-buffer
11616 (run-hook-with-args-until-failure
11617 'org-blocker-hook change-plist))))
11618 (if (org-called-interactively-p 'interactive)
11619 (error "TODO state change from %s to %s blocked" this org-state)
11621 (message "TODO state change from %s to %s blocked" this org-state)
11622 (throw 'exit nil))))
11623 (store-match-data match-data)
11624 (replace-match next t t)
11625 (unless (pos-visible-in-window-p hl-pos)
11626 (message "TODO state changed to %s" (org-trim next)))
11628 (setq head (org-get-todo-sequence-head org-state)
11629 ass (assoc head org-todo-kwd-alist)
11630 interpret (nth 1 ass)
11631 done-word (nth 3 ass)
11632 final-done-word (nth 4 ass)))
11633 (when (memq arg '(nextset previousset))
11634 (message "Keyword-Set %d/%d: %s"
11635 (- (length org-todo-sets) -1
11636 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11637 (length org-todo-sets)
11638 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11639 (setq org-last-todo-state-is-todo
11640 (not (member org-state org-done-keywords)))
11641 (setq now-done-p (and (member org-state org-done-keywords)
11642 (not (member this org-done-keywords))))
11643 (and logging (org-local-logging logging))
11644 (when (and (or org-todo-log-states org-log-done)
11645 (not (eq org-inhibit-logging t))
11646 (not (memq arg '(nextset previousset))))
11647 ;; we need to look at recording a time and note
11648 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11649 (nth 2 (assoc this org-todo-log-states))))
11650 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11651 (setq dolog 'time))
11652 (when (and org-state
11653 (member org-state org-not-done-keywords)
11654 (not (member this org-not-done-keywords)))
11655 ;; This is now a todo state and was not one before
11656 ;; If there was a CLOSED time stamp, get rid of it.
11657 (org-add-planning-info nil nil 'closed))
11658 (when (and now-done-p org-log-done)
11659 ;; It is now done, and it was not done before
11660 (org-add-planning-info 'closed (org-current-effective-time))
11661 (if (and (not dolog) (eq 'note org-log-done))
11662 (org-add-log-setup 'done org-state this 'findpos 'note)))
11663 (when (and org-state dolog)
11664 ;; This is a non-nil state, and we need to log it
11665 (org-add-log-setup 'state org-state this 'findpos dolog)))
11666 ;; Fixup tag positioning
11667 (org-todo-trigger-tag-changes org-state)
11668 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11669 (when org-provide-todo-statistics
11670 (org-update-parent-todo-statistics))
11671 (run-hooks 'org-after-todo-state-change-hook)
11672 (if (and arg (not (member org-state org-done-keywords)))
11673 (setq head (org-get-todo-sequence-head org-state)))
11674 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11675 ;; Do we need to trigger a repeat?
11677 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11678 ;; This is for the agenda, take a snapshot of the headline.
11680 (setq org-agenda-headline-snapshot-before-repeat
11681 (org-get-heading))))
11682 (org-auto-repeat-maybe org-state))
11683 ;; Fixup cursor location if close to the keyword
11684 (if (and (outline-on-heading-p)
11686 (save-excursion (beginning-of-line 1)
11687 (looking-at org-todo-line-regexp))
11688 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11690 (goto-char (or (match-end 2) (match-end 1)))
11691 (and (looking-at " ") (just-one-space))))
11692 (when org-trigger-hook
11694 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11696 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11697 "Block turning an entry into a TODO, using the hierarchy.
11698 This checks whether the current task should be blocked from state
11699 changes. Such blocking occurs when:
11701 1. The task has children which are not all in a completed state.
11703 2. A task has a parent with the property :ORDERED:, and there
11704 are siblings prior to the current task with incomplete
11707 3. The parent of the task is blocked because it has siblings that should
11708 be done first, or is child of a block grandparent TODO entry."
11710 (if (not org-enforce-todo-dependencies)
11711 t ; if locally turned off don't block
11713 ;; If this is not a todo state change, or if this entry is already DONE,
11715 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11716 (member (plist-get change-plist :from)
11717 (cons 'done org-done-keywords))
11718 (member (plist-get change-plist :to)
11719 (cons 'todo org-not-done-keywords))
11720 (not (plist-get change-plist :to)))
11721 (throw 'dont-block t))
11722 ;; If this task has children, and any are undone, it's blocked
11724 (org-back-to-heading t)
11725 (let ((this-level (funcall outline-level)))
11726 (outline-next-heading)
11727 (let ((child-level (funcall outline-level)))
11728 (while (and (not (eobp))
11729 (> child-level this-level))
11730 ;; this todo has children, check whether they are all
11732 (if (and (not (org-entry-is-done-p))
11733 (org-entry-is-todo-p))
11734 (throw 'dont-block nil))
11735 (outline-next-heading)
11736 (setq child-level (funcall outline-level))))))
11737 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11738 ;; any previous siblings are undone, it's blocked
11740 (org-back-to-heading t)
11741 (let* ((pos (point))
11742 (parent-pos (and (org-up-heading-safe) (point))))
11743 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11744 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11746 (re-search-forward org-not-done-heading-regexp pos t))
11747 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11748 ;; Search further up the hierarchy, to see if an ancestor is blocked
11750 (goto-char parent-pos)
11751 (if (not (looking-at org-not-done-heading-regexp))
11752 (throw 'dont-block t)) ; do not block, parent is not a TODO
11754 (setq parent-pos (and (org-up-heading-safe) (point)))
11755 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11756 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11758 (re-search-forward org-not-done-heading-regexp pos t))
11759 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11761 (defcustom org-track-ordered-property-with-tag nil
11762 "Should the ORDERED property also be shown as a tag?
11763 The ORDERED property decides if an entry should require subtasks to be
11764 completed in sequence. Since a property is not very visible, setting
11765 this option means that toggling the ORDERED property with the command
11766 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11767 not relevant for the behavior, but it makes things more visible.
11769 Note that toggling the tag with tags commands will not change the property
11770 and therefore not influence behavior!
11772 This can be t, meaning the tag ORDERED should be used, It can also be a
11773 string to select a different tag for this task."
11776 (const :tag "No tracking" nil)
11777 (const :tag "Track with ORDERED tag" t)
11778 (string :tag "Use other tag")))
11780 (defun org-toggle-ordered-property ()
11781 "Toggle the ORDERED property of the current entry.
11782 For better visibility, you can track the value of this property with a tag.
11783 See variable `org-track-ordered-property-with-tag'."
11785 (let* ((t1 org-track-ordered-property-with-tag)
11786 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11788 (org-back-to-heading)
11789 (if (org-entry-get nil "ORDERED")
11791 (org-delete-property "ORDERED")
11792 (and tag (org-toggle-tag tag 'off))
11793 (message "Subtasks can be completed in arbitrary order"))
11794 (org-entry-put nil "ORDERED" "t")
11795 (and tag (org-toggle-tag tag 'on))
11796 (message "Subtasks must be completed in sequence")))))
11798 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11799 (defun org-block-todo-from-checkboxes (change-plist)
11800 "Block turning an entry into a TODO, using checkboxes.
11801 This checks whether the current task should be blocked from state
11802 changes because there are unchecked boxes in this entry."
11803 (if (not org-enforce-todo-checkbox-dependencies)
11804 t ; if locally turned off don't block
11806 ;; If this is not a todo state change, or if this entry is already DONE,
11808 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11809 (member (plist-get change-plist :from)
11810 (cons 'done org-done-keywords))
11811 (member (plist-get change-plist :to)
11812 (cons 'todo org-not-done-keywords))
11813 (not (plist-get change-plist :to)))
11814 (throw 'dont-block t))
11815 ;; If this task has checkboxes that are not checked, it's blocked
11817 (org-back-to-heading t)
11818 (let ((beg (point)) end)
11819 (outline-next-heading)
11822 (if (org-list-search-forward
11823 (concat (org-item-beginning-re)
11824 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11828 (if (boundp 'org-blocked-by-checkboxes)
11829 (setq org-blocked-by-checkboxes t))
11830 (throw 'dont-block nil)))))
11831 t))) ; do not block
11833 (defun org-entry-blocked-p ()
11834 "Is the current entry blocked?"
11835 (if (org-entry-get nil "NOBLOCKING")
11836 nil ;; Never block this entry
11838 (run-hook-with-args-until-failure
11840 (list :type 'todo-state-change
11845 (defun org-update-statistics-cookies (all)
11846 "Update the statistics cookie, either from TODO or from checkboxes.
11847 This should be called with the cursor in a line with a statistics cookie."
11851 (org-update-checkbox-count 'all)
11852 (org-map-entries 'org-update-parent-todo-statistics))
11853 (if (not (org-at-heading-p))
11854 (org-update-checkbox-count)
11855 (let ((pos (move-marker (make-marker) (point)))
11857 (ignore-errors (org-back-to-heading t))
11858 (if (not (org-at-heading-p))
11859 (org-update-checkbox-count)
11860 (setq l1 (org-outline-level))
11861 (setq end (save-excursion
11862 (outline-next-heading)
11863 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11865 (if (and (save-excursion
11867 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11868 (not (save-excursion (re-search-forward
11869 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11870 (org-update-checkbox-count)
11871 (if (and l2 (> l2 l1))
11874 (org-update-parent-todo-statistics))
11876 (beginning-of-line 1)
11877 (while (re-search-forward
11878 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11880 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11882 (move-marker pos nil)))))
11884 (defvar org-entry-property-inherited-from) ;; defined below
11885 (defun org-update-parent-todo-statistics ()
11886 "Update any statistics cookie in the parent of the current headline.
11887 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11888 the entire subtree and this will travel up the hierarchy and update
11889 statistics everywhere."
11890 (let* ((prop (save-excursion (org-up-heading-safe)
11891 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11892 (recursive (or (not org-hierarchical-todo-statistics)
11893 (and prop (string-match "\\<recursive\\>" prop))))
11894 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11897 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11898 level ltoggle l1 new ndel
11899 (cnt-all 0) (cnt-done 0) is-percent kwd
11900 checkbox-beg ov ovs ove cookie-present)
11903 (beginning-of-line 1)
11904 (setq ltoggle (funcall outline-level))
11905 ;; Three situations are to consider:
11907 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11908 ;; to the top-level ancestor on the headline;
11910 ;; 2. If parent has "recursive" property, repeat up to the
11911 ;; headline setting that property, taking inheritance into
11914 ;; 3. Else, move up to direct parent and proceed only once.
11915 (while (and (setq level (org-up-heading-safe))
11916 (or recursive first)
11918 (setq first nil cookie-present nil)
11922 (downcase (or (org-entry-get nil "COOKIE_DATA")
11925 (while (re-search-forward box-re (point-at-eol) t)
11926 (setq cnt-all 0 cnt-done 0 cookie-present t)
11927 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11929 (unless (outline-next-heading) (throw 'exit nil))
11930 (while (and (looking-at org-complex-heading-regexp)
11931 (> (setq l1 (length (match-string 1))) level))
11932 (setq kwd (and (or recursive (= l1 ltoggle))
11934 (if (or (eq org-provide-todo-statistics 'all-headlines)
11935 (and (listp org-provide-todo-statistics)
11936 (or (member kwd org-provide-todo-statistics)
11937 (member kwd org-done-keywords))))
11938 (setq cnt-all (1+ cnt-all))
11939 (if (eq org-provide-todo-statistics t)
11940 (and kwd (setq cnt-all (1+ cnt-all)))))
11941 (and (member kwd org-done-keywords)
11942 (setq cnt-done (1+ cnt-done)))
11943 (outline-next-heading)))
11946 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11947 (format "[%d/%d]" cnt-done cnt-all))
11948 ndel (- (match-end 0) checkbox-beg))
11949 ;; handle overlays when updating cookie from column view
11950 (when (setq ov (car (overlays-at checkbox-beg)))
11951 (setq ovs (overlay-start ov) ove (overlay-end ov))
11952 (delete-overlay ov))
11953 (goto-char checkbox-beg)
11955 (delete-region (point) (+ (point) ndel))
11956 (when org-auto-align-tags (org-fix-tags-on-the-fly))
11957 (when ov (move-overlay ov ovs ove)))
11958 (when cookie-present
11959 (run-hook-with-args 'org-after-todo-statistics-hook
11960 cnt-done (- cnt-all cnt-done))))))
11961 (run-hooks 'org-todo-statistics-hook)))
11963 (defvar org-after-todo-statistics-hook nil
11964 "Hook that is called after a TODO statistics cookie has been updated.
11965 Each function is called with two arguments: the number of not-done entries
11966 and the number of done entries.
11968 For example, the following function, when added to this hook, will switch
11969 an entry to DONE when all children are done, and back to TODO when new
11970 entries are set to a TODO status. Note that this hook is only called
11971 when there is a statistics cookie in the headline!
11973 (defun org-summary-todo (n-done n-not-done)
11974 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
11975 (let (org-log-done org-log-states) ; turn off logging
11976 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
11979 (defvar org-todo-statistics-hook nil
11980 "Hook that is run whenever Org thinks TODO statistics should be updated.
11981 This hook runs even if there is no statistics cookie present, in which case
11982 `org-after-todo-statistics-hook' would not run.")
11984 (defun org-todo-trigger-tag-changes (state)
11985 "Apply the changes defined in `org-todo-state-tags-triggers'."
11986 (let ((l org-todo-state-tags-triggers)
11988 (when (or (not state) (equal state ""))
11989 (setq changes (append changes (cdr (assoc "" l)))))
11990 (when (and (stringp state) (> (length state) 0))
11991 (setq changes (append changes (cdr (assoc state l)))))
11992 (when (member state org-not-done-keywords)
11993 (setq changes (append changes (cdr (assoc 'todo l)))))
11994 (when (member state org-done-keywords)
11995 (setq changes (append changes (cdr (assoc 'done l)))))
11996 (dolist (c changes)
11997 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
11999 (defun org-local-logging (value)
12000 "Get logging settings from a property VALUE."
12002 ;; directly set the variables, they are already local.
12003 (setq org-log-done nil
12005 org-todo-log-states nil)
12006 (setq words (org-split-string value))
12007 (while (setq w (pop words))
12009 ((setq a (assoc w org-startup-options))
12010 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12011 (set (nth 1 a) (nth 2 a))))
12012 ((setq a (org-extract-log-state-settings w))
12013 (and (member (car a) org-todo-keywords-1)
12014 (push a org-todo-log-states)))))))
12016 (defun org-get-todo-sequence-head (kwd)
12017 "Return the head of the TODO sequence to which KWD belongs.
12018 If KWD is not set, check if there is a text property remembering the
12023 (or (get-text-property (point-at-bol) 'org-todo-head)
12025 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12026 nil (point-at-eol)))
12027 (get-text-property p 'org-todo-head))))
12028 ((not (member kwd org-todo-keywords-1))
12029 (car org-todo-keywords-1))
12030 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12032 (defun org-fast-todo-selection ()
12033 "Fast TODO keyword selection with single keys.
12034 Returns the new TODO keyword, or nil if no state change should occur."
12035 (let* ((fulltable org-todo-key-alist)
12036 (done-keywords org-done-keywords) ;; needed for the faces.
12037 (maxlen (apply 'max (mapcar
12039 (if (stringp (car x)) (string-width (car x)) 0))
12042 (fwidth (+ maxlen 3 1 3))
12043 (ncol (/ (- (window-width) 4) fwidth))
12047 (save-window-excursion
12049 (set-buffer (get-buffer-create " *Org todo*"))
12050 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12052 (org-set-local 'org-done-keywords done-keywords)
12053 (setq tbl fulltable cnt 0)
12054 (while (setq e (pop tbl))
12056 ((equal e '(:startgroup))
12057 (push '() groups) (setq ingroup t)
12058 (when (not (= cnt 0))
12062 ((equal e '(:endgroup))
12063 (setq ingroup nil cnt 0)
12065 ((equal e '(:newline))
12066 (when (not (= cnt 0))
12070 (while (equal (car tbl) '(:newline))
12072 (setq tbl (cdr tbl)))))
12074 (setq tg (car e) c (cdr e))
12075 (if ingroup (push tg (car groups)))
12076 (setq tg (org-add-props tg nil 'face
12077 (org-get-todo-face tg)))
12078 (if (and (= cnt 0) (not ingroup)) (insert " "))
12079 (insert "[" c "] " tg (make-string
12080 (- fwidth 4 (length tg)) ?\ ))
12081 (when (= (setq cnt (1+ cnt)) ncol)
12083 (if ingroup (insert " "))
12086 (goto-char (point-min))
12087 (if (not expert) (org-fit-window-to-buffer))
12088 (message "[a-z..]:Set [SPC]:clear")
12089 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12092 (and (= c ?q) (not (rassoc c fulltable))))
12093 (setq quit-flag t))
12095 ((setq e (rassoc c fulltable) tg (car e))
12097 (t (setq quit-flag t)))))))
12099 (defun org-entry-is-todo-p ()
12100 (member (org-get-todo-state) org-not-done-keywords))
12102 (defun org-entry-is-done-p ()
12103 (member (org-get-todo-state) org-done-keywords))
12105 (defun org-get-todo-state ()
12107 (org-back-to-heading t)
12108 (and (looking-at org-todo-line-regexp)
12110 (match-string 2))))
12112 (defun org-at-date-range-p (&optional inactive-ok)
12113 "Is the cursor inside a date range?"
12117 (let ((pos (point)))
12118 (skip-chars-backward "^[<\r\n")
12119 (skip-chars-backward "<[")
12120 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12121 (>= (match-end 0) pos)
12123 (skip-chars-backward "^<[\r\n")
12124 (skip-chars-backward "<[")
12125 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12126 (>= (match-end 0) pos)
12130 (defun org-get-repeat (&optional tagline)
12131 "Check if there is a deadline/schedule with repeater in this entry."
12134 (org-back-to-heading t)
12135 (and (re-search-forward (if tagline
12136 (concat tagline "\\s-*" org-repeat-re)
12138 (org-entry-end-position) t)
12139 (match-string-no-properties 1)))))
12141 (defvar org-last-changed-timestamp)
12142 (defvar org-last-inserted-timestamp)
12143 (defvar org-log-post-message)
12144 (defvar org-log-note-purpose)
12145 (defvar org-log-note-how)
12146 (defvar org-log-note-extra)
12147 (defun org-auto-repeat-maybe (done-word)
12148 "Check if the current headline contains a repeated deadline/schedule.
12149 If yes, set TODO state back to what it was and change the base date
12150 of repeating deadline/scheduled time stamps to new date.
12151 This function is run automatically after each state change to a DONE state."
12152 ;; last-state is dynamically scoped into this function
12153 (let* ((repeat (org-get-repeat))
12154 (aa (assoc org-last-state org-todo-kwd-alist))
12155 (interpret (nth 1 aa))
12157 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12158 (msg "Entry repeats: ")
12160 (org-todo-log-states nil)
12161 re type n what ts time to-state)
12163 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12164 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12165 org-todo-repeat-to-state))
12166 (unless (and to-state (member to-state org-todo-keywords-1))
12167 (setq to-state (if (eq interpret 'type) org-last-state head)))
12168 (org-todo to-state)
12169 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12170 (org-entry-put nil "LAST_REPEAT" (format-time-string
12171 (org-time-stamp-format t t))))
12172 (when org-log-repeat
12173 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12174 (memq 'org-add-log-note post-command-hook))
12175 ;; OK, we are already setup for some record
12176 (if (eq org-log-repeat 'note)
12177 ;; make sure we take a note, not only a time stamp
12178 (setq org-log-note-how 'note))
12179 ;; Set up for taking a record
12180 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12182 'findpos org-log-repeat)))
12183 (org-back-to-heading t)
12184 (org-add-planning-info nil nil 'closed)
12185 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12186 org-deadline-time-regexp "\\)\\|\\("
12187 org-ts-regexp "\\)"))
12188 (while (re-search-forward
12189 re (save-excursion (outline-next-heading) (point)) t)
12190 (setq type (if (match-end 1) org-scheduled-string
12191 (if (match-end 3) org-deadline-string "Plain:"))
12192 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12193 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12194 (setq n (string-to-number (match-string 2 ts))
12195 what (match-string 3 ts))
12196 (if (equal what "w") (setq n (* n 7) what "d"))
12197 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12198 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12199 ;; Preparation, see if we need to modify the start date for the change
12200 (when (match-end 1)
12201 (setq time (save-match-data (org-time-string-to-time ts)))
12203 ((equal (match-string 1 ts) ".")
12204 ;; Shift starting date to today
12205 (org-timestamp-change
12206 (- (org-today) (time-to-days time))
12208 ((equal (match-string 1 ts) "+")
12209 (let ((nshiftmax 10) (nshift 0))
12210 (while (or (= nshift 0)
12211 (<= (time-to-days time)
12212 (time-to-days (current-time))))
12213 (when (= (incf nshift) nshiftmax)
12214 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12216 (org-timestamp-change n (cdr (assoc what whata)))
12217 (org-at-timestamp-p t)
12218 (setq ts (match-string 1))
12219 (setq time (save-match-data (org-time-string-to-time ts)))))
12220 (org-timestamp-change (- n) (cdr (assoc what whata)))
12221 ;; rematch, so that we have everything in place for the real shift
12222 (org-at-timestamp-p t)
12223 (setq ts (match-string 1))
12224 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12225 (org-timestamp-change n (cdr (assoc what whata)))
12226 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12227 (setq org-log-post-message msg)
12228 (message "%s" msg))))
12230 (defun org-show-todo-tree (arg)
12231 "Make a compact tree which shows all headlines marked with TODO.
12232 The tree will show the lines where the regexp matches, and all higher
12233 headlines above the match.
12234 With a \\[universal-argument] prefix, prompt for a regexp to match.
12235 With a numeric prefix N, construct a sparse tree for the Nth element
12236 of `org-todo-keywords-1'."
12238 (let ((case-fold-search nil)
12240 (cond ((null arg) org-not-done-regexp)
12242 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12243 (mapcar 'list org-todo-keywords-1))))
12245 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12247 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12248 (regexp-quote (nth (1- (prefix-numeric-value arg))
12249 org-todo-keywords-1)))
12250 (t (error "Invalid prefix argument: %s" arg)))))
12251 (message "%d TODO entries found"
12252 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12254 (defun org-deadline (&optional remove time)
12255 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12256 With argument REMOVE, remove any deadline from the item.
12257 With argument TIME, set the deadline at the corresponding date. TIME
12258 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12260 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12261 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12262 'region-start-level 'region))
12263 org-loop-over-headlines-in-active-region)
12265 `(org-deadline ',remove ,time)
12266 org-loop-over-headlines-in-active-region
12267 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12268 (let* ((old-date (org-entry-get nil "DEADLINE"))
12269 (repeater (and old-date
12271 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12273 (match-string 1 old-date))))
12276 (when (and old-date org-log-redeadline)
12277 (org-add-log-setup 'deldeadline nil old-date 'findpos
12278 org-log-redeadline))
12279 (org-remove-timestamp-with-keyword org-deadline-string)
12280 (message "Item no longer has a deadline."))
12281 (org-add-planning-info 'deadline time 'closed)
12282 (when (and old-date org-log-redeadline
12283 (not (equal old-date
12284 (substring org-last-inserted-timestamp 1 -1))))
12285 (org-add-log-setup 'redeadline nil old-date 'findpos
12286 org-log-redeadline))
12289 (org-back-to-heading t)
12290 (when (re-search-forward (concat org-deadline-string " "
12291 org-last-inserted-timestamp)
12293 (outline-next-heading) (point)) t)
12294 (goto-char (1- (match-end 0)))
12295 (insert " " repeater)
12296 (setq org-last-inserted-timestamp
12297 (concat (substring org-last-inserted-timestamp 0 -1)
12299 (substring org-last-inserted-timestamp -1))))))
12300 (message "Deadline on %s" org-last-inserted-timestamp)))))
12302 (defun org-schedule (&optional remove time)
12303 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12304 With argument REMOVE, remove any scheduling date from the item.
12305 With argument TIME, scheduled at the corresponding date. TIME can
12306 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12308 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12309 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12310 'region-start-level 'region))
12311 org-loop-over-headlines-in-active-region)
12313 `(org-schedule ',remove ,time)
12314 org-loop-over-headlines-in-active-region
12315 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12316 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12317 (repeater (and old-date
12319 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12321 (match-string 1 old-date))))
12324 (when (and old-date org-log-reschedule)
12325 (org-add-log-setup 'delschedule nil old-date 'findpos
12326 org-log-reschedule))
12327 (org-remove-timestamp-with-keyword org-scheduled-string)
12328 (message "Item is no longer scheduled."))
12329 (org-add-planning-info 'scheduled time 'closed)
12330 (when (and old-date org-log-reschedule
12331 (not (equal old-date
12332 (substring org-last-inserted-timestamp 1 -1))))
12333 (org-add-log-setup 'reschedule nil old-date 'findpos
12334 org-log-reschedule))
12337 (org-back-to-heading t)
12338 (when (re-search-forward (concat org-scheduled-string " "
12339 org-last-inserted-timestamp)
12341 (outline-next-heading) (point)) t)
12342 (goto-char (1- (match-end 0)))
12343 (insert " " repeater)
12344 (setq org-last-inserted-timestamp
12345 (concat (substring org-last-inserted-timestamp 0 -1)
12347 (substring org-last-inserted-timestamp -1))))))
12348 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12350 (defun org-get-scheduled-time (pom &optional inherit)
12351 "Get the scheduled time as a time tuple, of a format suitable
12352 for calling org-schedule with, or if there is no scheduling,
12354 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12356 (apply 'encode-time (org-parse-time-string time)))))
12358 (defun org-get-deadline-time (pom &optional inherit)
12359 "Get the deadline as a time tuple, of a format suitable for
12360 calling org-deadline with, or if there is no scheduling, returns
12362 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12364 (apply 'encode-time (org-parse-time-string time)))))
12366 (defun org-remove-timestamp-with-keyword (keyword)
12367 "Remove all time stamps with KEYWORD in the current entry."
12368 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12371 (org-back-to-heading t)
12373 (outline-next-heading)
12374 (while (re-search-backward re beg t)
12376 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12377 (equal (char-before) ?\ ))
12378 (backward-delete-char 1)
12379 (if (string-match "^[ \t]*$" (buffer-substring
12380 (point-at-bol) (point-at-eol)))
12381 (delete-region (point-at-bol)
12382 (min (point-max) (1+ (point-at-eol))))))))))
12384 (defun org-add-planning-info (what &optional time &rest remove)
12385 "Insert new timestamp with keyword in the line directly after the headline.
12386 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12387 If non is given, the user is prompted for a date.
12388 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12391 (let (org-time-was-given org-end-time-was-given ts
12392 end default-time default-input)
12395 (when (and (memq what '(scheduled deadline))
12397 (and (stringp time)
12398 (string-match "^[-+]+[0-9]" time))))
12399 ;; Try to get a default date/time from existing timestamp
12401 (org-back-to-heading t)
12402 (setq end (save-excursion (outline-next-heading) (point)))
12403 (when (re-search-forward (if (eq what 'scheduled)
12404 org-scheduled-time-regexp
12405 org-deadline-time-regexp)
12407 (setq ts (match-string 1)
12409 (apply 'encode-time (org-parse-time-string ts))
12410 default-input (and ts (org-get-compact-tod ts))))))
12414 ;; This is a string (relative or absolute), set proper date
12415 (apply 'encode-time
12416 (org-read-date-analyze
12417 time default-time (decode-time default-time)))
12418 ;; If necessary, get the time from the user
12419 (or time (org-read-date nil 'to-time nil nil
12420 default-time default-input)))))
12422 (when (and org-insert-labeled-timestamps-at-point
12423 (member what '(scheduled deadline)))
12425 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12426 (org-insert-time-stamp time org-time-was-given
12427 nil nil nil (list org-end-time-was-given))
12431 (let (col list elt ts buffer-invisibility-spec)
12432 (org-back-to-heading t)
12433 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12434 (goto-char (match-end 1))
12435 (setq col (current-column))
12436 (goto-char (match-end 0))
12437 (if (eobp) (insert "\n") (forward-char 1))
12438 (when (and (not what)
12441 org-keyword-time-not-clock-regexp))))
12442 ;; Nothing to add, nothing to remove...... :-)
12444 (if (and (not (looking-at org-outline-regexp))
12445 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12447 (not (equal (match-string 1) org-clock-string)))
12448 (narrow-to-region (match-beginning 0) (match-end 0))
12449 (insert-before-markers "\n")
12451 (narrow-to-region (point) (point))
12452 (and org-adapt-indentation (org-indent-to-column col)))
12453 ;; Check if we have to remove something.
12454 (setq list (cons what remove))
12456 (setq elt (pop list))
12457 (when (or (and (eq elt 'scheduled)
12458 (re-search-forward org-scheduled-time-regexp nil t))
12459 (and (eq elt 'deadline)
12460 (re-search-forward org-deadline-time-regexp nil t))
12461 (and (eq elt 'closed)
12462 (re-search-forward org-closed-time-regexp nil t)))
12464 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12465 (and (looking-at "[ \t]+") (replace-match ""))
12466 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12469 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12470 (cond ((eq what 'scheduled) org-scheduled-string)
12471 ((eq what 'deadline) org-deadline-string)
12472 ((eq what 'closed) org-closed-string))
12474 (setq ts (org-insert-time-stamp
12476 (or org-time-was-given
12477 (and (eq what 'closed) org-log-done-with-time))
12479 nil nil (list org-end-time-was-given)))
12481 (if (not (or (bolp) (eq (char-before) ?\ )
12482 (memq (char-after) '(32 10))
12485 (goto-char (point-min))
12487 (if (and (looking-at "[ \t]*\n")
12488 (equal (char-before) ?\n))
12489 (delete-region (1- (point)) (point-at-eol)))
12492 (defvar org-log-note-marker (make-marker))
12493 (defvar org-log-note-purpose nil)
12494 (defvar org-log-note-state nil)
12495 (defvar org-log-note-previous-state nil)
12496 (defvar org-log-note-how nil)
12497 (defvar org-log-note-extra nil)
12498 (defvar org-log-note-window-configuration nil)
12499 (defvar org-log-note-return-to (make-marker))
12500 (defvar org-log-note-effective-time nil
12501 "Remembered current time so that dynamically scoped
12502 `org-extend-today-until' affects tha timestamps in state change
12505 (defvar org-log-post-message nil
12506 "Message to be displayed after a log note has been stored.
12507 The auto-repeater uses this.")
12509 (defun org-add-note ()
12510 "Add a note to the current entry.
12511 This is done in the same way as adding a state change note."
12513 (org-add-log-setup 'note nil nil 'findpos nil))
12515 (defvar org-property-end-re)
12516 (defun org-add-log-setup (&optional purpose state prev-state
12518 "Set up the post command hook to take a note.
12519 If this is about to TODO state change, the new state is expected in STATE.
12520 When FINDPOS is non-nil, find the correct position for the note in
12521 the current entry. If not, assume that it can be inserted at point.
12522 HOW is an indicator what kind of note should be created.
12523 EXTRA is additional text that will be inserted into the notes buffer."
12524 (let* ((org-log-into-drawer (org-log-into-drawer))
12525 (drawer (cond ((stringp org-log-into-drawer)
12526 org-log-into-drawer)
12527 (org-log-into-drawer "LOGBOOK"))))
12531 (org-back-to-heading t)
12532 (narrow-to-region (point) (save-excursion
12533 (outline-next-heading) (point)))
12534 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12535 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12537 (goto-char (match-end 0))
12540 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12543 (goto-char (match-end 0))
12544 (or org-log-states-order-reversed
12545 (and (re-search-forward org-property-end-re nil t)
12546 (goto-char (1- (match-beginning 0))))))
12547 (insert "\n:" drawer ":\n:END:")
12548 (beginning-of-line 0)
12550 (beginning-of-line 2)
12553 ((and org-log-state-notes-insert-after-drawers
12555 (forward-line) (looking-at org-drawer-regexp)))
12557 (while (looking-at org-drawer-regexp)
12558 (goto-char (match-end 0))
12559 (re-search-forward org-property-end-re (point-max) t)
12561 (forward-line -1)))
12562 (unless org-log-states-order-reversed
12563 (and (= (char-after) ?\n) (forward-char 1))
12564 (org-skip-over-state-notes)
12565 (skip-chars-backward " \t\n\r")))
12566 (move-marker org-log-note-marker (point))
12567 (setq org-log-note-purpose purpose
12568 org-log-note-state state
12569 org-log-note-previous-state prev-state
12570 org-log-note-how how
12571 org-log-note-extra extra
12572 org-log-note-effective-time (org-current-effective-time))
12573 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12575 (defun org-skip-over-state-notes ()
12576 "Skip past the list of State notes in an entry."
12577 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12578 (when (ignore-errors (goto-char (org-in-item-p)))
12579 (let* ((struct (org-list-struct))
12580 (prevs (org-list-prevs-alist struct)))
12581 (while (looking-at "[ \t]*- State")
12582 (goto-char (or (org-list-get-next-item (point) struct prevs)
12583 (org-list-get-item-end (point) struct)))))))
12585 (defun org-add-log-note (&optional purpose)
12586 "Pop up a window for taking a note, and add this note later at point."
12587 (remove-hook 'post-command-hook 'org-add-log-note)
12588 (setq org-log-note-window-configuration (current-window-configuration))
12589 (delete-other-windows)
12590 (move-marker org-log-note-return-to (point))
12591 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12592 (goto-char org-log-note-marker)
12593 (org-switch-to-buffer-other-window "*Org Note*")
12595 (if (memq org-log-note-how '(time state))
12596 (let (current-prefix-arg) (org-store-log-note))
12597 (let ((org-inhibit-startup t)) (org-mode))
12598 (insert (format "# Insert note for %s.
12599 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12601 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12602 ((eq org-log-note-purpose 'done) "closed todo item")
12603 ((eq org-log-note-purpose 'state)
12604 (format "state change from \"%s\" to \"%s\""
12605 (or org-log-note-previous-state "")
12606 (or org-log-note-state "")))
12607 ((eq org-log-note-purpose 'reschedule)
12609 ((eq org-log-note-purpose 'delschedule)
12610 "no longer scheduled")
12611 ((eq org-log-note-purpose 'redeadline)
12612 "changing deadline")
12613 ((eq org-log-note-purpose 'deldeadline)
12614 "removing deadline")
12615 ((eq org-log-note-purpose 'refile)
12617 ((eq org-log-note-purpose 'note)
12619 (t (error "This should not happen")))))
12620 (if org-log-note-extra (insert org-log-note-extra))
12621 (org-set-local 'org-finish-function 'org-store-log-note)
12622 (run-hooks 'org-log-buffer-setup-hook)))
12624 (defvar org-note-abort nil) ; dynamically scoped
12625 (defun org-store-log-note ()
12626 "Finish taking a log note, and insert it to where it belongs."
12627 (let ((txt (buffer-string))
12628 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12630 (kill-buffer (current-buffer))
12631 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12632 (setq txt (replace-match "" t t txt)))
12633 (if (string-match "\\s-+\\'" txt)
12634 (setq txt (replace-match "" t t txt)))
12635 (setq lines (org-split-string txt "\n"))
12636 (when (and note (string-match "\\S-" note))
12638 (org-replace-escapes
12640 (list (cons "%u" (user-login-name))
12641 (cons "%U" user-full-name)
12642 (cons "%t" (format-time-string
12643 (org-time-stamp-format 'long 'inactive)
12644 org-log-note-effective-time))
12645 (cons "%T" (format-time-string
12646 (org-time-stamp-format 'long nil)
12647 org-log-note-effective-time))
12648 (cons "%d" (format-time-string
12649 (org-time-stamp-format nil 'inactive)
12650 org-log-note-effective-time))
12651 (cons "%D" (format-time-string
12652 (org-time-stamp-format nil nil)
12653 org-log-note-effective-time))
12654 (cons "%s" (if org-log-note-state
12655 (concat "\"" org-log-note-state "\"")
12657 (cons "%S" (if org-log-note-previous-state
12658 (concat "\"" org-log-note-previous-state "\"")
12660 (if lines (setq note (concat note " \\\\")))
12662 (when (or current-prefix-arg org-note-abort)
12663 (when org-log-into-drawer
12664 (org-remove-empty-drawer-at
12665 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12666 org-log-note-marker))
12669 (with-current-buffer (marker-buffer org-log-note-marker)
12671 (goto-char org-log-note-marker)
12672 (move-marker org-log-note-marker nil)
12674 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12675 (setq ind (save-excursion
12676 (if (ignore-errors (goto-char (org-in-item-p)))
12677 (let ((struct (org-list-struct)))
12679 (org-list-get-top-point struct) struct))
12680 (skip-chars-backward " \r\t\n")
12682 ((and (org-at-heading-p)
12683 org-adapt-indentation)
12684 (1+ (org-current-level)))
12685 ((org-at-heading-p) 0)
12686 (t (org-get-indentation))))))
12687 (setq bul (org-list-bullet-string "-"))
12688 (org-indent-line-to ind)
12689 (insert bul (pop lines))
12690 (let ((ind-body (+ (length bul) ind)))
12693 (org-indent-line-to ind-body)
12694 (insert (pop lines))))
12695 (message "Note stored")
12696 (org-back-to-heading t)
12697 (org-cycle-hide-drawers 'children)))))
12698 (set-window-configuration org-log-note-window-configuration)
12699 (with-current-buffer (marker-buffer org-log-note-return-to)
12700 (goto-char org-log-note-return-to))
12701 (move-marker org-log-note-return-to nil)
12702 (and org-log-post-message (message "%s" org-log-post-message)))
12704 (defun org-remove-empty-drawer-at (drawer pos)
12705 "Remove an empty drawer DRAWER at position POS.
12706 POS may also be a marker."
12707 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12713 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12714 (replace-match ""))))))
12716 (defvar org-ts-type nil)
12717 (defun org-sparse-tree (&optional arg type)
12718 "Create a sparse tree, prompt for the details.
12719 This command can create sparse trees. You first need to select the type
12720 of match used to create the tree:
12722 t Show all TODO entries.
12723 T Show entries with a specific TODO keyword.
12724 m Show entries selected by a tags/property match.
12725 p Enter a property name and its value (both with completion on existing
12726 names/values) and show entries with that property.
12727 r Show entries matching a regular expression (`/' can be used as well).
12728 b Show deadlines and scheduled items before a date.
12729 a Show deadlines and scheduled items after a date.
12730 d Show deadlines due within `org-deadline-warning-days'.
12731 D Show deadlines and scheduled items between a date range."
12733 (let (ans kwd value ts-type)
12734 (setq type (or type org-sparse-tree-default-date-type))
12735 (setq org-ts-type type)
12736 (message "Sparse tree: [r]egexp [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty\n [d]eadlines [b]efore-date [a]fter-date [D]ates range\n [c]ycle through date types: %s"
12737 (cond ((eq type 'all) "all timestamps")
12738 ((eq type 'scheduled) "only scheduled")
12739 ((eq type 'deadline) "only deadline")
12740 ((eq type 'active) "only active timestamps")
12741 ((eq type 'inactive) "only inactive timestamps")
12742 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12743 (t "scheduled/deadline")))
12744 (setq ans (read-char-exclusive))
12747 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12749 (call-interactively 'org-check-deadlines))
12751 (call-interactively 'org-check-before-date))
12753 (call-interactively 'org-check-after-date))
12755 (call-interactively 'org-check-dates-range))
12757 (org-show-todo-tree nil))
12759 (org-show-todo-tree '(4)))
12760 ((member ans '(?T ?m))
12761 (call-interactively 'org-match-sparse-tree))
12762 ((member ans '(?p ?P))
12763 (setq kwd (org-icompleting-read "Property: "
12764 (mapcar 'list (org-buffer-property-keys))))
12765 (setq value (org-icompleting-read "Value: "
12766 (mapcar 'list (org-property-values kwd))))
12767 (unless (string-match "\\`{.*}\\'" value)
12768 (setq value (concat "\"" value "\"")))
12769 (org-match-sparse-tree arg (concat kwd "=" value)))
12770 ((member ans '(?r ?R ?/))
12771 (call-interactively 'org-occur))
12772 (t (error "No such sparse tree command \"%c\"" ans)))))
12774 (defvar org-occur-highlights nil
12775 "List of overlays used for occur matches.")
12776 (make-variable-buffer-local 'org-occur-highlights)
12777 (defvar org-occur-parameters nil
12778 "Parameters of the active org-occur calls.
12779 This is a list, each call to org-occur pushes as cons cell,
12780 containing the regular expression and the callback, onto the list.
12781 The list can contain several entries if `org-occur' has been called
12782 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12783 will only contain one set of parameters. When the highlights are
12784 removed (for example with `C-c C-c', or with the next edit (depending
12785 on `org-remove-highlights-with-change'), this variable is emptied
12787 (make-variable-buffer-local 'org-occur-parameters)
12789 (defun org-occur (regexp &optional keep-previous callback)
12790 "Make a compact tree which shows all matches of REGEXP.
12791 The tree will show the lines where the regexp matches, and all higher
12792 headlines above the match. It will also show the heading after the match,
12793 to make sure editing the matching entry is easy.
12794 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12795 call to `org-occur' will be kept, to allow stacking of calls to this
12797 If CALLBACK is non-nil, it is a function which is called to confirm
12798 that the match should indeed be shown."
12799 (interactive "sRegexp: \nP")
12800 (when (equal regexp "")
12801 (error "Regexp cannot be empty"))
12802 (unless keep-previous
12803 (org-remove-occur-highlights nil nil t))
12804 (push (cons regexp callback) org-occur-parameters)
12807 (goto-char (point-min))
12808 (if (or (not keep-previous) ; do not want to keep
12809 (not org-occur-highlights)) ; no previous matches
12812 (while (re-search-forward regexp nil t)
12813 (when (or (not callback)
12814 (save-match-data (funcall callback)))
12815 (setq cnt (1+ cnt))
12816 (when org-highlight-sparse-tree-matches
12817 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12818 (org-show-context 'occur-tree))))
12819 (when org-remove-highlights-with-change
12820 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12822 (unless org-sparse-tree-open-archived-trees
12823 (org-hide-archived-subtrees (point-min) (point-max)))
12824 (run-hooks 'org-occur-hook)
12825 (if (org-called-interactively-p 'interactive)
12826 (message "%d match(es) for regexp %s" cnt regexp))
12829 (defun org-occur-next-match (&optional n reset)
12830 "Function for `next-error-function' to find sparse tree matches.
12831 N is the number of matches to move, when negative move backwards.
12832 RESET is entirely ignored - this function always goes back to the
12833 starting point when no match is found."
12834 (let* ((limit (if (< n 0) (point-min) (point-max)))
12835 (search-func (if (< n 0)
12836 'previous-single-char-property-change
12837 'next-single-char-property-change))
12842 (while (setq p1 (funcall search-func (point) 'org-type))
12843 (when (equal p1 limit)
12845 (error "No more matches"))
12846 (when (equal (get-char-property p1 'org-type) 'org-occur)
12850 (throw 'exit (point))))
12853 (error "No more matches"))))
12855 (defun org-show-context (&optional key)
12856 "Make sure point and context are visible.
12857 How much context is shown depends upon the variables
12858 `org-show-hierarchy-above', `org-show-following-heading',
12859 `org-show-entry-below' and `org-show-siblings'."
12860 (let ((heading-p (org-at-heading-p t))
12861 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12862 (following-p (org-get-alist-option org-show-following-heading key))
12863 (entry-p (org-get-alist-option org-show-entry-below key))
12864 (siblings-p (org-get-alist-option org-show-siblings key)))
12866 ;; Show heading or entry text
12867 (if (and heading-p (not entry-p))
12868 (org-flag-heading nil) ; only show the heading
12869 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12870 (org-show-hidden-entry))) ; show entire entry
12872 ;; Show next sibling, or heading below text
12874 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12875 (org-flag-heading nil))))
12876 (when siblings-p (org-show-siblings))
12878 ;; show all higher headings, possibly with siblings
12880 (while (and (condition-case nil
12881 (progn (org-up-heading-all 1) t)
12884 (org-flag-heading nil)
12885 (when siblings-p (org-show-siblings))))))))
12887 (defvar org-reveal-start-hook nil
12888 "Hook run before revealing a location.")
12890 (defun org-reveal (&optional siblings)
12891 "Show current entry, hierarchy above it, and the following headline.
12892 This can be used to show a consistent set of context around locations
12893 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12894 not t for the search context.
12896 With optional argument SIBLINGS, on each level of the hierarchy all
12897 siblings are shown. This repairs the tree structure to what it would
12898 look like when opened with hierarchical calls to `org-cycle'.
12899 With double optional argument \\[universal-argument] \\[universal-argument], \
12900 go to the parent and show the
12903 (run-hooks 'org-reveal-start-hook)
12904 (let ((org-show-hierarchy-above t)
12905 (org-show-following-heading t)
12906 (org-show-siblings (if siblings t org-show-siblings)))
12907 (org-show-context nil))
12908 (when (equal siblings '(16))
12910 (when (org-up-heading-safe)
12912 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12914 (defun org-highlight-new-match (beg end)
12915 "Highlight from BEG to END and mark the highlight is an occur headline."
12916 (let ((ov (make-overlay beg end)))
12917 (overlay-put ov 'face 'secondary-selection)
12918 (overlay-put ov 'org-type 'org-occur)
12919 (push ov org-occur-highlights)))
12921 (defun org-remove-occur-highlights (&optional beg end noremove)
12922 "Remove the occur highlights from the buffer.
12923 BEG and END are ignored. If NOREMOVE is nil, remove this function
12924 from the `before-change-functions' in the current buffer."
12926 (unless org-inhibit-highlight-removal
12927 (mapc 'delete-overlay org-occur-highlights)
12928 (setq org-occur-highlights nil)
12929 (setq org-occur-parameters nil)
12931 (remove-hook 'before-change-functions
12932 'org-remove-occur-highlights 'local))))
12936 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12937 "Regular expression matching the priority indicator.")
12939 (defvar org-remove-priority-next-time nil)
12941 (defun org-priority-up ()
12942 "Increase the priority of the current item."
12944 (org-priority 'up))
12946 (defun org-priority-down ()
12947 "Decrease the priority of the current item."
12949 (org-priority 'down))
12951 (defun org-priority (&optional action show)
12952 "Change the priority of an item.
12953 ACTION can be `set', `up', `down', or a character."
12955 (if (equal action '(4))
12956 (org-show-priority)
12957 (unless org-enable-priority-commands
12958 (error "Priority commands are disabled"))
12959 (setq action (or action 'set))
12960 (let (current new news have remove)
12962 (org-back-to-heading t)
12963 (if (looking-at org-priority-regexp)
12964 (setq current (string-to-char (match-string 2))
12967 ((eq action 'remove)
12968 (setq remove t new ?\ ))
12969 ((or (eq action 'set)
12970 (if (featurep 'xemacs) (characterp action) (integerp action)))
12971 (if (not (eq action 'set))
12973 (message "Priority %c-%c, SPC to remove: "
12974 org-highest-priority org-lowest-priority)
12976 (setq new (read-char-exclusive))))
12977 (if (and (= (upcase org-highest-priority) org-highest-priority)
12978 (= (upcase org-lowest-priority) org-lowest-priority))
12979 (setq new (upcase new)))
12980 (cond ((equal new ?\ ) (setq remove t))
12981 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12982 (error "Priority must be between `%c' and `%c'"
12983 org-highest-priority org-lowest-priority))))
12986 (1- current) ; normal cycling
12987 ;; last priority was empty
12988 (if (eq last-command this-command)
12989 org-lowest-priority ; wrap around empty to lowest
12991 (if org-priority-start-cycle-with-default
12992 org-default-priority
12993 (1- org-default-priority))))))
12996 (1+ current) ; normal cycling
12997 ;; last priority was empty
12998 (if (eq last-command this-command)
12999 org-highest-priority ; wrap around empty to highest
13001 (if org-priority-start-cycle-with-default
13002 org-default-priority
13003 (1+ org-default-priority))))))
13004 (t (error "Invalid action")))
13005 (if (or (< (upcase new) org-highest-priority)
13006 (> (upcase new) org-lowest-priority))
13007 (if (and (memq action '(up down))
13008 (not have) (not (eq last-command this-command)))
13009 ;; `new' is from default priority
13011 "The default can not be set, see `org-default-priority' why")
13012 ;; normal cycling: `new' is beyond highest/lowest priority
13013 ;; and is wrapped around to the empty priority
13015 (setq news (format "%c" new))
13018 (replace-match "" t t nil 1)
13019 (replace-match news t t nil 2))
13021 (error "No priority cookie found in line")
13022 (let ((case-fold-search nil))
13023 (looking-at org-todo-line-regexp))
13026 (goto-char (match-end 2))
13027 (insert " [#" news "]"))
13028 (goto-char (match-beginning 3))
13029 (insert "[#" news "] "))))
13030 (org-preserve-lc (org-set-tags nil 'align)))
13032 (message "Priority removed")
13033 (message "Priority of current item set to %s" news)))))
13035 (defun org-show-priority ()
13036 "Show the priority of the current item.
13037 This priority is composed of the main priority given with the [#A] cookies,
13038 and by additional input from the age of a schedules or deadline entry."
13040 (let ((pri (if (eq major-mode 'org-agenda-mode)
13041 (org-get-at-bol 'priority)
13044 (beginning-of-line)
13045 (and (looking-at org-heading-regexp)
13046 (org-get-priority (match-string 0))))))))
13047 (message "Priority is %d" (if pri pri -1000))))
13049 (defun org-get-priority (s)
13050 "Find priority cookie and return priority."
13051 (if (functionp org-get-priority-function)
13052 (funcall org-get-priority-function)
13054 (if (not (string-match org-priority-regexp s))
13055 (* 1000 (- org-lowest-priority org-default-priority))
13056 (* 1000 (- org-lowest-priority
13057 (string-to-char (match-string 2 s))))))))
13061 (defvar org-agenda-archives-mode)
13062 (defvar org-map-continue-from nil
13063 "Position from where mapping should continue.
13064 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13066 (defvar org-scanner-tags nil
13067 "The current tag list while the tags scanner is running.")
13068 (defvar org-trust-scanner-tags nil
13069 "Should `org-get-tags-at' use the tags for the scanner.
13070 This is for internal dynamical scoping only.
13071 When this is non-nil, the function `org-get-tags-at' will return the value
13072 of `org-scanner-tags' instead of building the list by itself. This
13073 can lead to large speed-ups when the tags scanner is used in a file with
13074 many entries, and when the list of tags is retrieved, for example to
13075 obtain a list of properties. Building the tags list for each entry in such
13076 a file becomes an N^2 operation - but with this variable set, it scales
13079 (defun org-scan-tags (action matcher todo-only &optional start-level)
13080 "Scan headline tags with inheritance and produce output ACTION.
13082 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13083 or `agenda' to produce an entry list for an agenda view. It can also be
13084 a Lisp form or a function that should be called at each matched headline, in
13085 this case the return value is a list of all return values from these calls.
13087 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13088 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13089 only lines with a not-done TODO keyword are included in the output.
13090 This should be the same variable that was scoped into
13091 and set by `org-make-tags-matcher' when it constructed MATCHER.
13093 START-LEVEL can be a string with asterisks, reducing the scope to
13094 headlines matching this string."
13095 (require 'org-agenda)
13096 (let* ((re (concat "^"
13098 ;; Get the correct level to match
13099 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13100 org-outline-regexp)
13102 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13103 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13104 (props (list 'face 'default
13105 'done-face 'org-agenda-done
13106 'undone-face 'default
13107 'mouse-face 'highlight
13108 'org-not-done-regexp org-not-done-regexp
13109 'org-todo-regexp org-todo-regexp
13110 'org-complex-heading-regexp org-complex-heading-regexp
13112 (format "mouse-2 or RET jump to org file %s"
13113 (abbreviate-file-name
13114 (or (buffer-file-name (buffer-base-buffer))
13115 (buffer-name (buffer-base-buffer)))))))
13116 (case-fold-search nil)
13117 (org-map-continue-from nil)
13118 lspos tags tags-list
13119 (tags-alist (list (cons 0 org-file-tags)))
13120 (llast 0) rtn rtn1 level category i txt
13121 todo marker entry priority)
13122 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13123 (setq action (list 'lambda nil action)))
13125 (goto-char (point-min))
13126 (when (eq action 'sparse-tree)
13128 (org-remove-occur-highlights))
13129 (while (re-search-forward re nil t)
13130 (setq org-map-continue-from nil)
13132 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13133 tags (if (match-end 4) (org-match-string-no-properties 4)))
13134 (goto-char (setq lspos (match-beginning 0)))
13135 (setq level (org-reduced-level (org-outline-level))
13136 category (org-get-category))
13137 (setq i llast llast level)
13138 ;; remove tag lists from same and sublevels
13139 (while (>= i level)
13140 (when (setq entry (assoc i tags-alist))
13141 (setq tags-alist (delete entry tags-alist)))
13143 ;; add the next tags
13145 (setq tags (org-split-string tags ":")
13147 (cons (cons level tags) tags-alist)))
13148 ;; compile tags for current headline
13150 (if org-use-tag-inheritance
13151 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13153 org-scanner-tags tags-list)
13154 (when org-use-tag-inheritance
13155 (setcdr (car tags-alist)
13156 (mapcar (lambda (x)
13157 (setq x (copy-sequence x))
13158 (org-add-prop-inherited x))
13159 (cdar tags-alist))))
13160 (when (and tags org-use-tag-inheritance
13161 (or (not (eq t org-use-tag-inheritance))
13162 org-tags-exclude-from-inheritance))
13163 ;; selective inheritance, remove uninherited ones
13164 (setcdr (car tags-alist)
13165 (org-remove-uninherited-tags (cdar tags-alist))))
13168 ;; eval matcher only when the todo condition is OK
13169 (and (or (not todo-only) (member todo org-not-done-keywords))
13170 (let ((case-fold-search t) (org-trust-scanner-tags t))
13173 ;; Call the skipper, but return t if it does not skip,
13174 ;; so that the `and' form continues evaluating
13176 (unless (eq action 'sparse-tree) (org-agenda-skip))
13179 ;; Check if timestamps are deselecting this entry
13180 (or (not todo-only)
13181 (and (member todo org-not-done-keywords)
13182 (or (not org-agenda-tags-todo-honor-ignore-options)
13183 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13185 ;; Extra check for the archive tag
13186 ;; FIXME: Does the skipper already do this????
13188 (not (member org-archive-tag tags-list))
13189 ;; we have an archive tag, should we use this anyway?
13190 (or (not org-agenda-skip-archived-trees)
13191 (and (eq action 'agenda) org-agenda-archives-mode))))
13193 ;; select this headline
13195 ((eq action 'sparse-tree)
13196 (and org-highlight-sparse-tree-matches
13197 (org-get-heading) (match-end 0)
13198 (org-highlight-new-match
13199 (match-beginning 1) (match-end 1)))
13200 (org-show-context 'tags-tree))
13201 ((eq action 'agenda)
13202 (setq txt (org-agenda-format-item
13205 (if (eq org-tags-match-list-sublevels 'indented)
13206 (make-string (1- level) ?.) "")
13210 priority (org-get-priority txt))
13212 (setq marker (org-agenda-new-marker))
13213 (org-add-props txt props
13214 'org-marker marker 'org-hd-marker marker 'org-category category
13216 'priority priority 'type "tagsmatch")
13218 ((functionp action)
13219 (setq org-map-continue-from nil)
13221 (setq rtn1 (funcall action))
13223 (t (error "Invalid action")))
13225 ;; if we are to skip sublevels, jump to end of subtree
13226 (unless org-tags-match-list-sublevels
13227 (org-end-of-subtree t)
13228 (backward-char 1))))
13229 ;; Get the correct position from where to continue
13230 (if org-map-continue-from
13231 (goto-char org-map-continue-from)
13232 (and (= (point) lspos) (end-of-line 1)))))
13233 (when (and (eq action 'sparse-tree)
13234 (not org-sparse-tree-open-archived-trees))
13235 (org-hide-archived-subtrees (point-min) (point-max)))
13238 (defun org-remove-uninherited-tags (tags)
13239 "Remove all tags that are not inherited from the list TAGS."
13241 ((eq org-use-tag-inheritance t)
13242 (if org-tags-exclude-from-inheritance
13243 (org-delete-all org-tags-exclude-from-inheritance tags)
13245 ((not org-use-tag-inheritance) nil)
13246 ((stringp org-use-tag-inheritance)
13249 (if (and (string-match org-use-tag-inheritance x)
13250 (not (member x org-tags-exclude-from-inheritance)))
13253 ((listp org-use-tag-inheritance)
13256 (if (member x org-use-tag-inheritance) x nil))
13259 (defun org-match-sparse-tree (&optional todo-only match)
13260 "Create a sparse tree according to tags string MATCH.
13261 MATCH can contain positive and negative selection of tags, like
13262 \"+WORK+URGENT-WITHBOSS\".
13263 If optional argument TODO-ONLY is non-nil, only select lines that are
13266 (org-agenda-prepare-buffers (list (current-buffer)))
13267 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13269 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13271 (defvar org-cached-props nil)
13272 (defun org-cached-entry-get (pom property)
13273 (if (or (eq t org-use-property-inheritance)
13274 (and (stringp org-use-property-inheritance)
13275 (string-match org-use-property-inheritance property))
13276 (and (listp org-use-property-inheritance)
13277 (member property org-use-property-inheritance)))
13278 ;; Caching is not possible, check it directly
13279 (org-entry-get pom property 'inherit)
13280 ;; Get all properties, so that we can do complicated checks easily
13281 (cdr (assoc property (or org-cached-props
13282 (setq org-cached-props
13283 (org-entry-properties pom)))))))
13285 (defun org-global-tags-completion-table (&optional files)
13286 "Return the list of all tags in all agenda buffer/files.
13287 Optional FILES argument is a list of files which can be used
13288 instead of the agenda files."
13295 (set-buffer (find-file-noselect file))
13296 (append (org-get-buffer-tags)
13297 (mapcar (lambda (x) (if (stringp (car-safe x))
13298 (list (car-safe x)) nil))
13300 (if (and files (car files))
13302 (org-agenda-files))))))))
13304 (defun org-make-tags-matcher (match)
13305 "Create the TAGS/TODO matcher form for the selection string MATCH.
13307 The variable `todo-only' is scoped dynamically into this function.
13308 It will be set to t if the matcher restricts matching to TODO entries,
13309 otherwise will not be touched.
13311 Returns a cons of the selection string MATCH and the constructed
13312 lisp form implementing the matcher. The matcher is to be evaluated
13313 at an Org entry, with point on the headline, and returns t if the
13314 entry matches the selection string MATCH. The returned lisp form
13315 references two variables with information about the entry, which
13316 must be bound around the form's evaluation: todo, the TODO keyword
13317 at the entry (or nil of none); and tags-list, the list of all tags
13318 at the entry including inherited ones. Additionally, the category
13319 of the entry (if any) must be specified as the text property
13320 'org-category on the headline.
13322 See also `org-scan-tags'.
13324 (declare (special todo-only))
13325 (unless (boundp 'todo-only)
13326 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13328 ;; Get a new match request, with completion
13329 (let ((org-last-tags-completion-table
13330 (org-global-tags-completion-table)))
13331 (setq match (org-completing-read-no-i
13332 "Match: " 'org-tags-completion-function nil nil nil
13333 'org-tags-history))))
13335 ;; Parse the string and create a lisp form
13336 (let ((match0 match)
13337 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13339 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13340 orterms term orlist re-p str-p level-p level-op time-p
13341 prop-p pn pv po gv rest)
13342 (if (string-match "/+" match)
13343 ;; match contains also a todo-matching request
13345 (setq tagsmatch (substring match 0 (match-beginning 0))
13346 todomatch (substring match (match-end 0)))
13347 (if (string-match "^!" todomatch)
13348 (setq todo-only t todomatch (substring todomatch 1)))
13349 (if (string-match "^\\s-*$" todomatch)
13350 (setq todomatch nil)))
13351 ;; only matching tags
13352 (setq tagsmatch match todomatch nil))
13354 ;; Make the tags matcher
13355 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13356 (setq tagsmatcher t)
13357 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13358 (while (setq term (pop orterms))
13359 (while (and (equal (substring term -1) "\\") orterms)
13360 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13361 (while (string-match re term)
13362 (setq rest (substring term (match-end 0))
13363 minus (and (match-end 1)
13364 (equal (match-string 1 term) "-"))
13365 tag (save-match-data (replace-regexp-in-string
13367 (match-string 2 term)))
13368 re-p (equal (string-to-char tag) ?{)
13369 level-p (match-end 4)
13370 prop-p (match-end 5)
13372 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13374 (setq level-op (org-op-to-function (match-string 3 term)))
13375 `(,level-op level ,(string-to-number
13376 (match-string 4 term))))
13378 (setq pn (match-string 5 term)
13379 po (match-string 6 term)
13380 pv (match-string 7 term)
13381 re-p (equal (string-to-char pv) ?{)
13382 str-p (equal (string-to-char pv) ?\")
13383 time-p (save-match-data
13384 (string-match "^\"[[<].*[]>]\"$" pv))
13385 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13386 (if time-p (setq pv (org-matcher-time pv)))
13387 (setq po (org-op-to-function po (if time-p 'time str-p)))
13389 ((equal pn "CATEGORY")
13390 (setq gv '(get-text-property (point) 'org-category)))
13394 (setq gv `(org-cached-entry-get nil ,pn))))
13397 `(not (string-match ,pv (or ,gv "")))
13398 `(string-match ,pv (or ,gv "")))
13400 `(,po (or ,gv "") ,pv)
13401 `(,po (string-to-number (or ,gv ""))
13402 ,(string-to-number pv) ))))
13403 (t `(member ,tag tags-list)))
13404 mm (if minus (list 'not mm) mm)
13406 (push mm tagsmatcher))
13407 (push (if (> (length tagsmatcher) 1)
13408 (cons 'and tagsmatcher)
13411 (setq tagsmatcher nil))
13412 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13414 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13415 ;; Make the todo matcher
13416 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13417 (setq todomatcher t)
13418 (setq orterms (org-split-string todomatch "|") orlist nil)
13419 (while (setq term (pop orterms))
13420 (while (string-match re term)
13421 (setq minus (and (match-end 1)
13422 (equal (match-string 1 term) "-"))
13423 kwd (match-string 2 term)
13424 re-p (equal (string-to-char kwd) ?{)
13425 term (substring term (match-end 0))
13427 `(string-match ,(substring kwd 1 -1) todo)
13428 (list 'equal 'todo kwd))
13429 mm (if minus (list 'not mm) mm))
13430 (push mm todomatcher))
13431 (push (if (> (length todomatcher) 1)
13432 (cons 'and todomatcher)
13435 (setq todomatcher nil))
13436 (setq todomatcher (if (> (length orlist) 1)
13437 (cons 'or orlist) (car orlist))))
13439 ;; Return the string and lisp forms of the matcher
13440 (setq matcher (if todomatcher
13441 (list 'and tagsmatcher todomatcher)
13444 (setq matcher (list 'and '(member todo org-not-done-keywords)
13446 (cons match0 matcher)))
13448 (defun org-op-to-function (op &optional stringp)
13449 "Turn an operator into the appropriate function."
13452 ((equal op "<" ) '(< string< org-time<))
13453 ((equal op ">" ) '(> org-string> org-time>))
13454 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13455 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13456 ((member op '("=" "==")) '(= string= org-time=))
13457 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13458 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13460 (defun org<> (a b) (not (= a b)))
13461 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13462 (defun org-string>= (a b) (not (string< a b)))
13463 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13464 (defun org-string<> (a b) (not (string= a b)))
13465 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13466 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13467 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13468 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13469 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13470 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13472 "Convert S to a floating point time.
13473 If S is already a number, just return it. If it is a string, parse
13474 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13478 (condition-case nil
13479 (float-time (apply 'encode-time (org-parse-time-string s)))
13483 (defun org-time-today ()
13484 "Time in seconds today at 0:00.
13485 Returns the float number of seconds since the beginning of the
13486 epoch to the beginning of today (00:00)."
13487 (float-time (apply 'encode-time
13488 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13490 (defun org-matcher-time (s)
13491 "Interpret a time comparison value."
13494 ((string= s "<now>") (float-time))
13495 ((string= s "<today>") (org-time-today))
13496 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13497 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13498 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13499 (+ (org-time-today)
13500 (* (string-to-number (match-string 1 s))
13501 (cdr (assoc (match-string 2 s)
13502 '(("d" . 86400.0) ("w" . 604800.0)
13503 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13506 (defun org-match-any-p (re list)
13507 "Does re match any element of list?"
13508 (setq list (mapcar (lambda (x) (string-match re x)) list))
13511 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13512 (defvar org-tags-overlay (make-overlay 1 1))
13513 (org-detach-overlay org-tags-overlay)
13515 (defun org-get-local-tags-at (&optional pos)
13516 "Get a list of tags defined in the current headline."
13517 (org-get-tags-at pos 'local))
13519 (defun org-get-local-tags ()
13520 "Get a list of tags defined in the current headline."
13521 (org-get-tags-at nil 'local))
13523 (defun org-get-tags-at (&optional pos local)
13524 "Get a list of all headline tags applicable at POS.
13525 POS defaults to point. If tags are inherited, the list contains
13526 the targets in the same sequence as the headlines appear, i.e.
13527 the tags of the current headline come last.
13528 When LOCAL is non-nil, only return tags from the current headline,
13529 ignore inherited ones."
13531 (if (and org-trust-scanner-tags
13532 (or (not pos) (equal pos (point)))
13535 (let (tags ltags lastpos parent)
13539 (goto-char (or pos (point)))
13542 (condition-case nil
13544 (org-back-to-heading t)
13545 (while (not (equal lastpos (point)))
13546 (setq lastpos (point))
13548 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13549 (setq ltags (org-split-string
13550 (org-match-string-no-properties 1) ":"))
13552 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13555 (org-remove-uninherited-tags ltags)
13558 (or org-use-tag-inheritance (throw 'done t))
13559 (if local (throw 'done t))
13560 (or (org-up-heading-safe) (error nil))
13565 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13567 (defun org-add-prop-inherited (s)
13568 (add-text-properties 0 (length s) '(inherited t) s)
13571 (defun org-toggle-tag (tag &optional onoff)
13572 "Toggle the tag TAG for the current line.
13573 If ONOFF is `on' or `off', don't toggle but set to this state."
13576 (org-back-to-heading t)
13577 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13580 (setq current (match-string 1))
13581 (replace-match ""))
13583 (setq current (nreverse (org-split-string current ":")))
13587 (or (member tag current) (push tag current)))
13589 (or (not (member tag current)) (setq current (delete tag current))))
13590 (t (if (member tag current)
13591 (setq current (delete tag current))
13593 (push tag current))))
13597 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13598 (org-set-tags nil t))
13599 (delete-horizontal-space))
13600 (run-hooks 'org-after-tags-change-hook))
13603 (defun org-align-tags-here (to-col)
13604 ;; Assumes that this is a headline
13605 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13606 (beginning-of-line 1)
13607 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13608 (< pos (match-beginning 2)))
13610 (setq tags-l (- (match-end 2) (match-beginning 2)))
13611 (goto-char (match-beginning 1))
13613 (delete-region (point) (1+ (match-beginning 2)))
13614 (setq ncol (max (current-column)
13618 (- (abs to-col) tags-l))))
13620 (insert (make-string (- ncol (current-column)) ?\ ))
13621 (setq ncol (current-column))
13622 (when indent-tabs-mode (tabify p (point-at-eol)))
13623 (org-move-to-column (min ncol col) t))
13626 (defun org-set-tags-command (&optional arg just-align)
13627 "Call the set-tags command for the current entry."
13629 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13630 (org-set-tags arg just-align)
13632 (org-back-to-heading t)
13633 (org-set-tags arg just-align))))
13635 (defun org-set-tags-to (data)
13636 "Set the tags of the current entry to DATA, replacing the current tags.
13637 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13638 If DATA is nil or the empty string, any tags will be removed."
13639 (interactive "sTags: ")
13643 ((equal data "") "")
13645 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13648 (concat ":" (mapconcat 'identity data ":") ":"))))
13651 (org-back-to-heading t)
13652 (when (looking-at org-complex-heading-regexp)
13655 (goto-char (match-beginning 5))
13657 (delete-region (point) (point-at-eol))
13658 (org-set-tags nil 'align))
13659 (goto-char (point-at-eol))
13661 (org-set-tags nil 'align)))
13662 (beginning-of-line 1)
13663 (if (looking-at ".*?\\([ \t]+\\)$")
13664 (delete-region (match-beginning 1) (match-end 1))))))
13666 (defun org-align-all-tags ()
13667 "Align the tags i all headings."
13670 (or (ignore-errors (org-back-to-heading t))
13671 (outline-next-heading))
13672 (if (org-at-heading-p)
13674 (message "No headings"))))
13676 (defvar org-indent-indentation-per-level)
13677 (defun org-set-tags (&optional arg just-align)
13678 "Set the tags for the current headline.
13679 With prefix ARG, realign all tags in headings in the current buffer."
13681 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13682 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13683 'region-start-level 'region))
13684 org-loop-over-headlines-in-active-region)
13686 ;; We don't use ARG and JUST-ALIGN here these args are not
13687 ;; useful when looping over headlines
13689 org-loop-over-headlines-in-active-region
13690 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13691 (let* ((re org-outline-regexp-bol)
13692 (current (unless arg (org-get-tags-string)))
13693 (col (current-column))
13694 (org-setting-tags t)
13695 table current-tags inherited-tags ; computed below when needed
13696 tags p0 c0 c1 rpl di tc level)
13699 (goto-char (point-min))
13700 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13701 (while (re-search-forward re nil t)
13702 (org-set-tags nil t)
13704 (message "All tags realigned to column %d" org-tags-column))
13706 (setq tags current)
13707 ;; Get a new set of tags from the user
13709 (setq table (append org-tag-persistent-alist
13710 (or org-tag-alist (org-get-buffer-tags))
13712 org-complete-tags-always-offer-all-agenda-tags
13713 (org-global-tags-completion-table
13714 (org-agenda-files))))
13715 org-last-tags-completion-table table
13716 current-tags (org-split-string current ":")
13717 inherited-tags (nreverse
13718 (nthcdr (length current-tags)
13719 (nreverse (org-get-tags-at))))
13721 (if (or (eq t org-use-fast-tag-selection)
13722 (and org-use-fast-tag-selection
13723 (delq nil (mapcar 'cdr table))))
13724 (org-fast-tag-selection
13725 current-tags inherited-tags table
13726 (if org-fast-tag-selection-include-todo
13727 org-todo-key-alist))
13728 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13730 (org-icompleting-read "Tags: "
13731 'org-tags-completion-function
13732 nil nil current 'org-tags-history))))))
13733 (while (string-match "[-+&]+" tags)
13734 ;; No boolean logic, just a list
13735 (setq tags (replace-match ":" t t tags))))
13737 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13739 (if org-tags-sort-function
13740 (setq tags (mapconcat 'identity
13741 (sort (org-split-string
13742 tags (org-re "[^[:alnum:]_@#%]+"))
13743 org-tags-sort-function) ":")))
13745 (if (string-match "\\`[\t ]*\\'" tags)
13747 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13748 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13750 ;; Insert new tags at the correct column
13751 (beginning-of-line 1)
13752 (setq level (or (and (looking-at org-outline-regexp)
13753 (- (match-end 0) (point) 1))
13756 ((and (equal current "") (equal tags "")))
13757 ((re-search-forward
13758 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13760 (if (equal tags "")
13762 (goto-char (match-beginning 0))
13763 (setq c0 (current-column)
13764 ;; compute offset for the case of org-indent-mode active
13765 di (if org-indent-mode
13766 (* (1- org-indent-indentation-per-level) (1- level))
13768 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13769 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13770 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13771 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13772 (replace-match rpl t t)
13773 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13775 (t (error "Tags alignment failed")))
13776 (org-move-to-column col)
13778 (run-hooks 'org-after-tags-change-hook))))))
13780 (defun org-change-tag-in-region (beg end tag off)
13781 "Add or remove TAG for each entry in the region.
13782 This works in the agenda, and also in an org-mode buffer."
13784 (list (region-beginning) (region-end)
13785 (let ((org-last-tags-completion-table
13786 (if (derived-mode-p 'org-mode)
13787 (org-get-buffer-tags)
13788 (org-global-tags-completion-table))))
13789 (org-icompleting-read
13790 "Tag: " 'org-tags-completion-function nil nil nil
13791 'org-tags-history))
13793 (message "[s]et or
[r]emove? ")
13794 (equal (read-char-exclusive) ?r))))
13795 (if (fboundp 'deactivate-mark) (deactivate-mark))
13796 (let ((agendap (equal major-mode 'org-agenda-mode))
13797 l1 l2 m buf pos newhead (cnt 0))
13799 (setq l2 (1- (org-current-line)))
13801 (setq l1 (org-current-line))
13802 (loop for l from l1 to l2 do
13804 (setq m (get-text-property (point) 'org-hd-marker))
13805 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13807 (setq buf (if agendap (marker-buffer m) (current-buffer))
13808 pos (if agendap m (point)))
13809 (with-current-buffer buf
13813 (setq cnt (1+ cnt))
13814 (org-toggle-tag tag (if off 'off 'on))
13815 (setq newhead (org-get-heading)))))
13816 (and agendap (org-agenda-change-all-lines newhead m))))
13817 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13819 (defun org-tags-completion-function (string predicate &optional flag)
13820 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13821 (confirm (lambda (x) (stringp (car x)))))
13822 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13823 (setq s1 (match-string 1 string)
13824 s2 (match-string 2 string))
13825 (setq s1 "" s2 string))
13829 (setq rtn (try-completion s2 ctable confirm))
13832 (concat s1 s2 (substring rtn (length s2))
13833 (if (and org-add-colon-after-tag-completion
13834 (assoc rtn ctable))
13839 (all-completions s2 ctable confirm)
13843 (assoc s2 ctable)))
13846 (defun org-fast-tag-insert (kwd tags face &optional end)
13847 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13848 (insert (format "%-12s" (concat kwd ":"))
13849 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13852 (defun org-fast-tag-show-exit (flag)
13855 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13856 (replace-match ""))
13859 (org-move-to-column (- (window-width) 19) t)
13860 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13862 (defun org-set-current-tags-overlay (current prefix)
13863 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13864 (if (featurep 'xemacs)
13865 (org-overlay-display org-tags-overlay (concat prefix s)
13866 'secondary-selection)
13867 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13868 (org-overlay-display org-tags-overlay (concat prefix s)))))
13870 (defvar org-last-tag-selection-key nil)
13871 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13872 "Fast tag selection with single keys.
13873 CURRENT is the current list of tags in the headline, INHERITED is the
13874 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13875 possibly with grouping information. TODO-TABLE is a similar table with
13876 TODO keywords, should these have keys assigned to them.
13877 If the keys are nil, a-z are automatically assigned.
13878 Returns the new tags string, or nil to not change the current settings."
13879 (let* ((fulltable (append table todo-table))
13880 (maxlen (apply 'max (mapcar
13882 (if (stringp (car x)) (string-width (car x)) 0))
13884 (buf (current-buffer))
13885 (expert (eq org-fast-tag-selection-single-key 'expert))
13887 (fwidth (+ maxlen 3 1 3))
13888 (ncol (/ (- (window-width) 4) fwidth))
13891 tg cnt e c char c1 c2 ntable tbl rtn
13892 ov-start ov-end ov-prefix
13893 (exit-after-next org-fast-tag-selection-single-key)
13894 (done-keywords org-done-keywords)
13897 (beginning-of-line 1)
13899 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13900 (setq ov-start (match-beginning 1)
13901 ov-end (match-end 1)
13903 (setq ov-start (1- (point-at-eol))
13904 ov-end (1+ ov-start))
13905 (skip-chars-forward "^\n\r")
13908 (buffer-substring (1- (point)) (point))
13909 (if (> (current-column) org-tags-column)
13911 (make-string (- org-tags-column (current-column)) ?\ ))))))
13912 (move-overlay org-tags-overlay ov-start ov-end)
13913 (save-window-excursion
13915 (set-buffer (get-buffer-create " *Org tags*"))
13916 (delete-other-windows)
13917 (split-window-vertically)
13918 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13920 (org-set-local 'org-done-keywords done-keywords)
13921 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13922 (org-fast-tag-insert "Current" current c-face "\n\n")
13923 (org-fast-tag-show-exit exit-after-next)
13924 (org-set-current-tags-overlay current ov-prefix)
13925 (setq tbl fulltable char ?a cnt 0)
13926 (while (setq e (pop tbl))
13928 ((equal (car e) :startgroup)
13929 (push '() groups) (setq ingroup t)
13930 (when (not (= cnt 0))
13933 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13934 ((equal (car e) :endgroup)
13935 (setq ingroup nil cnt 0)
13936 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13937 ((equal e '(:newline))
13938 (when (not (= cnt 0))
13942 (while (equal (car tbl) '(:newline))
13944 (setq tbl (cdr tbl)))))
13946 (setq tg (copy-sequence (car e)) c2 nil)
13949 ;; automatically assign a character.
13950 (setq c1 (string-to-char
13951 (downcase (substring
13952 tg (if (= (string-to-char tg) ?@) 1 0)))))
13953 (if (or (rassoc c1 ntable) (rassoc c1 table))
13954 (while (or (rassoc char ntable) (rassoc char table))
13955 (setq char (1+ char)))
13957 (setq c (or c2 char)))
13958 (if ingroup (push tg (car groups)))
13959 (setq tg (org-add-props tg nil 'face
13961 ((not (assoc tg table))
13962 (org-get-todo-face tg))
13963 ((member tg current) c-face)
13964 ((member tg inherited) i-face))))
13965 (if (and (= cnt 0) (not ingroup)) (insert " "))
13966 (insert "[" c "] " tg (make-string
13967 (- fwidth 4 (length tg)) ?\ ))
13968 (push (cons tg c) ntable)
13969 (when (= (setq cnt (1+ cnt)) ncol)
13971 (if ingroup (insert " "))
13973 (setq ntable (nreverse ntable))
13975 (goto-char (point-min))
13976 (if (not expert) (org-fit-window-to-buffer))
13980 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
13981 (if (not groups) "no " "")
13982 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13983 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13984 (setq org-last-tag-selection-key c)
13986 ((= c ?\r) (throw 'exit t))
13988 (setq groups (not groups))
13989 (goto-char (point-min))
13990 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13993 (org-fast-tag-show-exit
13994 (setq exit-after-next (not exit-after-next)))
13996 (delete-other-windows)
13997 (set-window-buffer (split-window-vertically) " *Org tags*")
13998 (org-switch-to-buffer-other-window " *Org tags*")
13999 (org-fit-window-to-buffer)))
14001 (and (= c ?q) (not (rassoc c ntable))))
14002 (org-detach-overlay org-tags-overlay)
14003 (setq quit-flag t))
14006 (if exit-after-next (setq exit-after-next 'now)))
14008 (condition-case nil
14009 (setq tg (org-icompleting-read
14012 (with-current-buffer buf
14013 (org-get-buffer-tags)))))
14014 (quit (setq tg "")))
14015 (when (string-match "\\S-" tg)
14016 (add-to-list 'buffer-tags (list tg))
14017 (if (member tg current)
14018 (setq current (delete tg current))
14019 (push tg current)))
14020 (if exit-after-next (setq exit-after-next 'now)))
14021 ((setq e (rassoc c todo-table) tg (car e))
14022 (with-current-buffer buf
14023 (save-excursion (org-todo tg)))
14024 (if exit-after-next (setq exit-after-next 'now)))
14025 ((setq e (rassoc c ntable) tg (car e))
14026 (if (member tg current)
14027 (setq current (delete tg current))
14028 (loop for g in groups do
14031 (setq current (delete x current)))
14034 (if exit-after-next (setq exit-after-next 'now))))
14036 ;; Create a sorted list
14040 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14041 (if (eq exit-after-next 'now) (throw 'exit t))
14042 (goto-char (point-min))
14043 (beginning-of-line 2)
14044 (delete-region (point) (point-at-eol))
14045 (org-fast-tag-insert "Current" current c-face)
14046 (org-set-current-tags-overlay current ov-prefix)
14047 (while (re-search-forward
14048 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14049 (setq tg (match-string 1))
14050 (add-text-properties
14051 (match-beginning 1) (match-end 1)
14054 ((member tg current) c-face)
14055 ((member tg inherited) i-face)
14056 (t (get-text-property (match-beginning 1) 'face))))))
14057 (goto-char (point-min)))))
14058 (org-detach-overlay org-tags-overlay)
14060 (mapconcat 'identity current ":")
14063 (defun org-get-tags-string ()
14064 "Get the TAGS string in the current headline."
14065 (unless (org-at-heading-p t)
14066 (error "Not on a heading"))
14068 (beginning-of-line 1)
14069 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14070 (org-match-string-no-properties 1)
14073 (defun org-get-tags ()
14074 "Get the list of tags specified in the current headline."
14075 (org-split-string (org-get-tags-string) ":"))
14077 (defun org-get-buffer-tags ()
14078 "Get a table of all tags used in the buffer, for completion."
14081 (goto-char (point-min))
14082 (while (re-search-forward
14083 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14084 (when (equal (char-after (point-at-bol 0)) ?*)
14085 (mapc (lambda (x) (add-to-list 'tags x))
14086 (org-split-string (org-match-string-no-properties 1) ":")))))
14087 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14088 (mapcar 'list tags)))
14090 ;;;; The mapping API
14092 (defun org-map-entries (func &optional match scope &rest skip)
14093 "Call FUNC at each headline selected by MATCH in SCOPE.
14095 FUNC is a function or a lisp form. The function will be called without
14096 arguments, with the cursor positioned at the beginning of the headline.
14097 The return values of all calls to the function will be collected and
14098 returned as a list.
14100 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14101 does not need to preserve point. After evaluation, the cursor will be
14102 moved to the end of the line (presumably of the headline of the
14103 processed entry) and search continues from there. Under some
14104 circumstances, this may not produce the wanted results. For example,
14105 if you have removed (e.g. archived) the current (sub)tree it could
14106 mean that the next entry will be skipped entirely. In such cases, you
14107 can specify the position from where search should continue by making
14108 FUNC set the variable `org-map-continue-from' to the desired buffer
14111 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14112 Only headlines that are matched by this query will be considered during
14113 the iteration. When MATCH is nil or t, all headlines will be
14114 visited by the iteration.
14116 SCOPE determines the scope of this command. It can be any of:
14118 nil The current buffer, respecting the restriction if any
14119 tree The subtree started with the entry at point
14120 region The entries within the active region, if any
14122 The entries within the active region, but only those at
14123 the same level than the first one.
14124 file The current buffer, without restriction
14126 The current buffer, and any archives associated with it
14127 agenda All agenda files
14128 agenda-with-archives
14129 All agenda files with any archive files associated with them
14131 If this is a list, all files in the list will be scanned
14133 The remaining args are treated as settings for the skipping facilities of
14134 the scanner. The following items can be given here:
14136 archive skip trees with the archive tag.
14137 comment skip trees with the COMMENT keyword
14138 function or Emacs Lisp form:
14139 will be used as value for `org-agenda-skip-function', so whenever
14140 the function returns t, FUNC will not be called for that
14141 entry and search will continue from the point where the
14142 function leaves it.
14144 If your function needs to retrieve the tags including inherited tags
14145 at the *current* entry, you can use the value of the variable
14146 `org-scanner-tags' which will be much faster than getting the value
14147 with `org-get-tags-at'. If your function gets properties with
14148 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14149 to t around the call to `org-entry-properties' to get the same speedup.
14150 Note that if your function moves around to retrieve tags and properties at
14151 a *different* entry, you cannot use these techniques."
14152 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14153 (not (org-region-active-p)))
14154 (let* ((org-agenda-archives-mode nil) ; just to make sure
14155 (org-agenda-skip-archived-trees (memq 'archive skip))
14156 (org-agenda-skip-comment-trees (memq 'comment skip))
14157 (org-agenda-skip-function
14158 (car (org-delete-all '(comment archive) skip)))
14159 (org-tags-match-list-sublevels t)
14160 (start-level (eq scope 'region-start-level))
14162 org-todo-keywords-for-agenda
14163 org-done-keywords-for-agenda
14164 org-todo-keyword-alist-for-agenda
14165 org-drawers-for-agenda
14166 org-tag-alist-for-agenda
14170 ((eq match t) (setq matcher t))
14171 ((eq match nil) (setq matcher t))
14172 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14176 (cond ((eq scope 'tree)
14177 (org-back-to-heading t)
14178 (org-narrow-to-subtree)
14180 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14181 (org-region-active-p))
14182 ;; If needed, set start-level to a string like "2"
14185 (goto-char (region-beginning))
14186 (unless (org-at-heading-p) (outline-next-heading))
14187 (setq start-level (org-current-level))))
14188 (narrow-to-region (region-beginning)
14190 (goto-char (region-end))
14191 (unless (and (bolp) (org-at-heading-p))
14192 (outline-next-heading))
14198 (org-agenda-prepare-buffers
14199 (list (buffer-file-name (current-buffer))))
14200 (setq res (org-scan-tags func matcher todo-only start-level)))
14201 ;; Get the right scope
14203 ((and scope (listp scope) (symbolp (car scope)))
14204 (setq scope (eval scope)))
14205 ((eq scope 'agenda)
14206 (setq scope (org-agenda-files t)))
14207 ((eq scope 'agenda-with-archives)
14208 (setq scope (org-agenda-files t))
14209 (setq scope (org-add-archive-files scope)))
14211 (setq scope (list (buffer-file-name))))
14212 ((eq scope 'file-with-archives)
14213 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14214 (org-agenda-prepare-buffers scope)
14215 (while (setq file (pop scope))
14216 (with-current-buffer (org-find-base-buffer-visiting file)
14220 (goto-char (point-min))
14221 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14226 ;;; Setting and retrieving properties
14228 (defconst org-special-properties
14229 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14230 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14231 "The special properties valid in Org-mode.
14233 These are properties that are not defined in the property drawer,
14234 but in some other way.")
14236 (defconst org-default-properties
14237 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14238 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14239 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14240 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14241 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14242 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14243 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14244 "Some properties that are used by Org-mode for various purposes.
14245 Being in this list makes sure that they are offered for completion.")
14247 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14248 "Regular expression matching the first line of a property drawer.")
14250 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14251 "Regular expression matching the last line of a property drawer.")
14253 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14254 "Regular expression matching the first line of a property drawer.")
14256 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14257 "Regular expression matching the first line of a property drawer.")
14259 (defconst org-property-drawer-re
14260 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14261 org-property-end-re "\\)\n?")
14262 "Matches an entire property drawer.")
14264 (defconst org-clock-drawer-re
14265 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14266 org-property-end-re "\\)\n?")
14267 "Matches an entire clock drawer.")
14269 (defsubst org-re-property (property)
14270 "Return a regexp matching a PROPERTY line.
14271 Match group 1 will be set to the value."
14272 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14274 (defsubst org-re-property-keyword (property)
14275 "Return a regexp matching a PROPERTY line, possibly with no
14276 value for the property."
14277 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14279 (defun org-property-action ()
14280 "Do an action on properties."
14283 (org-at-property-p)
14284 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14285 (setq c (read-char-exclusive))
14288 (call-interactively 'org-set-property))
14290 (call-interactively 'org-delete-property))
14292 (call-interactively 'org-delete-property-globally))
14294 (call-interactively 'org-compute-property-at-point))
14295 (t (error "No such property action %c" c)))))
14297 (defun org-inc-effort ()
14298 "Increment the value of the effort property in the current entry."
14300 (org-set-effort nil t))
14302 (defun org-set-effort (&optional value increment)
14303 "Set the effort property of the current entry.
14304 With numerical prefix arg, use the nth allowed value, 0 stands for the
14305 10th allowed value.
14307 When INCREMENT is non-nil, set the property to the next allowed value."
14309 (if (equal value 0) (setq value 10))
14310 (let* ((completion-ignore-case t)
14311 (prop org-effort-property)
14312 (cur (org-entry-get nil prop))
14313 (allowed (org-property-get-allowed-values nil prop 'table))
14314 (existing (mapcar 'list (org-property-values prop)))
14317 ((stringp value) value)
14318 ((and allowed (integerp value))
14319 (or (car (nth (1- value) allowed))
14320 (car (org-last allowed))))
14321 ((and allowed increment)
14322 (or (caadr (member (list cur) allowed))
14323 (error "Allowed effort values are not set")))
14325 (message "Select 1-9,0, [RET%s]: %s"
14326 (if cur (concat "=" cur) "")
14327 (mapconcat 'car allowed " "))
14328 (setq rpl (read-char-exclusive))
14329 (if (equal rpl ?\r)
14331 (setq rpl (- rpl ?0))
14332 (if (equal rpl 0) (setq rpl 10))
14333 (if (and (> rpl 0) (<= rpl (length allowed)))
14334 (car (nth (1- rpl) allowed))
14335 (org-completing-read "Effort: " allowed nil))))
14337 (let (org-completion-use-ido org-completion-use-iswitchb)
14338 (org-completing-read
14339 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14340 (concat "[" cur "]") "")
14342 existing nil nil "" nil cur))))))
14343 (unless (equal (org-entry-get nil prop) val)
14344 (org-entry-put nil prop val))
14345 (message "%s is now %s" prop val)))
14347 (defun org-at-property-p ()
14348 "Is cursor inside a property drawer?"
14350 (beginning-of-line 1)
14351 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14352 (save-match-data ;; Used by calling procedures
14354 (range (unless (org-before-first-heading-p)
14355 (org-get-property-block))))
14356 (and range (<= (car range) p) (< p (cdr range))))))))
14358 (defun org-get-property-block (&optional beg end force)
14359 "Return the (beg . end) range of the body of the property drawer.
14360 BEG and END are the beginning and end of the current subtree, or of
14361 the part before the first headline. If they are not given, they will
14362 be found. If the drawer does not exist and FORCE is non-nil, create
14366 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14367 (progn (org-back-to-heading t) (point))))
14368 (end (or end (and (not (outline-next-heading)) (point-max))
14371 (if (re-search-forward org-property-start-re end t)
14372 (setq beg (1+ (match-end 0)))
14375 (org-insert-property-drawer)
14376 (setq end (progn (outline-next-heading) (point))))
14379 (if (re-search-forward org-property-start-re end t)
14380 (setq beg (1+ (match-end 0)))))
14381 (if (re-search-forward org-property-end-re end t)
14382 (setq end (match-beginning 0))
14383 (or force (throw 'exit nil))
14387 (insert ":END:\n"))
14390 (defun org-entry-properties (&optional pom which specific)
14391 "Get all properties of the entry at point-or-marker POM.
14392 This includes the TODO keyword, the tags, time strings for deadline,
14393 scheduled, and clocking, and any additional properties defined in the
14394 entry. The return value is an alist, keys may occur multiple times
14395 if the property key was used several times.
14396 POM may also be nil, in which case the current entry is used.
14397 If WHICH is nil or `all', get all properties. If WHICH is
14398 `special' or `standard', only get that subclass. If WHICH
14399 is a string only get exactly this property. SPECIFIC can be a string, the
14400 specific property we are interested in. Specifying it can speed
14401 things up because then unnecessary parsing is avoided."
14402 (setq which (or which 'all))
14403 (org-with-point-at pom
14404 (let ((clockstr (substring org-clock-string 0 -1))
14405 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14406 (case-fold-search nil)
14407 beg end range props sum-props key key1 value string clocksum clocksumt)
14409 (when (condition-case nil
14410 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14413 (setq sum-props (get-text-property (point) 'org-summaries))
14414 (setq clocksum (get-text-property (point) :org-clock-minutes)
14415 clocksumt (get-text-property (point) :org-clock-minutes-today))
14416 (outline-next-heading)
14418 (when (memq which '(all special))
14419 ;; Get the special properties, like TODO and tags
14421 (when (and (or (not specific) (string= specific "TODO"))
14422 (looking-at org-todo-line-regexp) (match-end 2))
14423 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14424 (when (and (or (not specific) (string= specific "PRIORITY"))
14425 (looking-at org-priority-regexp))
14426 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14427 (when (or (not specific) (string= specific "FILE"))
14428 (push (cons "FILE" buffer-file-name) props))
14429 (when (and (or (not specific) (string= specific "TAGS"))
14430 (setq value (org-get-tags-string))
14431 (string-match "\\S-" value))
14432 (push (cons "TAGS" value) props))
14433 (when (and (or (not specific) (string= specific "ALLTAGS"))
14434 (setq value (org-get-tags-at)))
14435 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14438 (when (or (not specific) (string= specific "BLOCKED"))
14439 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14440 (when (or (not specific)
14442 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14443 "TIMESTAMP" "TIMESTAMP_IA")))
14445 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14446 (setq key (if (match-end 1)
14447 (substring (org-match-string-no-properties 1)
14449 string (if (equal key clockstr)
14451 (buffer-substring-no-properties
14452 (match-beginning 3) (goto-char
14454 (substring (org-match-string-no-properties 3)
14456 ;; Get the correct property name from the key. This is
14457 ;; necessary if the user has configured time keywords.
14458 (setq key1 (concat key ":"))
14462 (if (= (char-after (match-beginning 3)) ?\[)
14463 "TIMESTAMP_IA" "TIMESTAMP")))
14464 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14465 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14466 ((equal key1 org-closed-string) (setq key "CLOSED"))
14467 ((equal key1 org-clock-string) (setq key "CLOCK")))
14468 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14470 (push (cons key string) props)
14471 ;; no need to search further if match is found
14473 (when (or (equal key "CLOCK") (not (assoc key props)))
14474 (push (cons key string) props)))))))
14476 (when (memq which '(all standard))
14477 ;; Get the standard properties, like :PROP: ...
14478 (setq range (org-get-property-block beg end))
14480 (goto-char (car range))
14481 (while (re-search-forward
14482 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14484 (setq key (org-match-string-no-properties 1)
14485 value (org-trim (or (org-match-string-no-properties 2) "")))
14486 (unless (member key excluded)
14487 (push (cons key (or value "")) props)))))
14489 (push (cons "CLOCKSUM"
14490 (org-columns-number-to-string (/ (float clocksum) 60.)
14494 (push (cons "CLOCKSUM_T"
14495 (org-columns-number-to-string (/ (float clocksumt) 60.)
14498 (unless (assoc "CATEGORY" props)
14499 (push (cons "CATEGORY" (org-get-category)) props))
14500 (append sum-props (nreverse props)))))))
14502 (defun org-entry-get (pom property &optional inherit literal-nil)
14503 "Get value of PROPERTY for entry or content at point-or-marker POM.
14504 If INHERIT is non-nil and the entry does not have the property,
14505 then also check higher levels of the hierarchy.
14506 If INHERIT is the symbol `selective', use inheritance only if the setting
14507 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14508 If the property is present but empty, the return value is the empty string.
14509 If the property is not present at all, nil is returned.
14511 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14512 do not interpret it as the list atom nil. This is used for inheritance
14513 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14514 (org-with-point-at pom
14515 (if (and inherit (if (eq inherit 'selective)
14516 (org-property-inherit-p property)
14518 (org-entry-get-with-inheritance property literal-nil)
14519 (if (member property org-special-properties)
14520 ;; We need a special property. Use `org-entry-properties' to
14521 ;; retrieve it, but specify the wanted property
14522 (cdr (assoc property (org-entry-properties nil 'special property)))
14523 (let* ((range (org-get-property-block))
14524 (props (list (or (assoc property org-file-properties)
14525 (assoc property org-global-properties)
14526 (assoc property org-global-properties-fixed))))
14528 (when (re-search-forward
14529 (org-re-property key) (cdr range) t)
14531 (org-update-property-plist
14534 (org-match-string-no-properties 1) "")
14537 (when (and range (goto-char (car range)))
14538 (funcall ap property)
14539 (goto-char (car range))
14540 (while (funcall ap (concat property "+")))
14541 (setq val (cdr (assoc property props)))
14542 (when val (if literal-nil val (org-not-nil val)))))))))
14544 (defun org-property-or-variable-value (var &optional inherit)
14545 "Check if there is a property fixing the value of VAR.
14546 If yes, return this value. If not, return the current value of the variable."
14547 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14548 (if (and prop (stringp prop) (string-match "\\S-" prop))
14550 (symbol-value var))))
14552 (defun org-entry-delete (pom property)
14553 "Delete the property PROPERTY from entry at point-or-marker POM."
14554 (org-with-point-at pom
14555 (if (member property org-special-properties)
14556 nil ; cannot delete these properties.
14557 (let ((range (org-get-property-block)))
14559 (goto-char (car range))
14561 (org-re-property property)
14564 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14568 ;; Multi-values properties are properties that contain multiple values
14569 ;; These values are assumed to be single words, separated by whitespace.
14570 (defun org-entry-add-to-multivalued-property (pom property value)
14571 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14572 (let* ((old (org-entry-get pom property))
14573 (values (and old (org-split-string old "[ \t]"))))
14574 (setq value (org-entry-protect-space value))
14575 (unless (member value values)
14576 (setq values (cons value values))
14577 (org-entry-put pom property
14578 (mapconcat 'identity values " ")))))
14580 (defun org-entry-remove-from-multivalued-property (pom property value)
14581 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14582 (let* ((old (org-entry-get pom property))
14583 (values (and old (org-split-string old "[ \t]"))))
14584 (setq value (org-entry-protect-space value))
14585 (when (member value values)
14586 (setq values (delete value values))
14587 (org-entry-put pom property
14588 (mapconcat 'identity values " ")))))
14590 (defun org-entry-member-in-multivalued-property (pom property value)
14591 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14592 (let* ((old (org-entry-get pom property))
14593 (values (and old (org-split-string old "[ \t]"))))
14594 (setq value (org-entry-protect-space value))
14595 (member value values)))
14597 (defun org-entry-get-multivalued-property (pom property)
14598 "Return a list of values in a multivalued property."
14599 (let* ((value (org-entry-get pom property))
14600 (values (and value (org-split-string value "[ \t]"))))
14601 (mapcar 'org-entry-restore-space values)))
14603 (defun org-entry-put-multivalued-property (pom property &rest values)
14604 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14605 VALUES should be a list of strings. Spaces will be protected."
14606 (org-entry-put pom property
14607 (mapconcat 'org-entry-protect-space values " "))
14608 (let* ((value (org-entry-get pom property))
14609 (values (and value (org-split-string value "[ \t]"))))
14610 (mapcar 'org-entry-restore-space values)))
14612 (defun org-entry-protect-space (s)
14613 "Protect spaces and newline in string S."
14614 (while (string-match " " s)
14615 (setq s (replace-match "%20" t t s)))
14616 (while (string-match "\n" s)
14617 (setq s (replace-match "%0A" t t s)))
14620 (defun org-entry-restore-space (s)
14621 "Restore spaces and newline in string S."
14622 (while (string-match "%20" s)
14623 (setq s (replace-match " " t t s)))
14624 (while (string-match "%0A" s)
14625 (setq s (replace-match "\n" t t s)))
14628 (defvar org-entry-property-inherited-from (make-marker)
14629 "Marker pointing to the entry from where a property was inherited.
14630 Each call to `org-entry-get-with-inheritance' will set this marker to the
14631 location of the entry where the inheritance search matched. If there was
14632 no match, the marker will point nowhere.
14633 Note that also `org-entry-get' calls this function, if the INHERIT flag
14636 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14637 "Get PROPERTY of entry or content at point, search higher levels if needed.
14638 The search will stop at the first ancestor which has the property defined.
14639 If the value found is \"nil\", return nil to show that the property
14640 should be considered as undefined (this is the meaning of nil here).
14641 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14642 (move-marker org-entry-property-inherited-from nil)
14649 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14650 (or (ignore-errors (org-back-to-heading t))
14651 (goto-char (point-min)))
14652 (move-marker org-entry-property-inherited-from (point))
14654 (or (ignore-errors (org-up-heading-safe))
14655 (throw 'ex nil))))))
14657 (cdr (assoc property org-file-properties))
14658 (cdr (assoc property org-global-properties))
14659 (cdr (assoc property org-global-properties-fixed))))
14660 (if literal-nil tmp (org-not-nil tmp))))
14662 (defvar org-property-changed-functions nil
14663 "Hook called when the value of a property has changed.
14664 Each hook function should accept two arguments, the name of the property
14665 and the new value.")
14667 (defun org-entry-put (pom property value)
14668 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14669 (org-with-point-at pom
14670 (org-back-to-heading t)
14671 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14674 ((equal property "TODO")
14675 (when (and (stringp value) (string-match "\\S-" value)
14676 (not (member value org-todo-keywords-1)))
14677 (error "\"%s\" is not a valid TODO state" value))
14678 (if (or (not value)
14679 (not (string-match "\\S-" value)))
14680 (setq value 'none))
14682 (org-set-tags nil 'align))
14683 ((equal property "PRIORITY")
14684 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14685 (string-to-char value) ?\ ))
14686 (org-set-tags nil 'align))
14687 ((equal property "CLOCKSUM")
14688 (if (not (re-search-forward
14689 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14690 (error "Cannot find a clock log")
14691 (goto-char (- (match-end 1) 2))
14693 ((eq value 'earlier) (org-timestamp-down))
14694 ((eq value 'later) (org-timestamp-up)))
14695 (org-clock-sum-current-item)))
14696 ((equal property "SCHEDULED")
14697 (if (re-search-forward org-scheduled-time-regexp end t)
14699 ((eq value 'earlier) (org-timestamp-change -1 'day))
14700 ((eq value 'later) (org-timestamp-change 1 'day))
14701 (t (call-interactively 'org-schedule)))
14702 (call-interactively 'org-schedule)))
14703 ((equal property "DEADLINE")
14704 (if (re-search-forward org-deadline-time-regexp end t)
14706 ((eq value 'earlier) (org-timestamp-change -1 'day))
14707 ((eq value 'later) (org-timestamp-change 1 'day))
14708 (t (call-interactively 'org-deadline)))
14709 (call-interactively 'org-deadline)))
14710 ((member property org-special-properties)
14711 (error "The %s property can not yet be set with `org-entry-put'"
14713 (t ; a non-special property
14714 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14715 (setq range (org-get-property-block beg end 'force))
14716 (goto-char (car range))
14717 (if (re-search-forward
14718 (org-re-property-keyword property) (cdr range) t)
14720 (delete-region (match-beginning 0) (match-end 0))
14721 (goto-char (match-beginning 0)))
14722 (goto-char (cdr range))
14726 (insert ":" property ":")
14727 (and value (insert " " value))
14728 (org-indent-line)))))
14729 (run-hook-with-args 'org-property-changed-functions property value)))
14731 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14732 "Get all property keys in the current buffer.
14733 With INCLUDE-SPECIALS, also list the special properties that reflect things
14734 like tags and TODO state.
14735 With INCLUDE-DEFAULTS, also include properties that has special meaning
14736 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14738 With INCLUDE-COLUMNS, also include property names given in COLUMN
14739 formats in the current buffer."
14740 (let (rtn range cfmt s p)
14744 (goto-char (point-min))
14745 (while (re-search-forward org-property-start-re nil t)
14746 (setq range (org-get-property-block))
14747 (goto-char (car range))
14748 (while (re-search-forward
14749 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14751 (add-to-list 'rtn (org-match-string-no-properties 1)))
14752 (outline-next-heading))))
14754 (when include-specials
14755 (setq rtn (append org-special-properties rtn)))
14757 (when include-defaults
14758 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14759 (add-to-list 'rtn org-effort-property))
14761 (when include-columns
14765 (goto-char (point-min))
14766 (while (re-search-forward
14767 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14769 (setq cfmt (match-string 2) s 0)
14770 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14772 (setq s (match-end 0)
14773 p (match-string 1 cfmt))
14774 (unless (or (equal p "ITEM")
14775 (member p org-special-properties))
14776 (add-to-list 'rtn (match-string 1 cfmt))))))))
14778 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14780 (defun org-property-values (key)
14781 "Return a list of all values of property KEY in the current buffer."
14785 (goto-char (point-min))
14786 (let ((re (org-re-property key))
14788 (while (re-search-forward re nil t)
14789 (add-to-list 'values (org-trim (match-string 1))))
14790 (delete "" values)))))
14792 (defun org-insert-property-drawer ()
14793 "Insert a property drawer into the current entry."
14794 (org-back-to-heading t)
14795 (looking-at org-outline-regexp)
14796 (let ((indent (if org-adapt-indentation
14797 (- (match-end 0) (match-beginning 0))
14800 (re (concat "^[ \t]*" org-keyword-time-regexp))
14802 (outline-next-heading)
14805 (while (re-search-forward re end t))
14806 (setq hiddenp (outline-invisible-p))
14808 (and (equal (char-after) ?\n) (forward-char 1))
14809 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14810 (if (member (match-string 1) '("CLOCK:" ":END:"))
14811 ;; just skip this line
14812 (beginning-of-line 2)
14813 ;; Drawer start, find the end
14814 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14815 (beginning-of-line 1)))
14816 (org-skip-over-state-notes)
14817 (skip-chars-backward " \t\n\r")
14818 (if (eq (char-before) ?*) (forward-char 1))
14819 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14820 (beginning-of-line 0)
14821 (org-indent-to-column indent)
14822 (beginning-of-line 2)
14823 (org-indent-to-column indent)
14824 (beginning-of-line 0)
14827 (org-back-to-heading t)
14829 (org-flag-drawer t))))
14831 (defun org-insert-drawer (&optional arg drawer)
14832 "Insert a drawer at point.
14834 Optional argument DRAWER, when non-nil, is a string representing
14835 drawer's name. Otherwise, the user is prompted for a name.
14837 If a region is active, insert the drawer around that region
14840 Point is left between drawer's boundaries."
14842 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14844 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14845 ;; internally by Org. They are meant to be inserted
14847 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14848 ;; Remove system drawers from list. Note: For some reason,
14849 ;; `org-completing-read' ignores the predicate while
14850 ;; `completing-read' handles it fine.
14851 (drawer (if arg "PROPERTIES"
14854 "Drawer: " org-drawers
14855 (lambda (d) (not (member d system-drawers))))))))
14857 ;; With C-u, fall back on `org-insert-property-drawer'
14858 (arg (org-insert-property-drawer))
14859 ;; With an active region, insert a drawer at point.
14860 ((not (org-region-active-p))
14862 (unless (bolp) (insert "\n"))
14863 (insert (format ":%s:\n\n:END:\n" drawer))
14864 (forward-line -2)))
14865 ;; Otherwise, insert the drawer at point
14867 (let ((rbeg (region-beginning))
14868 (rend (copy-marker (region-end))))
14872 (beginning-of-line)
14873 (when (save-excursion
14874 (re-search-forward org-outline-regexp-bol rend t))
14875 (error "Drawers cannot contain headlines"))
14876 ;; Position point at the beginning of the first
14877 ;; non-blank line in region. Insert drawer's opening
14878 ;; there, then indent it.
14879 (org-skip-whitespace)
14880 (beginning-of-line)
14881 (insert ":" drawer ":\n")
14883 (indent-for-tab-command)
14884 ;; Move point to the beginning of the first blank line
14885 ;; after the last non-blank line in region. Insert
14886 ;; drawer's closing, then indent it.
14888 (skip-chars-backward " \r\t\n")
14890 (deactivate-mark t)
14891 (indent-for-tab-command)
14892 (unless (eolp) (insert "\n")))
14893 ;; Clear marker, whatever the outcome of insertion is.
14894 (set-marker rend nil)))))))
14896 (defvar org-property-set-functions-alist nil
14897 "Property set function alist.
14898 Each entry should have the following format:
14900 (PROPERTY . READ-FUNCTION)
14902 The read function will be called with the same argument as
14903 `org-completing-read'.")
14905 (defun org-set-property-function (property)
14906 "Get the function that should be used to set PROPERTY.
14907 This is computed according to `org-property-set-functions-alist'."
14908 (or (cdr (assoc property org-property-set-functions-alist))
14909 'org-completing-read))
14911 (defun org-read-property-value (property)
14912 "Read PROPERTY value from user."
14913 (let* ((completion-ignore-case t)
14914 (allowed (org-property-get-allowed-values nil property 'table))
14915 (cur (org-entry-get nil property))
14916 (prompt (concat property " value"
14917 (if (and cur (string-match "\\S-" cur))
14918 (concat " [" cur "]") "") ": "))
14919 (set-function (org-set-property-function property))
14921 (funcall set-function prompt allowed nil
14922 (not (get-text-property 0 'org-unrestricted
14924 (let (org-completion-use-ido org-completion-use-iswitchb)
14925 (funcall set-function prompt
14926 (mapcar 'list (org-property-values property))
14927 nil nil "" nil cur)))))
14932 (defvar org-last-set-property nil)
14933 (defun org-read-property-name ()
14934 "Read a property name."
14935 (let* ((completion-ignore-case t)
14936 (keys (org-buffer-property-keys nil t t))
14937 (default-prop (or (save-excursion
14939 (beginning-of-line)
14940 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14941 (null (string= (match-string 1) "END"))
14942 (match-string 1))))
14943 org-last-set-property))
14944 (property (org-icompleting-read
14946 (if default-prop (concat " [" default-prop "]") "")
14948 (mapcar 'list keys)
14952 (if (member property keys)
14954 (or (cdr (assoc (downcase property)
14955 (mapcar (lambda (x) (cons (downcase x) x))
14959 (defun org-set-property (property value)
14960 "In the current entry, set PROPERTY to VALUE.
14961 When called interactively, this will prompt for a property name, offering
14962 completion on existing and default properties. And then it will prompt
14963 for a value, offering completion either on allowed values (via an inherited
14964 xxx_ALL property) or on existing values in other instances of this property
14965 in the current file."
14966 (interactive (list nil nil))
14967 (let* ((property (or property (org-read-property-name)))
14968 (value (or value (org-read-property-value property)))
14969 (fn (cdr (assoc property org-properties-postprocess-alist))))
14970 (setq org-last-set-property property)
14971 ;; Possibly postprocess the inserted value:
14972 (when fn (setq value (funcall fn value)))
14973 (unless (equal (org-entry-get nil property) value)
14974 (org-entry-put nil property value))))
14976 (defun org-delete-property (property)
14977 "In the current entry, delete PROPERTY."
14979 (let* ((completion-ignore-case t)
14980 (prop (org-icompleting-read "Property: "
14981 (org-entry-properties nil 'standard))))
14983 (message "Property %s %s" property
14984 (if (org-entry-delete nil property)
14986 "was not present in the entry")))
14988 (defun org-delete-property-globally (property)
14989 "Remove PROPERTY globally, from all entries."
14991 (let* ((completion-ignore-case t)
14992 (prop (org-icompleting-read
14993 "Globally remove property: "
14994 (mapcar 'list (org-buffer-property-keys)))))
14999 (goto-char (point-min))
15001 (while (re-search-forward
15002 (org-re-property property)
15004 (setq cnt (1+ cnt))
15005 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15006 (message "Property \"%s\" removed from %d entries" property cnt)))))
15008 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15010 (defun org-compute-property-at-point ()
15011 "Compute the property at point.
15012 This looks for an enclosing column format, extracts the operator and
15013 then applies it to the property in the column format's scope."
15015 (unless (org-at-property-p)
15016 (error "Not at a property"))
15017 (let ((prop (org-match-string-no-properties 2)))
15018 (org-columns-get-format-and-top-level)
15019 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15020 (error "No operator defined for property %s" prop))
15021 (org-columns-compute prop)))
15023 (defvar org-property-allowed-value-functions nil
15024 "Hook for functions supplying allowed values for a specific property.
15025 The functions must take a single argument, the name of the property, and
15026 return a flat list of allowed values. If \":ETC\" is one of
15027 the values, this means that these values are intended as defaults for
15028 completion, but that other values should be allowed too.
15029 The functions must return nil if they are not responsible for this
15032 (defun org-property-get-allowed-values (pom property &optional table)
15033 "Get allowed values for the property PROPERTY.
15034 When TABLE is non-nil, return an alist that can directly be used for
15038 ((equal property "TODO")
15039 (setq vals (org-with-point-at pom
15040 (append org-todo-keywords-1 '("")))))
15041 ((equal property "PRIORITY")
15042 (let ((n org-lowest-priority))
15043 (while (>= n org-highest-priority)
15044 (push (char-to-string n) vals)
15046 ((member property org-special-properties))
15047 ((setq vals (run-hook-with-args-until-success
15048 'org-property-allowed-value-functions property)))
15050 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15051 (when (and vals (string-match "\\S-" vals))
15052 (setq vals (car (read-from-string (concat "(" vals ")"))))
15053 (setq vals (mapcar (lambda (x)
15054 (cond ((stringp x) x)
15055 ((numberp x) (number-to-string x))
15056 ((symbolp x) (symbol-name x))
15059 (when (member ":ETC" vals)
15060 (setq vals (remove ":ETC" vals))
15061 (org-add-props (car vals) '(org-unrestricted t)))
15062 (if table (mapcar 'list vals) vals)))
15064 (defun org-property-previous-allowed-value (&optional previous)
15065 "Switch to the next allowed value for this property."
15067 (org-property-next-allowed-value t))
15069 (defun org-property-next-allowed-value (&optional previous)
15070 "Switch to the next allowed value for this property."
15072 (unless (org-at-property-p)
15073 (error "Not at a property"))
15074 (let* ((key (match-string 2))
15075 (value (match-string 3))
15076 (allowed (or (org-property-get-allowed-values (point) key)
15077 (and (member value '("[ ]" "[-]" "[X]"))
15081 (error "Allowed values for this property have not been defined"))
15082 (if previous (setq allowed (reverse allowed)))
15083 (if (member value allowed)
15084 (setq nval (car (cdr (member value allowed)))))
15085 (setq nval (or nval (car allowed)))
15086 (if (equal nval value)
15087 (error "Only one allowed value for this property"))
15088 (org-at-property-p)
15089 (replace-match (concat " :" key ": " nval) t t)
15091 (beginning-of-line 1)
15092 (skip-chars-forward " \t")
15093 (run-hook-with-args 'org-property-changed-functions key nval)))
15095 (defun org-find-olp (path &optional this-buffer)
15096 "Return a marker pointing to the entry at outline path OLP.
15097 If anything goes wrong, throw an error.
15098 You can wrap this call to catch the error like this:
15100 (condition-case msg
15101 (org-mobile-locate-entry (match-string 4))
15102 (error (nth 1 msg)))
15104 The return value will then be either a string with the error message,
15105 or a marker if everything is OK.
15107 If THIS-BUFFER is set, the outline path does not contain a file,
15109 (let* ((file (if this-buffer buffer-file-name (pop path)))
15110 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15114 limit re end found pos heading cnt flevel)
15115 (unless buffer (error "File not found :%s" file))
15116 (with-current-buffer buffer
15120 (setq limit (point-max))
15121 (goto-char (point-min))
15122 (while (setq heading (pop path))
15123 (setq re (format org-complex-heading-regexp-format
15124 (regexp-quote heading)))
15125 (setq cnt 0 pos (point))
15126 (while (re-search-forward re end t)
15127 (setq level (- (match-end 1) (match-beginning 1)))
15128 (if (and (>= level lmin) (<= level lmax))
15129 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15130 (when (= cnt 0) (error "Heading not found on level %d: %s"
15132 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15135 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15136 (setq end (save-excursion (org-end-of-subtree t t))))
15137 (when (org-at-heading-p)
15138 (move-marker (make-marker) (point))))))))
15140 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15141 "Find node HEADING in BUFFER.
15142 Return a marker to the heading if it was found, or nil if not.
15143 If POS-ONLY is set, return just the position instead of a marker.
15145 The heading text must match exact, but it may have a TODO keyword,
15146 a priority cookie and tags in the standard locations."
15147 (with-current-buffer (or buffer (current-buffer))
15151 (goto-char (point-min))
15152 (let (case-fold-search)
15153 (if (re-search-forward
15154 (format org-complex-heading-regexp-format
15155 (regexp-quote heading)) nil t)
15157 (match-beginning 0)
15158 (move-marker (make-marker) (match-beginning 0)))))))))
15160 (defun org-find-exact-heading-in-directory (heading &optional dir)
15161 "Find Org node headline HEADING in all .org files in directory DIR.
15162 When the target headline is found, return a marker to this location."
15163 (let ((files (directory-files (or dir default-directory)
15164 nil "\\`[^.#].*\\.org\\'"))
15165 file visiting m buffer)
15167 (while (setq file (pop files))
15168 (message "trying %s" file)
15169 (setq visiting (org-find-base-buffer-visiting file))
15170 (setq buffer (or visiting (find-file-noselect file)))
15171 (setq m (org-find-exact-headline-in-buffer
15173 (when (and (not m) (not visiting)) (kill-buffer buffer))
15174 (and m (throw 'found m))))))
15176 (defun org-find-entry-with-id (ident)
15177 "Locate the entry that contains the ID property with exact value IDENT.
15178 IDENT can be a string, a symbol or a number, this function will search for
15179 the string representation of it.
15180 Return the position where this entry starts, or nil if there is no such entry."
15181 (interactive "sID: ")
15183 ((stringp ident) ident)
15184 ((symbol-name ident) (symbol-name ident))
15185 ((numberp ident) (number-to-string ident))
15186 (t (error "IDENT %s must be a string, symbol or number" ident))))
15187 (case-fold-search nil))
15191 (goto-char (point-min))
15192 (when (re-search-forward
15193 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15195 (org-back-to-heading t)
15200 (defvar org-last-changed-timestamp nil)
15201 (defvar org-last-inserted-timestamp nil
15202 "The last time stamp inserted with `org-insert-time-stamp'.")
15203 (defvar org-time-was-given) ; dynamically scoped parameter
15204 (defvar org-end-time-was-given) ; dynamically scoped parameter
15205 (defvar org-ts-what) ; dynamically scoped parameter
15207 (defun org-time-stamp (arg &optional inactive)
15208 "Prompt for a date/time and insert a time stamp.
15209 If the user specifies a time like HH:MM or if this command is
15210 called with at least one prefix argument, the time stamp contains
15211 the date and the time. Otherwise, only the date is be included.
15213 All parts of a date not specified by the user is filled in from
15214 the current date/time. So if you just press return without
15215 typing anything, the time stamp will represent the current
15218 If there is already a timestamp at the cursor, it will be
15221 With two universal prefix arguments, insert an active timestamp
15222 with the current time without prompting the user."
15226 ;; Default time is either today, or, when entering a range,
15227 ;; the range start.
15228 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15230 (re-search-backward
15231 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15232 (- (point) 20) t)))
15233 (apply 'encode-time (org-parse-time-string (match-string 1)))
15235 (default-input (and ts (org-get-compact-tod ts)))
15236 (repeater (save-excursion
15238 (beginning-of-line)
15239 (when (re-search-forward
15240 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15241 (save-excursion (progn (end-of-line) (point))) t)
15242 (match-string 0)))))
15243 org-time-was-given org-end-time-was-given time)
15245 ((and (org-at-timestamp-p t)
15246 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15247 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15249 (setq time (let ((this-command this-command))
15250 (org-read-date arg 'totime nil nil
15251 default-time default-input inactive)))
15252 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15253 ((org-at-timestamp-p t)
15254 (setq time (let ((this-command this-command))
15255 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15256 (when (org-at-timestamp-p t) ; just to get the match data
15257 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15259 (setq org-last-changed-timestamp
15260 (org-insert-time-stamp
15261 time (or org-time-was-given arg)
15262 inactive nil nil (list org-end-time-was-given)))
15263 (when repeater (goto-char (1- (point))) (insert " " repeater)
15264 (setq org-last-changed-timestamp
15265 (concat (substring org-last-inserted-timestamp 0 -1)
15266 " " repeater ">"))))
15267 (message "Timestamp updated"))
15269 (org-insert-time-stamp (current-time) t))
15271 (setq time (let ((this-command this-command))
15272 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15273 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15274 nil nil (list org-end-time-was-given))))))
15276 ;; FIXME: can we use this for something else, like computing time differences?
15277 (defun org-get-compact-tod (s)
15278 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15279 (let* ((t1 (match-string 1 s))
15280 (h1 (string-to-number (match-string 2 s)))
15281 (m1 (string-to-number (match-string 3 s)))
15282 (t2 (and (match-end 4) (match-string 5 s)))
15283 (h2 (and t2 (string-to-number (match-string 6 s))))
15284 (m2 (and t2 (string-to-number (match-string 7 s))))
15288 (setq dh (- h2 h1) dm (- m2 m1))
15289 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15290 (concat t1 "+" (number-to-string dh)
15291 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15293 (defun org-time-stamp-inactive (&optional arg)
15294 "Insert an inactive time stamp.
15295 An inactive time stamp is enclosed in square brackets instead of angle
15296 brackets. It is inactive in the sense that it does not trigger agenda entries,
15297 does not link to the calendar and cannot be changed with the S-cursor keys.
15298 So these are more for recording a certain time/date."
15300 (org-time-stamp arg 'inactive))
15302 (defvar org-date-ovl (make-overlay 1 1))
15303 (overlay-put org-date-ovl 'face 'org-date-selected)
15304 (org-detach-overlay org-date-ovl)
15306 (defvar org-ans1) ; dynamically scoped parameter
15307 (defvar org-ans2) ; dynamically scoped parameter
15309 (defvar org-plain-time-of-day-regexp) ; defined below
15311 (defvar org-overriding-default-time nil) ; dynamically scoped
15312 (defvar org-read-date-overlay nil)
15313 (defvar org-dcst nil) ; dynamically scoped
15314 (defvar org-read-date-history nil)
15315 (defvar org-read-date-final-answer nil)
15316 (defvar org-read-date-analyze-futurep nil)
15317 (defvar org-read-date-analyze-forced-year nil)
15318 (defvar org-read-date-inactive)
15320 (defun org-read-date (&optional org-with-time to-time from-string prompt
15321 default-time default-input inactive)
15322 "Read a date, possibly a time, and make things smooth for the user.
15323 The prompt will suggest to enter an ISO date, but you can also enter anything
15324 which will at least partially be understood by `parse-time-string'.
15325 Unrecognized parts of the date will default to the current day, month, year,
15326 hour and minute. If this command is called to replace a timestamp at point,
15327 or to enter the second timestamp of a range, the default time is taken
15328 from the existing stamp. Furthermore, the command prefers the future,
15329 so if you are giving a date where the year is not given, and the day-month
15330 combination is already past in the current year, it will assume you
15331 mean next year. For details, see the manual. A few examples:
15333 3-2-5 --> 2003-02-05
15334 feb 15 --> currentyear-02-15
15335 2/15 --> currentyear-02-15
15336 sep 12 9 --> 2009-09-12
15337 12:45 --> today 12:45
15338 22 sept 0:34 --> currentyear-09-22 0:34
15339 12 --> currentyear-currentmonth-12
15340 Fri --> nearest Friday (today or later)
15343 Furthermore you can specify a relative date by giving, as the *first* thing
15344 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15345 change in days weeks, months, years.
15346 With a single plus or minus, the date is relative to today. With a double
15347 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15348 +4d --> four days from today
15349 +4 --> same as above
15350 +2w --> two weeks from today
15351 ++5 --> five days from default date
15353 The function understands only English month and weekday abbreviations.
15355 While prompting, a calendar is popped up - you can also select the
15356 date with the mouse (button 1). The calendar shows a period of three
15357 months. To scroll it to other months, use the keys `>' and `<'.
15358 If you don't like the calendar, turn it off with
15359 \(setq org-read-date-popup-calendar nil)
15361 With optional argument TO-TIME, the date will immediately be converted
15362 to an internal time.
15363 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15364 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15365 still enter a time, and this function will inform the calling routine
15366 about this change. The calling routine may then choose to change the
15367 format used to insert the time stamp into the buffer to include the time.
15368 With optional argument FROM-STRING, read from this string instead from
15369 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15370 the time/date that is used for everything that is not specified by the
15372 (require 'parse-time)
15373 (let* ((org-time-stamp-rounding-minutes
15374 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15375 (org-dcst org-display-custom-times)
15376 (ct (org-current-time))
15377 (org-def (or org-overriding-default-time default-time ct))
15378 (org-defdecode (decode-time org-def))
15380 (when (< (nth 2 org-defdecode) org-extend-today-until)
15381 (setcar (nthcdr 2 org-defdecode) -1)
15382 (setcar (nthcdr 1 org-defdecode) 59)
15383 (setq org-def (apply 'encode-time org-defdecode)
15384 org-defdecode (decode-time org-def)))))
15385 (calendar-frame-setup nil)
15386 (calendar-setup nil)
15387 (calendar-move-hook nil)
15388 (calendar-view-diary-initially-flag nil)
15389 (calendar-view-holidays-initially-flag nil)
15390 (timestr (format-time-string
15391 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15392 (prompt (concat (if prompt (concat prompt " ") "")
15393 (format "Date+time [%s]: " timestr)))
15394 ans (org-ans0 "") org-ans1 org-ans2 final)
15397 (from-string (setq ans from-string))
15398 (org-read-date-popup-calendar
15400 (save-window-excursion
15402 (org-eval-in-calendar '(setq cursor-type nil) t)
15405 (calendar-forward-day (- (time-to-days org-def)
15406 (calendar-absolute-from-gregorian
15407 (calendar-current-date))))
15408 (org-eval-in-calendar nil t)
15409 (let* ((old-map (current-local-map))
15410 (map (copy-keymap calendar-mode-map))
15411 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15412 (org-defkey map (kbd "RET") 'org-calendar-select)
15413 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15414 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15415 (org-defkey minibuffer-local-map [(meta shift left)]
15416 (lambda () (interactive)
15417 (org-eval-in-calendar '(calendar-backward-month 1))))
15418 (org-defkey minibuffer-local-map [(meta shift right)]
15419 (lambda () (interactive)
15420 (org-eval-in-calendar '(calendar-forward-month 1))))
15421 (org-defkey minibuffer-local-map [(meta shift up)]
15422 (lambda () (interactive)
15423 (org-eval-in-calendar '(calendar-backward-year 1))))
15424 (org-defkey minibuffer-local-map [(meta shift down)]
15425 (lambda () (interactive)
15426 (org-eval-in-calendar '(calendar-forward-year 1))))
15427 (org-defkey minibuffer-local-map [?\e (shift left)]
15428 (lambda () (interactive)
15429 (org-eval-in-calendar '(calendar-backward-month 1))))
15430 (org-defkey minibuffer-local-map [?\e (shift right)]
15431 (lambda () (interactive)
15432 (org-eval-in-calendar '(calendar-forward-month 1))))
15433 (org-defkey minibuffer-local-map [?\e (shift up)]
15434 (lambda () (interactive)
15435 (org-eval-in-calendar '(calendar-backward-year 1))))
15436 (org-defkey minibuffer-local-map [?\e (shift down)]
15437 (lambda () (interactive)
15438 (org-eval-in-calendar '(calendar-forward-year 1))))
15439 (org-defkey minibuffer-local-map [(shift up)]
15440 (lambda () (interactive)
15441 (org-eval-in-calendar '(calendar-backward-week 1))))
15442 (org-defkey minibuffer-local-map [(shift down)]
15443 (lambda () (interactive)
15444 (org-eval-in-calendar '(calendar-forward-week 1))))
15445 (org-defkey minibuffer-local-map [(shift left)]
15446 (lambda () (interactive)
15447 (org-eval-in-calendar '(calendar-backward-day 1))))
15448 (org-defkey minibuffer-local-map [(shift right)]
15449 (lambda () (interactive)
15450 (org-eval-in-calendar '(calendar-forward-day 1))))
15451 (org-defkey minibuffer-local-map ">"
15452 (lambda () (interactive)
15453 (org-eval-in-calendar '(scroll-calendar-left 1))))
15454 (org-defkey minibuffer-local-map "<"
15455 (lambda () (interactive)
15456 (org-eval-in-calendar '(scroll-calendar-right 1))))
15457 (org-defkey minibuffer-local-map "\C-v"
15458 (lambda () (interactive)
15459 (org-eval-in-calendar
15460 '(calendar-scroll-left-three-months 1))))
15461 (org-defkey minibuffer-local-map "\M-v"
15462 (lambda () (interactive)
15463 (org-eval-in-calendar
15464 '(calendar-scroll-right-three-months 1))))
15465 (run-hooks 'org-read-date-minibuffer-setup-hook)
15468 (use-local-map map)
15469 (setq org-read-date-inactive inactive)
15470 (add-hook 'post-command-hook 'org-read-date-display)
15471 (setq org-ans0 (read-string prompt default-input
15472 'org-read-date-history nil))
15473 ;; org-ans0: from prompt
15474 ;; org-ans1: from mouse click
15475 ;; org-ans2: from calendar motion
15476 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15477 (remove-hook 'post-command-hook 'org-read-date-display)
15478 (use-local-map old-map)
15479 (when org-read-date-overlay
15480 (delete-overlay org-read-date-overlay)
15481 (setq org-read-date-overlay nil)))))
15482 (bury-buffer "*Calendar*")))))
15484 (t ; Naked prompt only
15486 (setq ans (read-string prompt default-input
15487 'org-read-date-history timestr))
15488 (when org-read-date-overlay
15489 (delete-overlay org-read-date-overlay)
15490 (setq org-read-date-overlay nil)))))
15492 (setq final (org-read-date-analyze ans org-def org-defdecode))
15494 (when org-read-date-analyze-forced-year
15495 (message "Year was forced into %s"
15496 (if org-read-date-force-compatible-dates
15497 "compatible range (1970-2037)"
15498 "range representable on this machine"))
15501 ;; One round trip to get rid of 34th of August and stuff like that....
15502 (setq final (decode-time (apply 'encode-time final)))
15504 (setq org-read-date-final-answer ans)
15507 (apply 'encode-time final)
15508 (if (and (boundp 'org-time-was-given) org-time-was-given)
15509 (format "%04d-%02d-%02d %02d:%02d"
15510 (nth 5 final) (nth 4 final) (nth 3 final)
15511 (nth 2 final) (nth 1 final))
15512 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15515 (defvar org-defdecode)
15516 (defvar org-with-time)
15517 (defun org-read-date-display ()
15518 "Display the current date prompt interpretation in the minibuffer."
15519 (when org-read-date-display-live
15520 (when org-read-date-overlay
15521 (delete-overlay org-read-date-overlay))
15522 (when (minibufferp (current-buffer))
15525 (while (not (equal (buffer-substring
15526 (max (point-min) (- (point) 4)) (point))
15529 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15530 " " (or org-ans1 org-ans2)))
15531 (org-end-time-was-given nil)
15532 (f (org-read-date-analyze ans org-def org-defdecode))
15534 org-time-stamp-custom-formats
15535 org-time-stamp-formats))
15536 (fmt (if (or org-with-time
15537 (and (boundp 'org-time-was-given) org-time-was-given))
15540 (txt (format-time-string fmt (apply 'encode-time f)))
15541 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15542 (txt (concat "=> " txt)))
15543 (when (and org-end-time-was-given
15544 (string-match org-plain-time-of-day-regexp txt))
15545 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15546 org-end-time-was-given
15547 (substring txt (match-end 0)))))
15548 (when org-read-date-analyze-futurep
15549 (setq txt (concat txt " (=>F)")))
15550 (setq org-read-date-overlay
15551 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15552 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15554 (defun org-read-date-analyze (ans org-def org-defdecode)
15555 "Analyze the combined answer of the date prompt."
15556 ;; FIXME: cleanup and comment
15557 (let ((nowdecode (decode-time (current-time)))
15558 delta deltan deltaw deltadef year month day
15559 hour minute second wday pm h2 m2 tl wday1
15560 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15561 (setq org-read-date-analyze-futurep nil
15562 org-read-date-analyze-forced-year nil)
15563 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15566 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15567 (setq ans (replace-match "" t t ans)
15569 deltaw (nth 1 delta)
15570 deltadef (nth 2 delta)))
15572 ;; Check if there is an iso week date in there. If yes, store the
15573 ;; info and postpone interpreting it until the rest of the parsing
15575 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15576 (setq iso-year (if (match-end 1)
15577 (org-small-year-to-year
15578 (string-to-number (match-string 1 ans))))
15579 iso-weekday (if (match-end 3)
15580 (string-to-number (match-string 3 ans)))
15581 iso-week (string-to-number (match-string 2 ans)))
15582 (setq ans (replace-match "" t t ans)))
15584 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15585 (when (string-match
15586 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15587 (setq year (if (match-end 2)
15588 (string-to-number (match-string 2 ans))
15589 (progn (setq kill-year t)
15590 (string-to-number (format-time-string "%Y"))))
15591 month (string-to-number (match-string 3 ans))
15592 day (string-to-number (match-string 4 ans)))
15593 (if (< year 100) (setq year (+ 2000 year)))
15594 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15597 ;; Help matching dotted european dates
15598 (when (string-match
15599 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15600 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15602 (string-to-number (format-time-string "%Y")))
15603 day (string-to-number (match-string 1 ans))
15604 month (string-to-number (match-string 2 ans))
15605 ans (replace-match (format "%04d-%02d-%02d" year month day)
15608 ;; Help matching american dates, like 5/30 or 5/30/7
15609 (when (string-match
15610 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15611 (setq year (if (match-end 4)
15612 (string-to-number (match-string 4 ans))
15613 (progn (setq kill-year t)
15614 (string-to-number (format-time-string "%Y"))))
15615 month (string-to-number (match-string 1 ans))
15616 day (string-to-number (match-string 2 ans)))
15617 (if (< year 100) (setq year (+ 2000 year)))
15618 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15620 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15621 ;; If there is a time with am/pm, and *no* time without it, we convert
15622 ;; so that matching will be successful.
15623 (loop for i from 1 to 2 do ; twice, for end time as well
15624 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15625 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15626 (setq hour (string-to-number (match-string 1 ans))
15627 minute (if (match-end 3)
15628 (string-to-number (match-string 3 ans))
15631 (string-to-char (downcase (match-string 4 ans)))))
15632 (if (and (= hour 12) (not pm))
15634 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15635 (setq ans (replace-match (format "%02d:%02d" hour minute)
15638 ;; Check if a time range is given as a duration
15639 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15640 (setq hour (string-to-number (match-string 1 ans))
15641 h2 (+ hour (string-to-number (match-string 3 ans)))
15642 minute (string-to-number (match-string 2 ans))
15643 m2 (+ minute (if (match-end 5) (string-to-number
15644 (match-string 5 ans))0)))
15645 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15646 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15649 ;; Check if there is a time range
15650 (when (boundp 'org-end-time-was-given)
15651 (setq org-time-was-given nil)
15652 (when (and (string-match org-plain-time-of-day-regexp ans)
15654 (setq org-end-time-was-given (match-string 8 ans))
15655 (setq ans (concat (substring ans 0 (match-beginning 7))
15656 (substring ans (match-end 7))))))
15658 (setq tl (parse-time-string ans)
15659 day (or (nth 3 tl) (nth 3 org-defdecode))
15660 month (or (nth 4 tl)
15661 (if (and org-read-date-prefer-future
15662 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15663 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15664 (nth 4 org-defdecode)))
15665 year (or (and (not kill-year) (nth 5 tl))
15666 (if (and org-read-date-prefer-future
15667 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15668 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15669 (nth 5 org-defdecode)))
15670 hour (or (nth 2 tl) (nth 2 org-defdecode))
15671 minute (or (nth 1 tl) (nth 1 org-defdecode))
15672 second (or (nth 0 tl) 0)
15675 (when (and (eq org-read-date-prefer-future 'time)
15676 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15677 (equal day (nth 3 nowdecode))
15678 (equal month (nth 4 nowdecode))
15679 (equal year (nth 5 nowdecode))
15681 (or (< (nth 2 tl) (nth 2 nowdecode))
15682 (and (= (nth 2 tl) (nth 2 nowdecode))
15684 (< (nth 1 tl) (nth 1 nowdecode)))))
15688 ;; Special date definitions below
15691 ;; There was an iso week
15694 (setq year (or iso-year year)
15695 day (or iso-weekday wday 1)
15696 wday nil ; to make sure that the trigger below does not match
15697 iso-date (calendar-gregorian-from-absolute
15698 (calendar-absolute-from-iso
15699 (list iso-week day year))))
15700 ; FIXME: Should we also push ISO weeks into the future?
15701 ; (when (and org-read-date-prefer-future
15703 ; (< (calendar-absolute-from-gregorian iso-date)
15704 ; (time-to-days (current-time))))
15705 ; (setq year (1+ year)
15706 ; iso-date (calendar-gregorian-from-absolute
15707 ; (calendar-absolute-from-iso
15708 ; (list iso-week day year)))))
15709 (setq month (car iso-date)
15710 year (nth 2 iso-date)
15711 day (nth 1 iso-date)))
15715 (let ((now (decode-time (current-time))))
15716 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15717 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15718 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15719 ((equal deltaw "m") (setq month (+ month deltan)))
15720 ((equal deltaw "y") (setq year (+ year deltan)))))
15721 ((and wday (not (nth 3 tl)))
15722 ;; Weekday was given, but no day, so pick that day in the week
15723 ;; on or after the derived date.
15724 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15725 (unless (equal wday wday1)
15726 (setq day (+ day (% (- wday wday1 -7) 7))))))
15727 (if (and (boundp 'org-time-was-given)
15729 (setq org-time-was-given t))
15730 (if (< year 100) (setq year (+ 2000 year)))
15731 ;; Check of the date is representable
15732 (if org-read-date-force-compatible-dates
15735 (setq year 1970 org-read-date-analyze-forced-year t))
15737 (setq year 2037 org-read-date-analyze-forced-year t)))
15738 (condition-case nil
15739 (ignore (encode-time second minute hour day month year))
15741 (setq year (nth 5 org-defdecode))
15742 (setq org-read-date-analyze-forced-year t))))
15743 (setq org-read-date-analyze-futurep futurep)
15744 (list second minute hour day month year)))
15746 (defvar parse-time-weekdays)
15747 (defun org-read-date-get-relative (s today default)
15748 "Check string S for special relative date string.
15749 TODAY and DEFAULT are internal times, for today and for a default.
15750 Return shift list (N what def-flag)
15751 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15752 N is the number of WHATs to shift.
15753 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15754 the DEFAULT date rather than TODAY."
15755 (require 'parse-time)
15759 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15761 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15762 "\\([ \t]\\|$\\)") s)
15763 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15764 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15765 (string-to-char (substring (match-string 1 s) -1))
15767 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15768 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15769 (what (if (match-end 3) (match-string 3 s) "d"))
15770 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15771 (date (if rel default today))
15772 (wday (nth 6 (decode-time date)))
15776 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15777 (if (= dir ?-) (setq delta (- delta 7)))
15778 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15779 (list delta "d" rel))
15780 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15782 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15783 "Turn a user-specified date into the internal representation.
15784 The internal representation needed by the calendar is (month day year).
15785 This is a wrapper to handle the brain-dead convention in calendar that
15786 user function argument order change dependent on argument order."
15787 (if (boundp 'calendar-date-style)
15789 ((eq calendar-date-style 'american)
15790 (list arg1 arg2 arg3))
15791 ((eq calendar-date-style 'european)
15792 (list arg2 arg1 arg3))
15793 ((eq calendar-date-style 'iso)
15794 (list arg2 arg3 arg1)))
15795 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15796 (if (org-bound-and-true-p european-calendar-style)
15797 (list arg2 arg1 arg3)
15798 (list arg1 arg2 arg3)))))
15800 (defun org-eval-in-calendar (form &optional keepdate)
15801 "Eval FORM in the calendar window and return to current window.
15802 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15803 otherwise stick to the current value of `org-ans2'."
15804 (let ((sf (selected-frame))
15805 (sw (selected-window)))
15806 (select-window (get-buffer-window "*Calendar*" t))
15808 (when (and (not keepdate) (calendar-cursor-to-date))
15809 (let* ((date (calendar-cursor-to-date))
15810 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15811 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15812 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15814 (org-select-frame-set-input-focus sf)))
15816 (defun org-calendar-select ()
15817 "Return to `org-read-date' with the date currently selected.
15818 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15820 (when (calendar-cursor-to-date)
15821 (let* ((date (calendar-cursor-to-date))
15822 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15823 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15824 (if (active-minibuffer-window) (exit-minibuffer))))
15826 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15827 "Insert a date stamp for the date given by the internal TIME.
15828 WITH-HM means use the stamp format that includes the time of the day.
15829 INACTIVE means use square brackets instead of angular ones, so that the
15830 stamp will not contribute to the agenda.
15831 PRE and POST are optional strings to be inserted before and after the
15833 The command returns the inserted time stamp."
15834 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15836 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15837 (insert-before-markers (or pre ""))
15838 (when (listp extra)
15839 (setq extra (car extra))
15840 (if (and (stringp extra)
15841 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15842 (setq extra (format "-%02d:%02d"
15843 (string-to-number (match-string 1 extra))
15844 (string-to-number (match-string 2 extra))))
15847 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15848 (insert-before-markers (setq stamp (format-time-string fmt time)))
15849 (insert-before-markers (or post ""))
15850 (setq org-last-inserted-timestamp stamp)))
15852 (defun org-toggle-time-stamp-overlays ()
15853 "Toggle the use of custom time stamp formats."
15855 (setq org-display-custom-times (not org-display-custom-times))
15856 (unless org-display-custom-times
15857 (let ((p (point-min)) (bmp (buffer-modified-p)))
15858 (while (setq p (next-single-property-change p 'display))
15859 (if (and (get-text-property p 'display)
15860 (eq (get-text-property p 'face) 'org-date))
15861 (remove-text-properties
15862 p (setq p (next-single-property-change p 'display))
15864 (set-buffer-modified-p bmp)))
15865 (if (featurep 'xemacs)
15866 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15867 (org-restart-font-lock)
15868 (setq org-table-may-need-update t)
15869 (if org-display-custom-times
15870 (message "Time stamps are overlaid with custom format")
15871 (message "Time stamp overlays removed")))
15873 (defun org-display-custom-time (beg end)
15874 "Overlay modified time stamp format over timestamp between BEG and END."
15875 (let* ((ts (buffer-substring beg end))
15876 t1 w1 with-hm tf time str w2 (off 0))
15878 (setq t1 (org-parse-time-string ts t))
15879 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15880 (setq off (- (match-end 0) (match-beginning 0)))))
15881 (setq end (- end off))
15882 (setq w1 (- end beg)
15883 with-hm (and (nth 1 t1) (nth 2 t1))
15884 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15885 time (org-fix-decoded-time t1)
15887 (format-time-string
15888 (substring tf 1 -1) (apply 'encode-time time))
15889 nil 'mouse-face 'highlight)
15891 (if (not (= w2 w1))
15892 (add-text-properties (1+ beg) (+ 2 beg)
15893 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15894 (if (featurep 'xemacs)
15896 (put-text-property beg end 'invisible t)
15897 (put-text-property beg end 'end-glyph (make-glyph str)))
15898 (put-text-property beg end 'display str))))
15900 (defun org-translate-time (string)
15901 "Translate all timestamps in STRING to custom format.
15902 But do this only if the variable `org-display-custom-times' is set."
15903 (when org-display-custom-times
15906 (re org-ts-regexp-both)
15907 t1 with-hm inactive tf time str beg end)
15908 (while (setq start (string-match re string start))
15909 (setq beg (match-beginning 0)
15911 t1 (save-match-data
15912 (org-parse-time-string (substring string beg end) t))
15913 with-hm (and (nth 1 t1) (nth 2 t1))
15914 inactive (equal (substring string beg (1+ beg)) "[")
15915 tf (funcall (if with-hm 'cdr 'car)
15916 org-time-stamp-custom-formats)
15917 time (org-fix-decoded-time t1)
15918 str (format-time-string
15920 (if inactive "[" "<") (substring tf 1 -1)
15921 (if inactive "]" ">"))
15922 (apply 'encode-time time))
15923 string (replace-match str t t string)
15924 start (+ start (length str)))))))
15927 (defun org-fix-decoded-time (time)
15928 "Set 0 instead of nil for the first 6 elements of time.
15929 Don't touch the rest."
15931 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15933 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
15935 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
15936 "Difference between TIMESTAMP-STRING and now in days.
15937 If SECONDS is non-nil, return the difference in seconds."
15938 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
15939 (- (funcall fdiff (org-time-string-to-time timestamp-string))
15940 (funcall fdiff (current-time)))))
15942 (defun org-deadline-close (timestamp-string &optional ndays)
15943 "Is the time in TIMESTAMP-STRING close to the current date?"
15944 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15945 (and (< (org-time-stamp-to-now timestamp-string) ndays)
15946 (not (org-entry-is-done-p))))
15948 (defun org-get-wdays (ts)
15949 "Get the deadline lead time appropriate for timestring TS."
15951 ((<= org-deadline-warning-days 0)
15952 ;; 0 or negative, enforce this value no matter what
15953 (- org-deadline-warning-days))
15954 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15955 ;; lead time is specified.
15956 (floor (* (string-to-number (match-string 1 ts))
15957 (cdr (assoc (match-string 2 ts)
15958 '(("d" . 1) ("w" . 7)
15959 ("m" . 30.4) ("y" . 365.25)))))))
15960 ;; go for the default.
15961 (t org-deadline-warning-days)))
15963 (defun org-calendar-select-mouse (ev)
15964 "Return to `org-read-date' with the date currently selected.
15965 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15967 (mouse-set-point ev)
15968 (when (calendar-cursor-to-date)
15969 (let* ((date (calendar-cursor-to-date))
15970 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15971 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15972 (if (active-minibuffer-window) (exit-minibuffer))))
15974 (defun org-check-deadlines (ndays)
15975 "Check if there are any deadlines due or past due.
15976 A deadline is considered due if it happens within `org-deadline-warning-days'
15977 days from today's date. If the deadline appears in an entry marked DONE,
15978 it is not shown. The prefix arg NDAYS can be used to test that many
15979 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15981 (let* ((org-warn-days
15983 ((equal ndays '(4)) 100000)
15984 (ndays (prefix-numeric-value ndays))
15985 (t (abs org-deadline-warning-days))))
15986 (case-fold-search nil)
15987 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15989 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15991 (message "%d deadlines past-due or due within %d days"
15992 (org-occur regexp nil callback)
15995 (defsubst org-re-timestamp (type)
15996 "Return a regexp for timestamp TYPE.
15997 Allowed values for TYPE are:
15999 all: all timestamps
16000 active: only active timestamps (<...>)
16001 inactive: only inactive timestamps ([...])
16002 scheduled: only scheduled timestamps
16003 deadline: only deadline timestamps
16005 When TYPE is nil, fall back on returning a regexp that matches
16006 both scheduled and deadline timestamps."
16007 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9>
\n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16008 ((eq type 'active) org-ts-regexp)
16009 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^
\n>]*?\\)\\]")
16010 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16011 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16012 ((eq type 'scheduled-or-deadline)
16013 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16015 (defun org-check-before-date (date)
16016 "Check if there are deadlines or scheduled entries before DATE."
16017 (interactive (list (org-read-date)))
16018 (let ((case-fold-search nil)
16019 (regexp (org-re-timestamp org-ts-type))
16021 (lambda () (time-less-p
16022 (org-time-string-to-time (match-string 1))
16023 (org-time-string-to-time date)))))
16024 (message "%d entries before %s"
16025 (org-occur regexp nil callback) date)))
16027 (defun org-check-after-date (date)
16028 "Check if there are deadlines or scheduled entries after DATE."
16029 (interactive (list (org-read-date)))
16030 (let ((case-fold-search nil)
16031 (regexp (org-re-timestamp org-ts-type))
16035 (org-time-string-to-time (match-string 1))
16036 (org-time-string-to-time date))))))
16037 (message "%d entries after %s"
16038 (org-occur regexp nil callback) date)))
16040 (defun org-check-dates-range (start-date end-date)
16041 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16042 (interactive (list (org-read-date nil nil nil "Range starts")
16043 (org-read-date nil nil nil "Range end")))
16044 (let ((case-fold-search nil)
16045 (regexp (org-re-timestamp org-ts-type))
16048 (let ((match (match-string 1)))
16051 (org-time-string-to-time match)
16052 (org-time-string-to-time start-date)))
16054 (org-time-string-to-time match)
16055 (org-time-string-to-time end-date)))))))
16056 (message "%d entries between %s and %s"
16057 (org-occur regexp nil callback) start-date end-date)))
16059 (defun org-evaluate-time-range (&optional to-buffer)
16060 "Evaluate a time range by computing the difference between start and end.
16061 Normally the result is just printed in the echo area, but with prefix arg
16062 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16063 If the time range is actually in a table, the result is inserted into the
16065 For time difference computation, a year is assumed to be exactly 365
16066 days in order to avoid rounding problems."
16069 (org-clock-update-time-maybe)
16071 (unless (org-at-date-range-p t)
16072 (goto-char (point-at-bol))
16073 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16074 (if (not (org-at-date-range-p t))
16075 (error "Not at a time-stamp range, and none found in current line")))
16076 (let* ((ts1 (match-string 1))
16077 (ts2 (match-string 2))
16078 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16079 (match-end (match-end 0))
16080 (time1 (org-time-string-to-time ts1))
16081 (time2 (org-time-string-to-time ts2))
16082 (t1 (org-float-time time1))
16083 (t2 (org-float-time time2))
16084 (diff (abs (- t2 t1)))
16085 (negative (< (- t2 t1) 0))
16086 ;; (ys (floor (* 365 24 60 60)))
16089 (fy "%dy %dd %02d:%02d")
16091 (fd "%dd %02d:%02d")
16096 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16098 d (floor (/ diff ds)) diff (mod diff ds)
16099 h (floor (/ diff hs)) diff (mod diff hs)
16100 m (floor (/ diff 60)))
16101 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16103 d (floor (+ (/ diff ds) 0.5))
16105 (if (not to-buffer)
16106 (message "%s" (org-make-tdiff-string y d h m))
16107 (if (org-at-table-p)
16109 (goto-char match-end)
16111 (and (looking-at " *|") (goto-char (match-end 0))))
16112 (goto-char match-end))
16114 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16115 (replace-match ""))
16116 (if negative (insert " -"))
16117 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16118 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16119 (insert " " (format fh h m))))
16120 (if align (org-table-align))
16121 (message "Time difference inserted")))))
16123 (defun org-make-tdiff-string (y d h m)
16126 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16128 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16130 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16132 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16134 (apply 'format fmt (nreverse l))))
16136 (defun org-time-string-to-time (s &optional buffer pos)
16137 "Convert a timestamp string into internal time."
16138 (condition-case errdata
16139 (apply 'encode-time (org-parse-time-string s))
16140 (error (error "Bad timestamp `%s'%s\nError was: %s"
16141 s (if (not (and buffer pos))
16143 (format " at %d in buffer `%s'" pos buffer))
16146 (defun org-time-string-to-seconds (s)
16147 "Convert a timestamp string to a number of seconds."
16148 (org-float-time (org-time-string-to-time s)))
16150 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16151 "Convert a time stamp to an absolute day number.
16152 If there is a specifier for a cyclic time stamp, get the closest date to
16154 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16155 The variable date is bound by the calendar when this is called."
16157 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16158 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16161 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16162 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16163 (time-to-days (current-time))) (match-string 0 s)
16166 (condition-case errdata
16167 (apply 'encode-time (org-parse-time-string s))
16168 (error (error "Bad timestamp `%s'%s\nError was: %s"
16169 s (if (not (and buffer pos))
16171 (format " at %d in buffer `%s'" pos buffer))
16172 (cdr errdata))))))))
16174 (defun org-days-to-iso-week (days)
16175 "Return the iso week number."
16177 (car (calendar-iso-from-absolute days)))
16179 (defun org-small-year-to-year (year)
16180 "Convert 2-digit years into 4-digit years.
16181 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16182 The year 2000 cannot be abbreviated. Any year larger than 99
16183 is returned unchanged."
16185 (setq year (+ 2000 year))
16187 (setq year (+ 1900 year))))
16190 (defun org-time-from-absolute (d)
16191 "Return the time corresponding to date D.
16192 D may be an absolute day number, or a calendar-type list (month day year)."
16193 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16194 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16196 (defun org-calendar-holiday ()
16197 "List of holidays, for Diary display in Org-mode."
16198 (require 'holidays)
16200 (if (fboundp 'calendar-check-holidays)
16201 'calendar-check-holidays 'check-calendar-holidays) date)))
16202 (if hl (mapconcat 'identity hl "; "))))
16204 (defun org-diary-sexp-entry (sexp entry date)
16205 "Process a SEXP diary ENTRY for DATE."
16206 (require 'diary-lib)
16207 (let ((result (if calendar-debug-sexp
16208 (let ((stack-trace-on-error t))
16209 (eval (car (read-from-string sexp))))
16210 (condition-case nil
16211 (eval (car (read-from-string sexp)))
16214 (message "Bad sexp at line %d in %s: %s"
16216 (buffer-file-name) sexp)
16218 (cond ((stringp result) (split-string result "; "))
16219 ((and (consp result)
16220 (not (consp (cdr result)))
16221 (stringp (cdr result))) (cdr result))
16222 ((and (consp result)
16223 (stringp (car result))) result)
16226 (defun org-diary-to-ical-string (frombuf)
16227 "Get iCalendar entries from diary entries in buffer FROMBUF.
16228 This uses the icalendar.el library."
16229 (let* ((tmpdir (if (featurep 'xemacs)
16231 temporary-file-directory))
16232 (tmpfile (make-temp-name
16233 (expand-file-name "orgics" tmpdir)))
16235 (with-current-buffer frombuf
16236 (icalendar-export-region (point-min) (point-max) tmpfile)
16237 (setq buf (find-buffer-visiting tmpfile))
16239 (goto-char (point-min))
16240 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16241 (setq b (match-beginning 0)))
16242 (goto-char (point-max))
16243 (if (re-search-backward "^END:VEVENT" nil t)
16244 (setq e (match-end 0)))
16245 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16247 (delete-file tmpfile)
16250 (defun org-closest-date (start current change prefer show-all)
16251 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16252 When PREFER is `past', return a date that is either CURRENT or past.
16253 When PREFER is `future', return a date that is either CURRENT or future.
16254 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16255 ;; Make the proper lists from the dates
16257 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16258 dn dw sday cday n1 n2 n0
16259 d m y y1 y2 date1 date2 nmonths nm ny m2)
16261 (setq start (org-date-to-gregorian start)
16262 current (org-date-to-gregorian
16265 (time-to-days (current-time))))
16266 sday (calendar-absolute-from-gregorian start)
16267 cday (calendar-absolute-from-gregorian current))
16269 (if (<= cday sday) (throw 'exit sday))
16271 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16272 (setq dn (string-to-number (match-string 1 change))
16273 dw (cdr (assoc (match-string 2 change) a1)))
16274 (error "Invalid change specifier: %s" change))
16275 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16278 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16281 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16282 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16283 (setq date1 (list m d y1)
16284 n1 (calendar-absolute-from-gregorian date1)
16285 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16286 n2 (calendar-absolute-from-gregorian date2)))
16288 ;; approx number of month between the two dates
16289 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16290 ;; How often does dn fit in there?
16291 (setq d (nth 1 start) m (car start) y (nth 2 start)
16292 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16294 ny (floor (/ m 12))
16297 (while (> m 12) (setq m (- m 12) y (1+ y)))
16298 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16299 (setq m2 (+ m dn) y2 y)
16300 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16301 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16302 (while (<= n2 cday)
16303 (setq n1 n2 m m2 y y2)
16304 (setq m2 (+ m dn) y2 y)
16305 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16306 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16307 ;; Make sure n1 is the earlier date
16308 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16311 ((eq prefer 'past) (if (= cday n2) n2 n1))
16312 ((eq prefer 'future) (if (= cday n1) n1 n2))
16313 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16315 ((eq prefer 'past) (if (= cday n2) n2 n1))
16316 ((eq prefer 'future) (if (= cday n1) n1 n2))
16317 (t (if (= cday n1) n1 n2)))))))
16319 (defun org-date-to-gregorian (date)
16320 "Turn any specification of DATE into a Gregorian date for the calendar."
16321 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16322 ((and (listp date) (= (length date) 3)) date)
16324 (setq date (org-parse-time-string date))
16325 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16327 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16329 (defun org-parse-time-string (s &optional nodefault)
16330 "Parse the standard Org-mode time string.
16331 This should be a lot faster than the normal `parse-time-string'.
16332 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16333 hour and minute fields will be nil if not given."
16334 (if (string-match org-ts-regexp0 s)
16336 (if (or (match-beginning 8) (not nodefault))
16337 (string-to-number (or (match-string 8 s) "0")))
16338 (if (or (match-beginning 7) (not nodefault))
16339 (string-to-number (or (match-string 7 s) "0")))
16340 (string-to-number (match-string 4 s))
16341 (string-to-number (match-string 3 s))
16342 (string-to-number (match-string 2 s))
16344 (error "Not a standard Org-mode time string: %s" s)))
16346 (defun org-timestamp-up (&optional arg)
16347 "Increase the date item at the cursor by one.
16348 If the cursor is on the year, change the year. If it is on the month,
16349 the day or the time, change that.
16350 With prefix ARG, change by that many units."
16352 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16354 (defun org-timestamp-down (&optional arg)
16355 "Decrease the date item at the cursor by one.
16356 If the cursor is on the year, change the year. If it is on the month,
16357 the day or the time, change that.
16358 With prefix ARG, change by that many units."
16360 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16362 (defun org-timestamp-up-day (&optional arg)
16363 "Increase the date in the time stamp by one day.
16364 With prefix ARG, change that many days."
16366 (if (and (not (org-at-timestamp-p t))
16367 (org-at-heading-p))
16369 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16371 (defun org-timestamp-down-day (&optional arg)
16372 "Decrease the date in the time stamp by one day.
16373 With prefix ARG, change that many days."
16375 (if (and (not (org-at-timestamp-p t))
16376 (org-at-heading-p))
16378 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16380 (defun org-at-timestamp-p (&optional inactive-ok)
16381 "Determine if the cursor is in or at a timestamp."
16383 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16385 (ans (or (looking-at tsr)
16387 (skip-chars-backward "^[<\n\r\t")
16388 (if (> (point) (point-min)) (backward-char 1))
16389 (and (looking-at tsr)
16390 (> (- (match-end 0) pos) -1))))))
16392 (boundp 'org-ts-what)
16395 ((= pos (match-beginning 0)) 'bracket)
16396 ;; Point is considered to be "on the bracket" whether
16397 ;; it's really on it or right after it.
16398 ((= pos (1- (match-end 0))) 'bracket)
16399 ((= pos (match-end 0)) 'after)
16400 ((org-pos-in-match-range pos 2) 'year)
16401 ((org-pos-in-match-range pos 3) 'month)
16402 ((org-pos-in-match-range pos 7) 'hour)
16403 ((org-pos-in-match-range pos 8) 'minute)
16404 ((or (org-pos-in-match-range pos 4)
16405 (org-pos-in-match-range pos 5)) 'day)
16406 ((and (> pos (or (match-end 8) (match-end 5)))
16407 (< pos (match-end 0)))
16408 (- pos (or (match-end 8) (match-end 5))))
16412 (defun org-toggle-timestamp-type ()
16413 "Toggle the type (<active> or [inactive]) of a time stamp."
16415 (when (org-at-timestamp-p t)
16416 (let ((beg (match-beginning 0)) (end (match-end 0))
16417 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16420 (while (re-search-forward "[][<>]" end t)
16421 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16423 (message "Timestamp is now %sactive"
16424 (if (equal (char-after beg) ?<) "" "in")))))
16426 (defvar org-clock-history) ; defined in org-clock.el
16427 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16428 (defun org-timestamp-change (n &optional what updown)
16429 "Change the date in the time stamp at point.
16430 The date will be changed by N times WHAT. WHAT can be `day', `month',
16431 `year', `minute', `second'. If WHAT is not given, the cursor position
16432 in the timestamp determines what will be changed."
16433 (let ((origin (point)) origin-cat
16435 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16438 ts time time0 fixnext clrgx)
16439 (if (not (org-at-timestamp-p t))
16440 (error "Not at a timestamp"))
16441 (if (and (not what) (eq org-ts-what 'bracket))
16442 (org-toggle-timestamp-type)
16443 ;; Point isn't on brackets. Remember the part of the time-stamp
16444 ;; the point was in. Indeed, size of time-stamps may change,
16445 ;; but point must be kept in the same category nonetheless.
16446 (setq origin-cat org-ts-what)
16447 (if (and (not what) (not (eq org-ts-what 'day))
16448 org-display-custom-times
16449 (get-text-property (point) 'display)
16450 (not (get-text-property (1- (point)) 'display)))
16451 (setq org-ts-what 'day))
16452 (setq org-ts-what (or what org-ts-what)
16453 inactive (= (char-after (match-beginning 0)) ?\[)
16454 ts (match-string 0))
16457 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16459 (setq extra (match-string 1 ts)))
16460 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16462 (setq time0 (org-parse-time-string ts))
16464 (eq org-ts-what 'minute)
16465 (not current-prefix-arg))
16466 ;; This looks like s-up and s-down. Change by one rounding step.
16467 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16468 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16469 (setcar (cdr time0) (+ (nth 1 time0)
16470 (if (> n 0) (- rem) (- dm rem))))))
16472 (encode-time (or (car time0) 0)
16473 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16474 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16475 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16476 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16477 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16479 (when (and (member org-ts-what '(hour minute))
16481 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16482 (setq extra (org-modify-ts-extra
16484 (if (eq org-ts-what 'hour) 2 5)
16486 (when (integerp org-ts-what)
16487 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16488 (if (eq what 'calendar)
16489 (let ((cal-date (org-get-date-from-calendar)))
16490 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16491 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16492 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16493 (setcar time0 (or (car time0) 0))
16494 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16495 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16496 (setq time (apply 'encode-time time0))))
16497 ;; Insert the new time-stamp, and ensure point stays in the same
16498 ;; category as before (i.e. not after the last position in that
16500 (let ((pos (point)))
16501 ;; Stay before inserted string. `save-excursion' is of no use.
16502 (setq org-last-changed-timestamp
16503 (org-insert-time-stamp time with-hm inactive nil nil extra))
16506 (looking-at org-ts-regexp3)
16508 ;; `day' category ends before `hour' if any, or at
16509 ;; the end of the day name.
16510 ((eq origin-cat 'day)
16511 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16512 ((eq origin-cat 'hour) (min (match-end 7) origin))
16513 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16514 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16515 ;; `year' and `month' have both fixed size: point
16516 ;; couldn't have moved into another part.
16518 ;; Update clock if on a CLOCK line.
16519 (org-clock-update-time-maybe)
16520 ;; Maybe adjust the closest clock in `org-clock-history'
16521 (when org-clock-adjust-closest
16522 (if (not (and (org-at-clock-log-p)
16523 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16524 org-clock-history))))))
16525 (message "No clock to adjust")
16526 (cond ((save-excursion ; fix previous clock?
16527 (re-search-backward org-ts-regexp0 nil t)
16528 (org-looking-back (concat org-clock-string " \\[")))
16529 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16530 ((save-excursion ; fix next clock?
16531 (re-search-backward org-ts-regexp0 nil t)
16532 (looking-at (concat org-ts-regexp0 "\\] =>")))
16533 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16534 (save-window-excursion
16535 ;; Find closest clock to point, adjust the previous/next one in history
16536 (let* ((p (save-excursion (org-back-to-heading t)))
16537 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16539 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16540 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16542 (message "No clock to adjust")
16544 (org-goto-marker-or-bmk clfixpos)
16546 (when (re-search-forward clrgx nil t)
16547 (goto-char (match-beginning 1))
16548 (let (org-clock-adjust-closest)
16549 (org-timestamp-change n org-ts-what updown))
16550 (message "Clock adjusted in %s for heading: %s"
16551 (file-name-nondirectory (buffer-file-name))
16552 (org-get-heading t t)))))))))
16553 ;; Try to recenter the calendar window, if any.
16554 (if (and org-calendar-follow-timestamp-change
16555 (get-buffer-window "*Calendar*" t)
16556 (memq org-ts-what '(day month year)))
16557 (org-recenter-calendar (time-to-days time))))))
16559 (defun org-modify-ts-extra (s pos n dm)
16560 "Change the different parts of the lead-time and repeat fields in timestamp."
16561 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16563 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16565 ((or (org-pos-in-match-range pos 2)
16566 (org-pos-in-match-range pos 3))
16567 (setq m (string-to-number (match-string 3 s))
16568 h (string-to-number (match-string 2 s)))
16569 (if (org-pos-in-match-range pos 2)
16571 (setq n (* dm (org-no-warnings (signum n))))
16572 (when (not (= 0 (setq rem (% m dm))))
16573 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16575 (if (< m 0) (setq m (+ m 60) h (1- h)))
16576 (if (> m 59) (setq m (- m 60) h (1+ h)))
16577 (setq h (min 24 (max 0 h)))
16578 (setq ng 1 new (format "-%02d:%02d" h m)))
16579 ((org-pos-in-match-range pos 6)
16580 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16581 ((org-pos-in-match-range pos 5)
16582 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16584 ((org-pos-in-match-range pos 9)
16585 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16586 ((org-pos-in-match-range pos 8)
16587 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16591 (substring s 0 (match-beginning ng))
16593 (substring s (match-end ng))))))
16596 (defun org-recenter-calendar (date)
16597 "If the calendar is visible, recenter it to DATE."
16598 (let ((cwin (get-buffer-window "*Calendar*" t)))
16600 (let ((calendar-move-hook nil))
16601 (with-selected-window cwin
16602 (calendar-goto-date (if (listp date) date
16603 (calendar-gregorian-from-absolute date))))))))
16605 (defun org-goto-calendar (&optional arg)
16606 "Go to the Emacs calendar at the current date.
16607 If there is a time stamp in the current line, go to that date.
16608 A prefix ARG can be used to force the current date."
16610 (let ((tsr org-ts-regexp) diff
16611 (calendar-move-hook nil)
16612 (calendar-view-holidays-initially-flag nil)
16613 (calendar-view-diary-initially-flag nil))
16614 (if (or (org-at-timestamp-p)
16616 (beginning-of-line 1)
16617 (looking-at (concat ".*" tsr))))
16618 (let ((d1 (time-to-days (current-time)))
16620 (org-time-string-to-time (match-string 1)))))
16621 (setq diff (- d2 d1))))
16623 (calendar-goto-today)
16624 (if (and diff (not arg)) (calendar-forward-day diff))))
16626 (defun org-get-date-from-calendar ()
16627 "Return a list (month day year) of date at point in calendar."
16628 (with-current-buffer "*Calendar*"
16630 (calendar-cursor-to-date))))
16632 (defun org-date-from-calendar ()
16633 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16634 If there is already a time stamp at the cursor position, update it."
16636 (if (org-at-timestamp-p t)
16637 (org-timestamp-change 0 'calendar)
16638 (let ((cal-date (org-get-date-from-calendar)))
16639 (org-insert-time-stamp
16640 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16642 (defun org-minutes-to-hh:mm-string (m)
16643 "Compute H:MM from a number of minutes."
16644 (let ((h (/ m 60)))
16645 (setq m (- m (* 60 h)))
16646 (format org-time-clocksum-format h m)))
16648 (defun org-hh:mm-string-to-minutes (s)
16649 "Convert a string H:MM to a number of minutes.
16650 If the string is just a number, interpret it as minutes.
16651 In fact, the first hh:mm or number in the string will be taken,
16652 there can be extra stuff in the string.
16653 If no number is found, the return value is 0."
16656 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16657 (+ (* (string-to-number (match-string 1 s)) 60)
16658 (string-to-number (match-string 2 s))))
16659 ((string-match "\\([0-9]+\\)" s)
16660 (string-to-number (match-string 1 s)))
16663 (defcustom org-effort-durations
16666 ("w" . ,(* 60 8 5))
16667 ("m" . ,(* 60 8 5 4))
16668 ("y" . ,(* 60 8 5 40)))
16669 "Conversion factor to minutes for an effort modifier.
16671 Each entry has the form (MODIFIER . MINUTES).
16673 In an effort string, a number followed by MODIFIER is multiplied
16674 by the specified number of MINUTES to obtain an effort in
16677 For example, if the value of this variable is ((\"hours\" . 60)), then an
16678 effort string \"2hours\" is equivalent to 120 minutes."
16681 :type '(alist :key-type (string :tag "Modifier")
16682 :value-type (number :tag "Minutes")))
16684 (defcustom org-image-actual-width t
16685 "Should we use the actual width of images when inlining them?
16687 When set to `t', always use the image width.
16689 When set to a number, use imagemagick (when available) to set
16690 the image's width to this value.
16692 When set to a number in a list, try to get the width from the
16693 #+ATTR.* keyword if it matches a width specification like
16694 width=\"[0-9]+\", and fall back on that number if none is found.
16696 When set to nil, try to get the width from an #+ATTR.* keyword
16697 and fall back on the original width if none is found.
16699 This requires Emacs >= 24.1, build with imagemagick support."
16700 :group 'org-appearance
16703 (const :tag "Use the image width" t)
16704 (integer :tag "Use a number of pixels")
16705 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16706 (const :tag "Use #+ATTR* or don't resize" nil)))
16708 (defun org-duration-string-to-minutes (s &optional output-to-string)
16709 "Convert a duration string S to minutes.
16711 A bare number is interpreted as minutes, modifiers can be set by
16712 customizing `org-effort-durations' (which see).
16714 Entries containing a colon are interpreted as H:MM by
16715 `org-hh:mm-string-to-minutes'."
16717 (re (concat "\\([0-9.]+\\) *\\("
16718 (regexp-opt (mapcar 'car org-effort-durations))
16720 (while (string-match re s)
16721 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16722 (string-to-number (match-string 1 s))))
16723 (setq s (replace-match "" nil t s)))
16724 (setq result (floor result))
16725 (incf result (org-hh:mm-string-to-minutes s))
16726 (if output-to-string (number-to-string result) result)))
16730 (defun org-save-all-org-buffers ()
16731 "Save all Org-mode buffers without user confirmation."
16733 (message "Saving all Org-mode buffers...")
16734 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16735 (when (featurep 'org-id) (org-id-locations-save))
16736 (message "Saving all Org-mode buffers... done"))
16738 (defun org-revert-all-org-buffers ()
16739 "Revert all Org-mode buffers.
16740 Prompt for confirmation when there are unsaved changes.
16741 Be sure you know what you are doing before letting this function
16742 overwrite your changes.
16744 This function is useful in a setup where one tracks org files
16745 with a version control system, to revert on one machine after pulling
16746 changes from another. I believe the procedure must be like this:
16748 1. M-x org-save-all-org-buffers
16749 2. Pull changes from the other machine, resolve conflicts
16750 3. M-x org-revert-all-org-buffers"
16752 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16755 (save-window-excursion
16758 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16759 (with-current-buffer b buffer-file-name))
16760 (org-pop-to-buffer-same-window b)
16761 (revert-buffer t 'no-confirm)))
16763 (when (and (featurep 'org-id) org-id-track-globally)
16764 (org-id-locations-load)))))
16769 (defun org-switchb (&optional arg)
16770 "Switch between Org buffers.
16771 With one prefix argument, restrict available buffers to files.
16772 With two prefix arguments, restrict available buffers to agenda files.
16774 Defaults to `iswitchb' for buffer name completion.
16775 Set `org-completion-use-ido' to make it use ido instead."
16777 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16778 ((equal arg '(16)) (org-buffer-list 'agenda))
16779 (t (org-buffer-list))))
16780 (org-completion-use-iswitchb org-completion-use-iswitchb)
16781 (org-completion-use-ido org-completion-use-ido))
16782 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16783 (setq org-completion-use-iswitchb t))
16784 (org-pop-to-buffer-same-window
16785 (org-icompleting-read "Org buffer: "
16786 (mapcar 'list (mapcar 'buffer-name blist))
16789 ;;; Define some older names previously used for this functionality
16791 (defalias 'org-ido-switchb 'org-switchb)
16793 (defalias 'org-iswitchb 'org-switchb)
16795 (defun org-buffer-list (&optional predicate exclude-tmp)
16796 "Return a list of Org buffers.
16797 PREDICATE can be `export', `files' or `agenda'.
16799 export restrict the list to Export buffers.
16800 files restrict the list to buffers visiting Org files.
16801 agenda restrict the list to buffers visiting agenda files.
16803 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16805 (agenda-files (and (eq predicate 'agenda)
16806 (mapcar 'file-truename (org-agenda-files t))))
16809 ((eq predicate 'files)
16810 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16811 ((eq predicate 'export)
16812 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16813 ((eq predicate 'agenda)
16815 (with-current-buffer b
16816 (and (derived-mode-p 'org-mode)
16817 (setq bfn (buffer-file-name b))
16818 (member (file-truename bfn) agenda-files)))))
16819 (t (lambda (b) (with-current-buffer b
16820 (or (derived-mode-p 'org-mode)
16821 (string-match "\*Org .*Export"
16822 (buffer-name b)))))))))
16826 (if (and (funcall filter b)
16827 (or (not exclude-tmp)
16828 (not (string-match "tmp" (buffer-name b)))))
16833 (defun org-agenda-files (&optional unrestricted archives)
16834 "Get the list of agenda files.
16835 Optional UNRESTRICTED means return the full list even if a restriction
16836 is currently in place.
16837 When ARCHIVES is t, include all archive files that are really being
16838 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16839 `org-agenda-archives-mode' is t."
16842 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16843 ((stringp org-agenda-files) (org-read-agenda-file-list))
16844 ((listp org-agenda-files) org-agenda-files)
16845 (t (error "Invalid value of `org-agenda-files'")))))
16846 (setq files (apply 'append
16847 (mapcar (lambda (f)
16848 (if (file-directory-p f)
16850 f t org-agenda-file-regexp)
16853 (when org-agenda-skip-unavailable-files
16854 (setq files (delq nil
16857 (and (file-readable-p file) file)))
16859 (when (or (eq archives t)
16860 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16861 (setq files (org-add-archive-files files)))
16864 (defun org-agenda-file-p (&optional file)
16865 "Return non-nil, if FILE is an agenda file.
16866 If FILE is omitted, use the file associated with the current
16868 (member (or file (buffer-file-name))
16869 (org-agenda-files t)))
16871 (defun org-edit-agenda-file-list ()
16872 "Edit the list of agenda files.
16873 Depending on setup, this either uses customize to edit the variable
16874 `org-agenda-files', or it visits the file that is holding the list. In the
16875 latter case, the buffer is set up in a way that saving it automatically kills
16876 the buffer and restores the previous window configuration."
16878 (if (stringp org-agenda-files)
16879 (let ((cw (current-window-configuration)))
16880 (find-file org-agenda-files)
16881 (org-set-local 'org-window-configuration cw)
16882 (org-add-hook 'after-save-hook
16884 (set-window-configuration
16885 (prog1 org-window-configuration
16886 (kill-buffer (current-buffer))))
16887 (org-install-agenda-files-menu)
16888 (message "New agenda file list installed"))
16890 (message "%s" (substitute-command-keys
16891 "Edit list and finish with \\[save-buffer]")))
16892 (customize-variable 'org-agenda-files)))
16894 (defun org-store-new-agenda-file-list (list)
16895 "Set new value for the agenda file list and save it correctly."
16896 (if (stringp org-agenda-files)
16897 (let ((fe (org-read-agenda-file-list t)) b u)
16898 (while (setq b (find-buffer-visiting org-agenda-files))
16900 (with-temp-file org-agenda-files
16903 (lambda (f) ;; Keep un-expanded entries.
16904 (if (setq u (assoc f fe))
16909 (let ((org-mode-hook nil) (org-inhibit-startup t)
16910 (org-insert-mode-line-in-empty-file nil))
16911 (setq org-agenda-files list)
16912 (customize-save-variable 'org-agenda-files org-agenda-files))))
16914 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16915 "Read the list of agenda files from a file.
16916 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16917 filenames, used by `org-store-new-agenda-file-list' to write back
16918 un-expanded file names."
16919 (when (file-directory-p org-agenda-files)
16920 (error "`org-agenda-files' cannot be a single directory"))
16921 (when (stringp org-agenda-files)
16923 (insert-file-contents org-agenda-files)
16926 (let ((e (expand-file-name (substitute-in-file-name f)
16928 (if pair-with-expansion
16931 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16934 (defun org-cycle-agenda-files ()
16935 "Cycle through the files in `org-agenda-files'.
16936 If the current buffer visits an agenda file, find the next one in the list.
16937 If the current buffer does not, find the first agenda file."
16939 (let* ((fs (org-agenda-files t))
16940 (files (append fs (list (car fs))))
16941 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16943 (unless files (error "No agenda files"))
16945 (while (setq file (pop files))
16946 (if (equal (file-truename file) tcf)
16948 (find-file (car files))
16950 (find-file (car fs)))
16951 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16953 (defun org-agenda-file-to-front (&optional to-end)
16954 "Move/add the current file to the top of the agenda file list.
16955 If the file is not present in the list, it is added to the front. If it is
16956 present, it is moved there. With optional argument TO-END, add/move to the
16959 (let ((org-agenda-skip-unavailable-files nil)
16960 (file-alist (mapcar (lambda (x)
16961 (cons (file-truename x) x))
16962 (org-agenda-files t)))
16963 (ctf (file-truename buffer-file-name))
16965 (setq x (assoc ctf file-alist) had x)
16967 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16969 (setq file-alist (append (delq x file-alist) (list x)))
16970 (setq file-alist (cons x (delq x file-alist))))
16971 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16972 (org-install-agenda-files-menu)
16973 (message "File %s to %s of agenda file list"
16974 (if had "moved" "added") (if to-end "end" "front"))))
16976 (defun org-remove-file (&optional file)
16977 "Remove current file from the list of files in variable `org-agenda-files'.
16978 These are the files which are being checked for agenda entries.
16979 Optional argument FILE means use this file instead of the current."
16981 (let* ((org-agenda-skip-unavailable-files nil)
16982 (file (or file buffer-file-name))
16983 (true-file (file-truename file))
16984 (afile (abbreviate-file-name file))
16985 (files (delq nil (mapcar
16987 (if (equal true-file
16990 (org-agenda-files t)))))
16991 (if (not (= (length files) (length (org-agenda-files t))))
16993 (org-store-new-agenda-file-list files)
16994 (org-install-agenda-files-menu)
16995 (message "Removed file: %s" afile))
16996 (message "File was not in list: %s (not removed)" afile))))
16998 (defun org-file-menu-entry (file)
16999 (vector file (list 'find-file file) t))
17001 (defun org-check-agenda-file (file)
17002 "Make sure FILE exists. If not, ask user what to do."
17003 (when (not (file-exists-p file))
17004 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17005 (abbreviate-file-name file))
17006 (let ((r (downcase (read-char-exclusive))))
17009 (org-remove-file file)
17010 (throw 'nextfile t))
17011 (t (error "Abort"))))))
17013 (defun org-get-agenda-file-buffer (file)
17014 "Get a buffer visiting FILE. If the buffer needs to be created, add
17015 it to the list of buffers which might be released later."
17016 (let ((buf (org-find-base-buffer-visiting file)))
17018 buf ; just return it
17019 ;; Make a new buffer and remember it
17020 (setq buf (find-file-noselect file))
17021 (if buf (push buf org-agenda-new-buffers))
17024 (defun org-release-buffers (blist)
17025 "Release all buffers in list, asking the user for confirmation when needed.
17026 When a buffer is unmodified, it is just killed. When modified, it is saved
17027 \(if the user agrees) and then killed."
17029 (while (setq buf (pop blist))
17030 (setq file (buffer-file-name buf))
17031 (when (and (buffer-modified-p buf)
17033 (y-or-n-p (format "Save file %s? " file)))
17034 (with-current-buffer buf (save-buffer)))
17035 (kill-buffer buf))))
17037 (defun org-agenda-prepare-buffers (files)
17038 "Create buffers for all agenda files, protect archived trees and comments."
17040 (let ((pa '(:org-archived t))
17041 (pc '(:org-comment t))
17042 (pall '(:org-archived t :org-comment t))
17043 (inhibit-read-only t)
17044 (rea (concat ":" org-archive-tag ":"))
17048 (while (setq file (pop files))
17052 (org-check-agenda-file file)
17053 (set-buffer (org-get-agenda-file-buffer file)))
17055 (setq bmp (buffer-modified-p))
17056 (org-refresh-category-properties)
17057 (setq org-todo-keywords-for-agenda
17058 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17059 (setq org-done-keywords-for-agenda
17060 (append org-done-keywords-for-agenda org-done-keywords))
17061 (setq org-todo-keyword-alist-for-agenda
17062 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17063 (setq org-drawers-for-agenda
17064 (append org-drawers-for-agenda org-drawers))
17065 (setq org-tag-alist-for-agenda
17066 (append org-tag-alist-for-agenda org-tag-alist))
17069 (remove-text-properties (point-min) (point-max) pall)
17070 (when org-agenda-skip-archived-trees
17071 (goto-char (point-min))
17072 (while (re-search-forward rea nil t)
17073 (if (org-at-heading-p t)
17074 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17075 (goto-char (point-min))
17076 (setq re (format org-heading-keyword-regexp-format
17077 org-comment-string))
17078 (while (re-search-forward re nil t)
17079 (add-text-properties
17080 (match-beginning 0) (org-end-of-subtree t) pc)))
17081 (set-buffer-modified-p bmp)))))
17082 (setq org-todo-keywords-for-agenda
17083 (org-uniquify org-todo-keywords-for-agenda))
17084 (setq org-todo-keyword-alist-for-agenda
17085 (org-uniquify org-todo-keyword-alist-for-agenda)
17086 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17088 ;;;; Embedded LaTeX
17090 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17091 "Keymap for the minor `org-cdlatex-mode'.")
17093 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17094 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17095 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17096 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17097 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17099 (defvar org-cdlatex-texmathp-advice-is-done nil
17100 "Flag remembering if we have applied the advice to texmathp already.")
17102 (define-minor-mode org-cdlatex-mode
17103 "Toggle the minor `org-cdlatex-mode'.
17104 This mode supports entering LaTeX environment and math in LaTeX fragments
17106 \\{org-cdlatex-mode-map}"
17108 (when org-cdlatex-mode
17110 (run-hooks 'cdlatex-mode-hook)
17111 (cdlatex-compute-tables))
17112 (unless org-cdlatex-texmathp-advice-is-done
17113 (setq org-cdlatex-texmathp-advice-is-done t)
17114 (defadvice texmathp (around org-math-always-on activate)
17115 "Always return t in org-mode buffers.
17116 This is because we want to insert math symbols without dollars even outside
17117 the LaTeX math segments. If Orgmode thinks that point is actually inside
17118 an embedded LaTeX fragment, let texmathp do its job.
17119 \\[org-cdlatex-mode-map]"
17123 ((not (derived-mode-p 'org-mode)) ad-do-it)
17124 ((eq this-command 'cdlatex-math-symbol)
17125 (setq ad-return-value t
17126 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17128 (let ((p (org-inside-LaTeX-fragment-p)))
17129 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17130 (setq ad-return-value t
17131 texmathp-why '("Org-mode embedded math" . 0))
17132 (if p ad-do-it)))))))))
17134 (defun turn-on-org-cdlatex ()
17135 "Unconditionally turn on `org-cdlatex-mode'."
17136 (org-cdlatex-mode 1))
17138 (defun org-inside-LaTeX-fragment-p ()
17139 "Test if point is inside a LaTeX fragment.
17140 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17141 sequence appearing also before point.
17142 Even though the matchers for math are configurable, this function assumes
17143 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17144 delimiters are skipped when they have been removed by customization.
17145 The return value is nil, or a cons cell with the delimiter and the
17146 position of this delimiter.
17148 This function does a reasonably good job, but can locally be fooled by
17149 for example currency specifications. For example it will assume being in
17150 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17151 fragments that are properly closed, but during editing, we have to live
17152 with the uncertainty caused by missing closing delimiters. This function
17153 looks only before point, not after."
17155 (let ((pos (point))
17156 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17158 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17160 dd-on str (start 0) m re)
17163 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17164 re (nth 1 (assoc "$" org-latex-regexps)))
17165 (while (string-match re str start)
17167 ((= (match-end 0) (length str))
17168 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17169 ((= (match-end 0) (- (length str) 5))
17171 (t (setq start (match-end 0))))))
17172 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17174 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17175 (and (match-beginning 2) (throw 'exit nil))
17177 (while (re-search-backward "\\$\\$" lim t)
17178 (setq dd-on (not dd-on)))
17180 (if dd-on (cons "$$" m))))))
17182 (defun org-inside-latex-macro-p ()
17183 "Is point inside a LaTeX macro or its arguments?"
17186 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17188 (defun org-try-cdlatex-tab ()
17189 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17190 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17191 - inside a LaTeX fragment, or
17192 - after the first word in a line, where an abbreviation expansion could
17193 insert a LaTeX environment."
17194 (when org-cdlatex-mode
17196 ;; Before any word on the line: No expansion possible.
17197 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17198 ;; Just after first word on the line: Expand it. Make sure it
17199 ;; cannot happen on headlines, though.
17201 (skip-chars-backward "a-zA-Z0-9*")
17202 (skip-chars-backward " \t")
17203 (and (bolp) (not (org-at-heading-p))))
17205 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17207 (defun org-cdlatex-underscore-caret (&optional arg)
17208 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17209 Revert to the normal definition outside of these fragments."
17211 (if (org-inside-LaTeX-fragment-p)
17212 (call-interactively 'cdlatex-sub-superscript)
17213 (let (org-cdlatex-mode)
17214 (call-interactively (key-binding (vector last-input-event))))))
17216 (defun org-cdlatex-math-modify (&optional arg)
17217 "Execute `cdlatex-math-modify' in LaTeX fragments.
17218 Revert to the normal definition outside of these fragments."
17220 (if (org-inside-LaTeX-fragment-p)
17221 (call-interactively 'cdlatex-math-modify)
17222 (let (org-cdlatex-mode)
17223 (call-interactively (key-binding (vector last-input-event))))))
17225 (defvar org-latex-fragment-image-overlays nil
17226 "List of overlays carrying the images of latex fragments.")
17227 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17229 (defun org-remove-latex-fragment-image-overlays ()
17230 "Remove all overlays with LaTeX fragment images in current buffer."
17231 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17232 (setq org-latex-fragment-image-overlays nil))
17234 (defun org-preview-latex-fragment (&optional subtree)
17235 "Preview the LaTeX fragment at point, or all locally or globally.
17236 If the cursor is in a LaTeX fragment, create the image and overlay
17237 it over the source code. If there is no fragment at point, display
17238 all fragments in the current text, from one headline to the next. With
17239 prefix SUBTREE, display all fragments in the current subtree. With a
17240 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17241 the cursor is before the first headline,
17242 display all fragments in the buffer.
17243 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17245 (unless buffer-file-name
17246 (error "Can't preview LaTeX fragment in a non-file buffer"))
17247 (org-remove-latex-fragment-image-overlays)
17250 (let (beg end at msg)
17252 ((or (equal subtree '(16))
17253 (not (save-excursion
17254 (re-search-backward org-outline-regexp-bol nil t))))
17255 (setq beg (point-min) end (point-max)
17256 msg "Creating images for buffer...%s"))
17257 ((equal subtree '(4))
17258 (org-back-to-heading)
17259 (setq beg (point) end (org-end-of-subtree t)
17260 msg "Creating images for subtree...%s"))
17262 (if (setq at (org-inside-LaTeX-fragment-p))
17263 (goto-char (max (point-min) (- (cdr at) 2)))
17264 (org-back-to-heading))
17265 (setq beg (point) end (progn (outline-next-heading) (point))
17266 msg (if at "Creating image...%s"
17267 "Creating images for entry...%s"))))
17269 (narrow-to-region beg end)
17272 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17273 (file-name-nondirectory
17274 buffer-file-name)))
17275 default-directory 'overlays msg at 'forbuffer
17276 org-latex-create-formula-image-program)
17277 (message msg "done. Use `C-c C-c' to remove images.")))))
17279 (defvar org-latex-regexps
17280 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17281 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17282 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17283 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17284 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17285 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17286 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17287 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17288 "Regular expressions for matching embedded LaTeX.")
17290 (defvar org-export-have-math nil) ;; dynamic scoping
17291 (defun org-format-latex (prefix &optional dir overlays msg at
17292 forbuffer processing-type)
17293 "Replace LaTeX fragments with links to an image, and produce images.
17294 Some of the options can be changed using the variable
17295 `org-format-latex-options'."
17296 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17297 (let* ((prefixnodir (file-name-nondirectory prefix))
17298 (absprefix (expand-file-name prefix dir))
17299 (todir (file-name-directory absprefix))
17300 (opt org-format-latex-options)
17301 (optnew org-format-latex-options)
17302 (matchers (plist-get opt :matchers))
17303 (re-list org-latex-regexps)
17304 (org-format-latex-header-extra
17305 (plist-get (org-infile-export-plist) :latex-header-extra))
17306 (cnt 0) txt hash link beg end re e checkdir
17308 m n block-type block linkfile movefile ov)
17309 ;; Check the different regular expressions
17310 (while (setq e (pop re-list))
17311 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17312 block (if block-type "\n\n" ""))
17313 (when (member m matchers)
17314 (goto-char (point-min))
17315 (while (re-search-forward re nil t)
17316 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17317 (not (get-text-property (match-beginning n)
17320 (not (eq (get-char-property (match-beginning n)
17322 'org-latex-overlay))))
17323 (setq org-export-have-math t)
17325 ((eq processing-type 'verbatim)
17326 ;; Leave the text verbatim, just protect it
17327 (add-text-properties (match-beginning n) (match-end n)
17328 '(org-protected t)))
17329 ((eq processing-type 'mathjax)
17330 ;; Prepare for MathJax processing
17331 (setq string (match-string n))
17332 (if (member m '("$" "$1"))
17334 (delete-region (match-beginning n) (match-end n))
17335 (goto-char (match-beginning n))
17336 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17338 '(org-protected t))))
17339 (add-text-properties (match-beginning n) (match-end n)
17340 '(org-protected t))))
17341 ((or (eq processing-type 'dvipng)
17342 (eq processing-type 'imagemagick))
17343 ;; Process to an image
17344 (setq txt (match-string n)
17345 beg (match-beginning n) end (match-end n)
17347 (let ((face (face-at-point))
17348 (fg (plist-get opt :foreground))
17349 (bg (plist-get opt :background))
17350 print-length print-level) ; make sure full list is printed
17352 ; Get the colors from the face at point
17354 (when (eq fg 'auto)
17355 (setq fg (face-attribute face :foreground nil 'default)))
17356 (when (eq bg 'auto)
17357 (setq bg (face-attribute face :background nil 'default)))
17358 (setq optnew (copy-sequence opt))
17359 (plist-put optnew :foreground fg)
17360 (plist-put optnew :background bg))
17361 (setq hash (sha1 (prin1-to-string
17362 (list org-format-latex-header
17363 org-format-latex-header-extra
17364 org-export-latex-default-packages-alist
17365 org-export-latex-packages-alist
17366 org-format-latex-options
17367 forbuffer txt fg bg)))
17368 linkfile (format "%s_%s.png" prefix hash)
17369 movefile (format "%s_%s.png" absprefix hash)))
17370 (setq link (concat block "[[file:" linkfile "]]" block))
17371 (if msg (message msg cnt))
17373 (unless checkdir ; make sure the directory exists
17375 (or (file-directory-p todir) (make-directory todir t)))
17376 (org-create-formula-image
17377 txt movefile optnew forbuffer processing-type)
17381 (if (eq (overlay-get o 'org-overlay-type)
17382 'org-latex-overlay)
17383 (delete-overlay o)))
17384 (overlays-in beg end))
17385 (setq ov (make-overlay beg end))
17386 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17387 (if (featurep 'xemacs)
17389 (overlay-put ov 'invisible t)
17392 (make-glyph (vector 'png :file movefile))))
17395 (list 'image :type 'png :file movefile :ascent 'center)))
17396 (push ov org-latex-fragment-image-overlays)
17398 (delete-region beg end)
17399 (insert (org-add-props link
17400 (list 'org-latex-src
17401 (replace-regexp-in-string
17403 'org-latex-src-embed-type
17404 (if block-type 'paragraph 'character))))))
17405 ((eq processing-type 'mathml)
17406 ;; Process to MathML
17407 (unless (save-match-data (org-format-latex-mathml-available-p))
17408 (error "LaTeX to MathML converter not configured"))
17409 (setq txt (match-string n)
17410 beg (match-beginning n) end (match-end n)
17412 (if msg (message msg cnt))
17414 (delete-region beg end)
17415 (insert (org-format-latex-as-mathml
17416 txt block-type prefix dir)))
17418 (error "Unknown conversion type %s for latex fragments"
17419 processing-type)))))))))
17421 (defun org-create-math-formula (latex-frag &optional mathml-file)
17422 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17423 Use `org-latex-to-mathml-convert-command'. If the conversion is
17424 sucessful, return the portion between \"<math...> </math>\"
17425 elements otherwise return nil. When MATHML-FILE is specified,
17426 write the results in to that file. When invoked as an
17427 interactive command, prompt for LATEX-FRAG, with initial value
17428 set to the current active region and echo the results for user
17430 (interactive (list (let ((frag (when (org-region-active-p)
17431 (buffer-substring-no-properties
17432 (region-beginning) (region-end)))))
17433 (read-string "LaTeX Fragment: " frag nil frag))))
17434 (unless latex-frag (error "Invalid latex-frag"))
17435 (let* ((tmp-in-file (file-relative-name
17436 (make-temp-name (expand-file-name "ltxmathml-in"))))
17437 (ignore (write-region latex-frag nil tmp-in-file))
17438 (tmp-out-file (file-relative-name
17439 (make-temp-name (expand-file-name "ltxmathml-out"))))
17441 org-latex-to-mathml-convert-command
17442 `((?j . ,(shell-quote-argument
17443 (expand-file-name org-latex-to-mathml-jar-file)))
17444 (?I . ,(shell-quote-argument tmp-in-file))
17445 (?o . ,(shell-quote-argument tmp-out-file)))))
17446 mathml shell-command-output)
17447 (when (org-called-interactively-p 'any)
17448 (unless (org-format-latex-mathml-available-p)
17449 (error "LaTeX to MathML converter not configured")))
17450 (message "Running %s" cmd)
17451 (setq shell-command-output (shell-command-to-string cmd))
17453 (when (file-readable-p tmp-out-file)
17454 (with-current-buffer (find-file-noselect tmp-out-file t)
17455 (goto-char (point-min))
17456 (when (re-search-forward
17459 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17461 (regexp-quote "</math>")) nil t)
17462 (prog1 (match-string 0) (kill-buffer))))))
17466 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17468 (write-region mathml nil mathml-file))
17469 (when (org-called-interactively-p 'any)
17471 ((message "LaTeX to MathML conversion failed")
17472 (message shell-command-output)))
17473 (delete-file tmp-in-file)
17474 (when (file-exists-p tmp-out-file)
17475 (delete-file tmp-out-file))
17478 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17479 prefix &optional dir)
17480 "Use `org-create-math-formula' but check local cache first."
17481 (let* ((absprefix (expand-file-name prefix dir))
17482 (print-length nil) (print-level nil)
17483 (formula-id (concat
17488 org-latex-to-mathml-convert-command)))))
17489 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17490 (formula-cache-dir (file-name-directory formula-cache)))
17492 (unless (file-directory-p formula-cache-dir)
17493 (make-directory formula-cache-dir t))
17495 (unless (file-exists-p formula-cache)
17496 (org-create-math-formula latex-frag formula-cache))
17498 (if (file-exists-p formula-cache)
17499 ;; Successful conversion. Return the link to MathML file.
17501 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17502 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17503 'org-latex-src-embed-type (if latex-frag-type
17504 'paragraph 'character)))
17505 ;; Failed conversion. Return the LaTeX fragment verbatim
17506 (add-text-properties
17507 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17510 (defun org-create-formula-image (string tofile options buffer &optional type)
17511 "Create an image from LaTeX source using dvipng or convert.
17512 This function calls either `org-create-formula-image-with-dvipng'
17513 or `org-create-formula-image-with-imagemagick' depending on the
17514 value of `org-latex-create-formula-image-program' or on the value
17515 of the optional TYPE variable.
17517 Note: ultimately these two function should be combined as they
17518 share a good deal of logic."
17519 (org-check-external-command
17520 "latex" "needed to convert LaTeX fragments to images")
17522 (case (or type org-latex-create-formula-image-program)
17524 (org-check-external-command
17525 "dvipng" "needed to convert LaTeX fragments to images")
17526 #'org-create-formula-image-with-dvipng)
17528 (org-check-external-command
17529 "convert" "you need to install imagemagick")
17530 #'org-create-formula-image-with-imagemagick)
17532 "invalid value of `org-latex-create-formula-image-program'")))
17533 string tofile options buffer))
17535 ;; This function borrows from Ganesh Swami's latex2png.el
17536 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17537 "This calls dvipng."
17538 (require 'org-latex)
17539 (let* ((tmpdir (if (featurep 'xemacs)
17541 temporary-file-directory))
17542 (texfilebase (make-temp-name
17543 (expand-file-name "orgtex" tmpdir)))
17544 (texfile (concat texfilebase ".tex"))
17545 (dvifile (concat texfilebase ".dvi"))
17546 (pngfile (concat texfilebase ".png"))
17547 (fnh (if (featurep 'xemacs)
17548 (font-height (face-font 'default))
17549 (face-attribute 'default :height nil)))
17550 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17551 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17552 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17554 (bg (or (plist-get options (if buffer :background :html-background))
17556 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17557 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17558 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17559 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17560 (with-temp-file texfile
17561 (insert (org-splice-latex-header
17562 org-format-latex-header
17563 org-export-latex-default-packages-alist
17564 org-export-latex-packages-alist t
17565 org-format-latex-header-extra))
17566 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17567 (require 'org-latex)
17568 (org-export-latex-fix-inputenc))
17569 (let ((dir default-directory))
17570 (condition-case nil
17573 (call-process "latex" nil nil nil texfile))
17576 (if (not (file-exists-p dvifile))
17577 (progn (message "Failed to create dvi file from %s" texfile) nil)
17578 (condition-case nil
17579 (if (featurep 'xemacs)
17580 (call-process "dvipng" nil nil nil
17585 (call-process "dvipng" nil nil nil
17588 ;;"-x" scale "-y" scale
17593 (if (not (file-exists-p pngfile))
17594 (if org-format-latex-signal-error
17595 (error "Failed to create png file from %s" texfile)
17596 (message "Failed to create png file from %s" texfile)
17598 ;; Use the requested file name and clean up
17599 (copy-file pngfile tofile 'replace)
17600 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17601 (if (file-exists-p (concat texfilebase e))
17602 (delete-file (concat texfilebase e))))
17605 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17606 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17607 "This calls convert, which is included into imagemagick."
17608 (require 'org-latex)
17609 (let* ((tmpdir (if (featurep 'xemacs)
17611 temporary-file-directory))
17612 (texfilebase (make-temp-name
17613 (expand-file-name "orgtex" tmpdir)))
17614 (texfile (concat texfilebase ".tex"))
17615 (pdffile (concat texfilebase ".pdf"))
17616 (pngfile (concat texfilebase ".png"))
17617 (fnh (if (featurep 'xemacs)
17618 (font-height (face-font 'default))
17619 (face-attribute 'default :height nil)))
17620 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17621 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17622 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17624 (bg (or (plist-get options (if buffer :background :html-background))
17626 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17627 (setq fg (org-latex-color-format fg)))
17628 (if (eq bg 'default) (setq bg (org-latex-color :background))
17629 (setq bg (org-latex-color-format
17630 (if (string= bg "Transparent") "white" bg))))
17631 (with-temp-file texfile
17632 (insert (org-splice-latex-header
17633 org-format-latex-header
17634 org-export-latex-default-packages-alist
17635 org-export-latex-packages-alist t
17636 org-format-latex-header-extra))
17637 (insert "\n\\begin{document}\n"
17638 "\\definecolor{fg}{rgb}{" fg "}\n"
17639 "\\definecolor{bg}{rgb}{" bg "}\n"
17640 "\n\\pagecolor{bg}\n"
17644 "\n\\end{document}\n" )
17645 (require 'org-latex)
17646 (org-export-latex-fix-inputenc))
17647 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17648 (condition-case nil
17651 (setq cmds org-latex-to-pdf-process)
17653 (setq latex-frags-cmds (pop cmds))
17654 (if (listp latex-frags-cmds)
17656 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17657 (while latex-frags-cmds
17658 (setq cmd (pop latex-frags-cmds))
17659 (while (string-match "%b" cmd)
17660 (setq cmd (replace-match
17662 (shell-quote-argument texfile))
17664 (while (string-match "%f" cmd)
17665 (setq cmd (replace-match
17667 (shell-quote-argument (file-name-nondirectory texfile)))
17669 (while (string-match "%o" cmd)
17670 (setq cmd (replace-match
17672 (shell-quote-argument (file-name-directory texfile)))
17674 (setq cmd (split-string cmd))
17675 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17678 (if (not (file-exists-p pdffile))
17679 (progn (message "Failed to create pdf file from %s" texfile) nil)
17680 (condition-case nil
17681 (if (featurep 'xemacs)
17682 (call-process "convert" nil nil nil
17688 ;; "-sharpen" "0x1.0"
17690 (call-process "convert" nil nil nil
17696 ; "-sharpen" "0x1.0"
17699 (if (not (file-exists-p pngfile))
17700 (if org-format-latex-signal-error
17701 (error "Failed to create png file from %s" texfile)
17702 (message "Failed to create png file from %s" texfile)
17704 ;; Use the requested file name and clean up
17705 (copy-file pngfile tofile 'replace)
17706 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17707 (if (file-exists-p (concat texfilebase e))
17708 (delete-file (concat texfilebase e))))
17711 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17712 "Fill a LaTeX header template TPL.
17713 In the template, the following place holders will be recognized:
17715 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17716 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17717 [PACKAGES] \\usepackage statements for PKG
17718 [NO-PACKAGES] do not include PKG
17719 [EXTRA] the string EXTRA
17720 [NO-EXTRA] do not include EXTRA
17722 For backward compatibility, if both the positive and the negative place
17723 holder is missing, the positive one (without the \"NO-\") will be
17724 assumed to be present at the end of the template.
17725 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17727 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17728 (let (rpl (end ""))
17729 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17730 (setq rpl (if (or (match-end 1) (not def-pkg))
17731 "" (org-latex-packages-to-string def-pkg snippets-p t))
17732 tpl (replace-match rpl t t tpl))
17733 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17735 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17736 (setq rpl (if (or (match-end 1) (not pkg))
17737 "" (org-latex-packages-to-string pkg snippets-p t))
17738 tpl (replace-match rpl t t tpl))
17741 (org-latex-packages-to-string pkg snippets-p)))))
17743 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17744 (setq rpl (if (or (match-end 1) (not extra))
17745 "" (concat extra "\n"))
17746 tpl (replace-match rpl t t tpl))
17747 (if (and extra (string-match "\\S-" extra))
17748 (setq end (concat end "\n" extra))))
17750 (if (string-match "\\S-" end)
17751 (concat tpl "\n" end)
17754 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17755 "Turn an alist of packages into a string with the \\usepackage macros."
17756 (setq pkg (mapconcat (lambda(p)
17759 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17760 (format "%% Package %s omitted" (cadr p)))
17761 ((equal "" (car p))
17762 (format "\\usepackage{%s}" (cadr p)))
17764 (format "\\usepackage[%s]{%s}"
17765 (car p) (cadr p)))))
17768 (if newline (concat pkg "\n") pkg))
17770 (defun org-dvipng-color (attr)
17771 "Return a RGB color specification for dvipng."
17772 (apply 'format "rgb %s %s %s"
17773 (mapcar 'org-normalize-color
17774 (if (featurep 'xemacs)
17775 (color-rgb-components
17776 (face-property 'default
17777 (cond ((eq attr :foreground) 'foreground)
17778 ((eq attr :background) 'background))))
17779 (color-values (face-attribute 'default attr nil))))))
17781 (defun org-dvipng-color-format (color-name)
17782 "Convert COLOR-NAME to a RGB color value for dvipng."
17783 (apply 'format "rgb %s %s %s"
17784 (mapcar 'org-normalize-color
17785 (color-values color-name))))
17787 (defun org-latex-color (attr)
17788 "Return a RGB color for the LaTeX color package."
17789 (apply 'format "%s,%s,%s"
17790 (mapcar 'org-normalize-color
17791 (if (featurep 'xemacs)
17792 (color-rgb-components
17793 (face-property 'default
17794 (cond ((eq attr :foreground) 'foreground)
17795 ((eq attr :background) 'background))))
17796 (color-values (face-attribute 'default attr nil))))))
17798 (defun org-latex-color-format (color-name)
17799 "Convert COLOR-NAME to a RGB color value."
17800 (apply 'format "%s,%s,%s"
17801 (mapcar 'org-normalize-color
17802 (color-values color-name))))
17804 (defun org-normalize-color (value)
17805 "Return string to be used as color value for an RGB component."
17806 (format "%g" (/ value 65535.0)))
17811 (defvar org-inline-image-overlays nil)
17812 (make-variable-buffer-local 'org-inline-image-overlays)
17814 (defun org-toggle-inline-images (&optional include-linked)
17815 "Toggle the display of inline images.
17816 INCLUDE-LINKED is passed to `org-display-inline-images'."
17818 (if org-inline-image-overlays
17820 (org-remove-inline-images)
17821 (message "Inline image display turned off"))
17822 (org-display-inline-images include-linked)
17823 (if (and (org-called-interactively-p)
17824 org-inline-image-overlays)
17825 (message "%d images displayed inline"
17826 (length org-inline-image-overlays))
17827 (message "No images to display inline"))))
17829 (defun org-redisplay-inline-images ()
17830 "Refresh the display of inline images."
17832 (if (not org-inline-image-overlays)
17833 (org-toggle-inline-images)
17834 (org-toggle-inline-images)
17835 (org-toggle-inline-images)))
17837 (defun org-display-inline-images (&optional include-linked refresh beg end)
17838 "Display inline images.
17839 Normally only links without a description part are inlined, because this
17840 is how it will work for export. When INCLUDE-LINKED is set, also links
17841 with a description part will be inlined. This can be nice for a quick
17842 look at those images, but it does not reflect what exported files will look
17844 When REFRESH is set, refresh existing images between BEG and END.
17845 This will create new image displays only if necessary.
17846 BEG and END default to the buffer boundaries."
17849 (org-remove-inline-images)
17850 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17854 (setq beg (or beg (point-min)) end (or end (point-max)))
17856 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17857 (substring (org-image-file-name-regexp) 0 -2)
17858 "\\)\\]" (if include-linked "" "\\]")))
17859 old file ov img type attrwidth width)
17860 (while (re-search-forward re end t)
17861 (setq old (get-char-property-and-overlay (match-beginning 1)
17862 'org-image-overlay)
17863 file (expand-file-name
17864 (concat (or (match-string 3) "") (match-string 4))))
17865 (when (image-type-available-p 'imagemagick)
17866 (setq attrwidth (if (or (listp org-image-actual-width)
17867 (null org-image-actual-width))
17870 (when (re-search-backward
17871 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
17873 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
17874 (string-to-number (match-string 1))))))
17875 width (cond ((eq org-image-actual-width t) nil)
17876 ((null org-image-actual-width) attrwidth)
17877 ((numberp org-image-actual-width)
17878 org-image-actual-width)
17879 ((listp org-image-actual-width)
17880 (or attrwidth (car org-image-actual-width))))
17881 type (if width 'imagemagick)))
17882 (when (file-exists-p file)
17883 (if (and (car-safe old) refresh)
17884 (image-refresh (overlay-get (cdr old) 'display))
17885 (setq img (save-match-data (create-image file type nil :width width)))
17887 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17888 (overlay-put ov 'display img)
17889 (overlay-put ov 'face 'default)
17890 (overlay-put ov 'org-image-overlay t)
17891 (overlay-put ov 'modification-hooks
17892 (list 'org-display-inline-remove-overlay))
17893 (push ov org-inline-image-overlays)))))))))
17895 (define-obsolete-function-alias
17896 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17898 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17899 "Remove inline-display overlay if a corresponding region is modified."
17900 (let ((inhibit-modification-hooks t))
17901 (when (and ov after)
17902 (delete ov org-inline-image-overlays)
17903 (delete-overlay ov))))
17905 (defun org-remove-inline-images ()
17906 "Remove inline display of images."
17908 (mapc 'delete-overlay org-inline-image-overlays)
17909 (setq org-inline-image-overlays nil))
17913 ;; Outline functions from `outline-mode-prefix-map'
17914 ;; that can be remapped in Org:
17915 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17916 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17917 (define-key org-mode-map [remap outline-forward-same-level]
17918 'org-forward-heading-same-level)
17919 (define-key org-mode-map [remap outline-backward-same-level]
17920 'org-backward-heading-same-level)
17921 (define-key org-mode-map [remap show-branches]
17922 'org-kill-note-or-show-branches)
17923 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17924 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17925 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17927 ;; Outline functions from `outline-mode-prefix-map' that can not
17928 ;; be remapped in Org:
17930 ;; - the column "key binding" shows whether the Outline function is still
17931 ;; available in Org mode on the same key that it has been bound to in
17933 ;; - "overridden": key used for a different functionality in Org mode
17934 ;; - else: key still bound to the same Outline function in Org mode
17936 ;; | Outline function | key binding | Org replacement |
17937 ;; |------------------------------------+-------------+-----------------------|
17938 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17939 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17940 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17941 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17942 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17943 ;; | `show-entry' | overridden | no replacement |
17944 ;; | `show-children' | `C-c C-i' | visibility cycling |
17945 ;; | `show-branches' | `C-c C-k' | still same function |
17946 ;; | `show-subtree' | overridden | visibility cycling |
17947 ;; | `show-all' | overridden | no replacement |
17948 ;; | `hide-subtree' | overridden | visibility cycling |
17949 ;; | `hide-body' | overridden | no replacement |
17950 ;; | `hide-entry' | overridden | visibility cycling |
17951 ;; | `hide-leaves' | overridden | no replacement |
17952 ;; | `hide-sublevels' | overridden | no replacement |
17953 ;; | `hide-other' | overridden | no replacement |
17955 ;; Make `C-c C-x' a prefix key
17956 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17958 ;; TAB key with modifiers
17959 (org-defkey org-mode-map "\C-i" 'org-cycle)
17960 (org-defkey org-mode-map [(tab)] 'org-cycle)
17961 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17962 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17963 ;; The following line is necessary under Suse GNU/Linux
17964 (unless (featurep 'xemacs)
17965 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17966 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17967 (define-key org-mode-map [backtab] 'org-shifttab)
17969 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17970 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17971 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17973 ;; Cursor keys with modifiers
17974 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17975 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17976 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17977 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17979 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17980 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17981 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17982 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17984 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17985 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17986 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17987 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17989 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17990 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17991 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17992 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17995 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17996 (mapc (lambda (pair)
17997 (define-key org-babel-map (car pair) (cdr pair)))
17998 org-babel-key-bindings)
18000 ;;; Extra keys for tty access.
18001 ;; We only set them when really needed because otherwise the
18002 ;; menus don't show the simple keys
18004 (when (or org-use-extra-keys
18005 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18006 (not window-system))
18007 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18008 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18009 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18010 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18011 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18012 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18013 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18014 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18015 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18016 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18017 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18018 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18019 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18020 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18021 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18022 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18023 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18024 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18025 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18026 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18027 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18028 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18029 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18030 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18031 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18032 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18033 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18034 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18036 ;; All the other keys
18038 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18039 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18040 (if (boundp 'narrow-map)
18041 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18042 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18043 (if (boundp 'narrow-map)
18044 (org-defkey narrow-map "b" 'org-narrow-to-block)
18045 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18046 (if (boundp 'narrow-map)
18047 (org-defkey narrow-map "e" 'org-narrow-to-element)
18048 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18049 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18050 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18051 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18052 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18053 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18054 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18055 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18056 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18057 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18058 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18059 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18060 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18061 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18062 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18063 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18064 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18065 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18066 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18067 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18068 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18069 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18070 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18071 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18072 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18073 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18074 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18075 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18076 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18077 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18078 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18079 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18080 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18081 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18082 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18083 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18084 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18085 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18086 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18087 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18088 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18089 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18090 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18091 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18092 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18093 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18094 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18095 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18096 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18097 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18098 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18099 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18100 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18101 (org-defkey org-mode-map "\C-c^" 'org-sort)
18102 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18103 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18104 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18105 (org-defkey org-mode-map "\C-m" 'org-return)
18106 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18107 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18108 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18109 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18110 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18111 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18112 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18113 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18114 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18115 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18116 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18117 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18118 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18119 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18120 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18121 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18122 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18123 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18124 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18125 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18126 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18127 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18128 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18130 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18131 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18132 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18134 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18135 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18136 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18137 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18138 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18139 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18140 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18141 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18142 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18143 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18144 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18145 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18146 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18147 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18148 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18149 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18150 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18151 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18152 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18153 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18154 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18155 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18157 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18158 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18159 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18160 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18161 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18163 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18165 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18167 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18168 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18170 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18173 (when (featurep 'xemacs)
18174 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18177 (defconst org-speed-commands-default
18179 ("Outline Navigation")
18180 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18181 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18182 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18183 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18184 ("u" . (org-speed-move-safe 'outline-up-heading))
18186 ("g" . (org-refile t))
18187 ("Outline Visibility")
18189 ("C" . org-shifttab)
18190 (" " . org-display-outline-path)
18191 (":" . org-columns)
18192 ("Outline Structure Editing")
18193 ("U" . org-shiftmetaup)
18194 ("D" . org-shiftmetadown)
18195 ("r" . org-metaright)
18196 ("l" . org-metaleft)
18197 ("R" . org-shiftmetaright)
18198 ("L" . org-shiftmetaleft)
18199 ("i" . (progn (forward-char 1) (call-interactively
18200 'org-insert-heading-respect-content)))
18203 ("a" . org-archive-subtree-default-with-confirmation)
18204 ("." . org-mark-subtree)
18205 ("#" . org-toggle-comment)
18207 ("I" . org-clock-in)
18208 ("O" . org-clock-out)
18209 ("Meta Data Editing")
18211 ("," . (org-priority))
18212 ("0" . (org-priority ?\ ))
18213 ("1" . (org-priority ?A))
18214 ("2" . (org-priority ?B))
18215 ("3" . (org-priority ?C))
18216 (";" . org-set-tags-command)
18217 ("e" . org-set-effort)
18218 ("E" . org-inc-effort)
18219 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18220 (org-entry-put (point) "APPT_WARNTIME" m)))
18221 ("Agenda Views etc")
18223 ("/" . org-sparse-tree)
18225 ("o" . org-open-at-point)
18226 ("?" . org-speed-command-help)
18227 ("<" . (org-agenda-set-restriction-lock 'subtree))
18228 (">" . (org-agenda-remove-restriction-lock))
18230 "The default speed commands.")
18232 (defun org-print-speed-command (e)
18233 (if (> (length (car e)) 1)
18238 (princ (make-string (length (car e)) ?-))
18242 (if (symbolp (cdr e))
18243 (princ (symbol-name (cdr e)))
18247 (defun org-speed-command-help ()
18248 "Show the available speed commands."
18250 (if (not org-use-speed-commands)
18251 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18252 (with-output-to-temp-buffer "*Help*"
18253 (princ "User-defined Speed commands\n===========================\n")
18254 (mapc 'org-print-speed-command org-speed-commands-user)
18256 (princ "Built-in Speed commands\n=======================\n")
18257 (mapc 'org-print-speed-command org-speed-commands-default))
18258 (with-current-buffer "*Help*"
18259 (setq truncate-lines t))))
18261 (defun org-speed-move-safe (cmd)
18262 "Execute CMD, but make sure that the cursor always ends up in a headline.
18263 If not, return to the original position and throw an error."
18265 (let ((pos (point)))
18266 (call-interactively cmd)
18267 (unless (and (bolp) (org-at-heading-p))
18269 (error "Boundary reached while executing %s" cmd))))
18271 (defvar org-self-insert-command-undo-counter 0)
18273 (defvar org-table-auto-blank-field) ; defined in org-table.el
18274 (defvar org-speed-command nil)
18276 (define-obsolete-function-alias
18277 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18279 (defun org-speed-command-activate (keys)
18280 "Hook for activating single-letter speed commands.
18281 `org-speed-commands-default' specifies a minimal command set.
18282 Use `org-speed-commands-user' for further customization."
18283 (when (or (and (bolp) (looking-at org-outline-regexp))
18284 (and (functionp org-use-speed-commands)
18285 (funcall org-use-speed-commands)))
18286 (cdr (assoc keys (append org-speed-commands-user
18287 org-speed-commands-default)))))
18289 (define-obsolete-function-alias
18290 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18292 (defun org-babel-speed-command-activate (keys)
18293 "Hook for activating single-letter code block commands."
18294 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18295 (cdr (assoc keys org-babel-key-bindings))))
18297 (defcustom org-speed-command-hook
18298 '(org-speed-command-default-hook org-babel-speed-command-hook)
18299 "Hook for activating speed commands at strategic locations.
18300 Hook functions are called in sequence until a valid handler is
18303 Each hook takes a single argument, a user-pressed command key
18304 which is also a `self-insert-command' from the global map.
18306 Within the hook, examine the cursor position and the command key
18307 and return nil or a valid handler as appropriate. Handler could
18308 be one of an interactive command, a function, or a form.
18310 Set `org-use-speed-commands' to non-nil value to enable this
18311 hook. The default setting is `org-speed-command-activate'."
18312 :group 'org-structure
18316 (defun org-self-insert-command (N)
18317 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18318 If the cursor is in a table looking at whitespace, the whitespace is
18319 overwritten, and the table is not marked as requiring realignment."
18321 (org-check-before-invisible-edit 'insert)
18323 ((and org-use-speed-commands
18324 (setq org-speed-command
18325 (run-hook-with-args-until-success
18326 'org-speed-command-hook (this-command-keys))))
18328 ((commandp org-speed-command)
18329 (setq this-command org-speed-command)
18330 (call-interactively org-speed-command))
18331 ((functionp org-speed-command)
18332 (funcall org-speed-command))
18333 ((and org-speed-command (listp org-speed-command))
18334 (eval org-speed-command))
18335 (t (let (org-use-speed-commands)
18336 (call-interactively 'org-self-insert-command)))))
18340 ;; check if we blank the field, and if that triggers align
18341 (and (featurep 'org-table) org-table-auto-blank-field
18342 (member last-command
18343 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18344 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18345 ;; got extra space, this field does not determine column width
18346 (let (org-table-may-need-update) (org-table-blank-field))
18347 ;; no extra space, this field may determine column width
18348 (org-table-blank-field)))
18351 (looking-at "[^|\n]* |"))
18352 (let (org-table-may-need-update)
18353 (goto-char (1- (match-end 0)))
18354 (backward-delete-char 1)
18355 (goto-char (match-beginning 0))
18356 (self-insert-command N)))
18358 (setq org-table-may-need-update t)
18359 (self-insert-command N)
18360 (org-fix-tags-on-the-fly)
18361 (if org-self-insert-cluster-for-undo
18362 (if (not (eq last-command 'org-self-insert-command))
18363 (setq org-self-insert-command-undo-counter 1)
18364 (if (>= org-self-insert-command-undo-counter 20)
18365 (setq org-self-insert-command-undo-counter 1)
18366 (and (> org-self-insert-command-undo-counter 0)
18367 buffer-undo-list (listp buffer-undo-list)
18368 (not (cadr buffer-undo-list)) ; remove nil entry
18369 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18370 (setq org-self-insert-command-undo-counter
18371 (1+ org-self-insert-command-undo-counter))))))))
18373 (defun org-check-before-invisible-edit (kind)
18374 "Check is editing if kind KIND would be dangerous with invisible text around.
18375 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18376 ;; First, try to get out of here as quickly as possible, to reduce overhead
18377 (if (and org-catch-invisible-edits
18378 (or (not (boundp 'visible-mode)) (not visible-mode))
18379 (or (get-char-property (point) 'invisible)
18380 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18381 ;; OK, we need to take a closer look
18382 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18383 (invisible-before-point (if (bobp) nil (get-char-property
18384 (1- (point)) 'invisible)))
18385 (border-and-ok-direction
18387 ;; Check if we are acting predictably before invisible text
18388 (and invisible-at-point (not invisible-before-point)
18389 (memq kind '(insert delete-backward)))
18390 ;; Check if we are acting predictably after invisible text
18391 ;; This works not well, and I have turned it off. It seems
18392 ;; better to always show and stop after invisible text.
18393 ;; (and (not invisible-at-point) invisible-before-point
18394 ;; (memq kind '(insert delete)))
18396 (when (or (memq invisible-at-point '(outline org-hide-block t))
18397 (memq invisible-before-point '(outline org-hide-block t)))
18398 (if (eq org-catch-invisible-edits 'error)
18399 (error "Editing in invisible areas is prohibited - make visible first"))
18400 (if (and org-custom-properties-overlays
18401 (y-or-n-p "Display invisible properties in this buffer? "))
18402 (org-toggle-custom-properties-visibility)
18403 ;; Make the area visible
18405 (if invisible-before-point
18406 (goto-char (previous-single-char-property-change
18407 (point) 'invisible)))
18410 ((eq org-catch-invisible-edits 'show)
18411 ;; That's it, we do the edit after showing
18413 "Unfolding invisible region around point before editing")
18415 ((and (eq org-catch-invisible-edits 'smart)
18416 border-and-ok-direction)
18417 (message "Unfolding invisible region around point before editing"))
18419 ;; Don't do the edit, make the user repeat it in full visibility
18420 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18422 (defun org-fix-tags-on-the-fly ()
18423 (when (and (equal (char-after (point-at-bol)) ?*)
18424 (org-at-heading-p))
18425 (org-align-tags-here org-tags-column)))
18427 (defun org-delete-backward-char (N)
18428 "Like `delete-backward-char', insert whitespace at field end in tables.
18429 When deleting backwards, in tables this function will insert whitespace in
18430 front of the next \"|\" separator, to keep the table aligned. The table will
18431 still be marked for re-alignment if the field did fill the entire column,
18432 because, in this case the deletion might narrow the column."
18434 (org-check-before-invisible-edit 'delete-backward)
18435 (if (and (org-table-p)
18437 (string-match "|" (buffer-substring (point-at-bol) (point)))
18438 (looking-at ".*?|"))
18439 (let ((pos (point))
18440 (noalign (looking-at "[^|\n\r]* |"))
18441 (c org-table-may-need-update))
18442 (backward-delete-char N)
18443 (if (not overwrite-mode)
18445 (skip-chars-forward "^|")
18447 (goto-char (1- pos))))
18448 ;; noalign: if there were two spaces at the end, this field
18449 ;; does not determine the width of the column.
18450 (if noalign (setq org-table-may-need-update c)))
18451 (backward-delete-char N)
18452 (org-fix-tags-on-the-fly)))
18454 (defun org-delete-char (N)
18455 "Like `delete-char', but insert whitespace at field end in tables.
18456 When deleting characters, in tables this function will insert whitespace in
18457 front of the next \"|\" separator, to keep the table aligned. The table will
18458 still be marked for re-alignment if the field did fill the entire column,
18459 because, in this case the deletion might narrow the column."
18461 (org-check-before-invisible-edit 'delete)
18462 (if (and (org-table-p)
18464 (not (= (char-after) ?|))
18466 (if (looking-at ".*?|")
18467 (let ((pos (point))
18468 (noalign (looking-at "[^|\n\r]* |"))
18469 (c org-table-may-need-update))
18470 (replace-match (concat
18471 (substring (match-string 0) 1 -1)
18474 ;; noalign: if there were two spaces at the end, this field
18475 ;; does not determine the width of the column.
18476 (if noalign (setq org-table-may-need-update c)))
18479 (org-fix-tags-on-the-fly)))
18481 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18482 (put 'org-self-insert-command 'delete-selection t)
18483 (put 'orgtbl-self-insert-command 'delete-selection t)
18484 (put 'org-delete-char 'delete-selection 'supersede)
18485 (put 'org-delete-backward-char 'delete-selection 'supersede)
18486 (put 'org-yank 'delete-selection 'yank)
18488 ;; Make `flyspell-mode' delay after some commands
18489 (put 'org-self-insert-command 'flyspell-delayed t)
18490 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18491 (put 'org-delete-char 'flyspell-delayed t)
18492 (put 'org-delete-backward-char 'flyspell-delayed t)
18494 ;; Make pabbrev-mode expand after org-mode commands
18495 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18496 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18498 ;; How to do this: Measure non-white length of current string
18499 ;; If equal to column width, we should realign.
18501 (defun org-remap (map &rest commands)
18502 "In MAP, remap the functions given in COMMANDS.
18503 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18506 (setq old (pop commands) new (pop commands))
18507 (if (fboundp 'command-remapping)
18508 (org-defkey map (vector 'remap old) new)
18509 (substitute-key-definition old new map global-map)))))
18511 (when (eq org-enable-table-editor 'optimized)
18512 ;; If the user wants maximum table support, we need to hijack
18513 ;; some standard editing functions
18514 (org-remap org-mode-map
18515 'self-insert-command 'org-self-insert-command
18516 'delete-char 'org-delete-char
18517 'delete-backward-char 'org-delete-backward-char)
18518 (org-defkey org-mode-map "|" 'org-force-self-insert))
18520 (defvar org-ctrl-c-ctrl-c-hook nil
18521 "Hook for functions attaching themselves to `C-c C-c'.
18523 This can be used to add additional functionality to the C-c C-c
18524 key which executes context-dependent commands. This hook is run
18525 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18526 run after the last test.
18528 Each function will be called with no arguments. The function
18529 must check if the context is appropriate for it to act. If yes,
18530 it should do its thing and then return a non-nil value. If the
18531 context is wrong, just do nothing and return nil.")
18533 (defvar org-ctrl-c-ctrl-c-final-hook nil
18534 "Hook for functions attaching themselves to `C-c C-c'.
18536 This can be used to add additional functionality to the C-c C-c
18537 key which executes context-dependent commands. This hook is run
18538 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18539 before the first test.
18541 Each function will be called with no arguments. The function
18542 must check if the context is appropriate for it to act. If yes,
18543 it should do its thing and then return a non-nil value. If the
18544 context is wrong, just do nothing and return nil.")
18546 (defvar org-tab-first-hook nil
18547 "Hook for functions to attach themselves to TAB.
18548 See `org-ctrl-c-ctrl-c-hook' for more information.
18549 This hook runs as the first action when TAB is pressed, even before
18550 `org-cycle' messes around with the `outline-regexp' to cater for
18551 inline tasks and plain list item folding.
18552 If any function in this hook returns t, any other actions that
18553 would have been caused by TAB (such as table field motion or visibility
18554 cycling) will not occur.")
18556 (defvar org-tab-after-check-for-table-hook nil
18557 "Hook for functions to attach themselves to TAB.
18558 See `org-ctrl-c-ctrl-c-hook' for more information.
18559 This hook runs after it has been established that the cursor is not in a
18560 table, but before checking if the cursor is in a headline or if global cycling
18562 If any function in this hook returns t, not other actions like visibility
18563 cycling will be done.")
18565 (defvar org-tab-after-check-for-cycling-hook nil
18566 "Hook for functions to attach themselves to TAB.
18567 See `org-ctrl-c-ctrl-c-hook' for more information.
18568 This hook runs after it has been established that not table field motion and
18569 not visibility should be done because of current context. This is probably
18570 the place where a package like yasnippets can hook in.")
18572 (defvar org-tab-before-tab-emulation-hook nil
18573 "Hook for functions to attach themselves to TAB.
18574 See `org-ctrl-c-ctrl-c-hook' for more information.
18575 This hook runs after every other options for TAB have been exhausted, but
18576 before indentation and \t insertion takes place.")
18578 (defvar org-metaleft-hook nil
18579 "Hook for functions attaching themselves to `M-left'.
18580 See `org-ctrl-c-ctrl-c-hook' for more information.")
18581 (defvar org-metaright-hook nil
18582 "Hook for functions attaching themselves to `M-right'.
18583 See `org-ctrl-c-ctrl-c-hook' for more information.")
18584 (defvar org-metaup-hook nil
18585 "Hook for functions attaching themselves to `M-up'.
18586 See `org-ctrl-c-ctrl-c-hook' for more information.")
18587 (defvar org-metadown-hook nil
18588 "Hook for functions attaching themselves to `M-down'.
18589 See `org-ctrl-c-ctrl-c-hook' for more information.")
18590 (defvar org-shiftmetaleft-hook nil
18591 "Hook for functions attaching themselves to `M-S-left'.
18592 See `org-ctrl-c-ctrl-c-hook' for more information.")
18593 (defvar org-shiftmetaright-hook nil
18594 "Hook for functions attaching themselves to `M-S-right'.
18595 See `org-ctrl-c-ctrl-c-hook' for more information.")
18596 (defvar org-shiftmetaup-hook nil
18597 "Hook for functions attaching themselves to `M-S-up'.
18598 See `org-ctrl-c-ctrl-c-hook' for more information.")
18599 (defvar org-shiftmetadown-hook nil
18600 "Hook for functions attaching themselves to `M-S-down'.
18601 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defvar org-metareturn-hook nil
18603 "Hook for functions attaching themselves to `M-RET'.
18604 See `org-ctrl-c-ctrl-c-hook' for more information.")
18605 (defvar org-shiftup-hook nil
18606 "Hook for functions attaching themselves to `S-up'.
18607 See `org-ctrl-c-ctrl-c-hook' for more information.")
18608 (defvar org-shiftup-final-hook nil
18609 "Hook for functions attaching themselves to `S-up'.
18610 This one runs after all other options except shift-select have been excluded.
18611 See `org-ctrl-c-ctrl-c-hook' for more information.")
18612 (defvar org-shiftdown-hook nil
18613 "Hook for functions attaching themselves to `S-down'.
18614 See `org-ctrl-c-ctrl-c-hook' for more information.")
18615 (defvar org-shiftdown-final-hook nil
18616 "Hook for functions attaching themselves to `S-down'.
18617 This one runs after all other options except shift-select have been excluded.
18618 See `org-ctrl-c-ctrl-c-hook' for more information.")
18619 (defvar org-shiftleft-hook nil
18620 "Hook for functions attaching themselves to `S-left'.
18621 See `org-ctrl-c-ctrl-c-hook' for more information.")
18622 (defvar org-shiftleft-final-hook nil
18623 "Hook for functions attaching themselves to `S-left'.
18624 This one runs after all other options except shift-select have been excluded.
18625 See `org-ctrl-c-ctrl-c-hook' for more information.")
18626 (defvar org-shiftright-hook nil
18627 "Hook for functions attaching themselves to `S-right'.
18628 See `org-ctrl-c-ctrl-c-hook' for more information.")
18629 (defvar org-shiftright-final-hook nil
18630 "Hook for functions attaching themselves to `S-right'.
18631 This one runs after all other options except shift-select have been excluded.
18632 See `org-ctrl-c-ctrl-c-hook' for more information.")
18634 (defun org-modifier-cursor-error ()
18635 "Throw an error, a modified cursor command was applied in wrong context."
18636 (error "This command is active in special context like tables, headlines or items"))
18638 (defun org-shiftselect-error ()
18639 "Throw an error because Shift-Cursor command was applied in wrong context."
18640 (if (and (boundp 'shift-select-mode) shift-select-mode)
18641 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18642 (error "This command works only in special context like headlines or timestamps")))
18644 (defun org-call-for-shift-select (cmd)
18645 (let ((this-command-keys-shift-translated t))
18646 (call-interactively cmd)))
18648 (defun org-shifttab (&optional arg)
18649 "Global visibility cycling or move to previous table field.
18650 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18652 See the individual commands for more information."
18655 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18657 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18658 (message "Content view to level: %d" arg)
18659 (org-content (prefix-numeric-value arg2))
18660 (setq org-cycle-global-status 'overview)))
18661 (t (call-interactively 'org-global-cycle))))
18663 (defun org-shiftmetaleft ()
18664 "Promote subtree or delete table column.
18665 Calls `org-promote-subtree', `org-outdent-item-tree', or
18666 `org-table-delete-column', depending on context. See the
18667 individual commands for more information."
18670 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18671 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18672 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18673 ((if (not (org-region-active-p)) (org-at-item-p)
18674 (save-excursion (goto-char (region-beginning))
18676 (call-interactively 'org-outdent-item-tree))
18677 (t (org-modifier-cursor-error))))
18679 (defun org-shiftmetaright ()
18680 "Demote subtree or insert table column.
18681 Calls `org-demote-subtree', `org-indent-item-tree', or
18682 `org-table-insert-column', depending on context. See the
18683 individual commands for more information."
18686 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18687 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18688 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18689 ((if (not (org-region-active-p)) (org-at-item-p)
18690 (save-excursion (goto-char (region-beginning))
18692 (call-interactively 'org-indent-item-tree))
18693 (t (org-modifier-cursor-error))))
18695 (defun org-shiftmetaup (&optional arg)
18696 "Move subtree up or kill table row.
18697 Calls `org-move-subtree-up' or `org-table-kill-row' or
18698 `org-move-item-up' or `org-timestamp-up', depending on context.
18699 See the individual commands for more information."
18702 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18703 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18704 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18705 ((org-at-item-p) (call-interactively 'org-move-item-up))
18706 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18707 (call-interactively 'org-timestamp-up)))
18708 (t (org-modifier-cursor-error))))
18710 (defun org-shiftmetadown (&optional arg)
18711 "Move subtree down or insert table row.
18712 Calls `org-move-subtree-down' or `org-table-insert-row' or
18713 `org-move-item-down' or `org-timestamp-up', depending on context.
18714 See the individual commands for more information."
18717 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18718 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18719 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18720 ((org-at-item-p) (call-interactively 'org-move-item-down))
18721 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18722 (call-interactively 'org-timestamp-down)))
18723 (t (org-modifier-cursor-error))))
18725 (defsubst org-hidden-tree-error ()
18727 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18729 (defun org-metaleft (&optional arg)
18730 "Promote heading or move table column to left.
18731 Calls `org-do-promote' or `org-table-move-column', depending on context.
18732 With no specific context, calls the Emacs default `backward-word'.
18733 See the individual commands for more information."
18736 ((run-hook-with-args-until-success 'org-metaleft-hook))
18737 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18738 ((org-with-limited-levels
18739 (or (org-at-heading-p)
18740 (and (org-region-active-p)
18742 (goto-char (region-beginning))
18743 (org-at-heading-p)))))
18744 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18745 (call-interactively 'org-do-promote))
18746 ;; At an inline task.
18747 ((org-at-heading-p)
18748 (call-interactively 'org-inlinetask-promote))
18749 ((or (org-at-item-p)
18750 (and (org-region-active-p)
18752 (goto-char (region-beginning))
18754 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18755 (call-interactively 'org-outdent-item))
18756 (t (call-interactively 'backward-word))))
18758 (defun org-metaright (&optional arg)
18759 "Demote a subtree, a list item or move table column to right.
18760 In front of a drawer or a block keyword, indent it correctly.
18761 With no specific context, calls the Emacs default `forward-word'.
18762 See the individual commands for more information."
18765 ((run-hook-with-args-until-success 'org-metaright-hook))
18766 ((org-at-table-p) (call-interactively 'org-table-move-column))
18767 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18768 ((org-at-block-p) (call-interactively 'org-indent-block))
18769 ((org-with-limited-levels
18770 (or (org-at-heading-p)
18771 (and (org-region-active-p)
18773 (goto-char (region-beginning))
18774 (org-at-heading-p)))))
18775 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18776 (call-interactively 'org-do-demote))
18777 ;; At an inline task.
18778 ((org-at-heading-p)
18779 (call-interactively 'org-inlinetask-demote))
18780 ((or (org-at-item-p)
18781 (and (org-region-active-p)
18783 (goto-char (region-beginning))
18785 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18786 (call-interactively 'org-indent-item))
18787 (t (call-interactively 'forward-word))))
18789 (defun org-check-for-hidden (what)
18790 "Check if there are hidden headlines/items in the current visual line.
18791 WHAT can be either `headlines' or `items'. If the current line is
18792 an outline or item heading and it has a folded subtree below it,
18793 this function returns t, nil otherwise."
18795 ((eq what 'headlines) org-outline-regexp-bol)
18796 ((eq what 'items) (org-item-beginning-re))
18797 (t (error "This should not happen"))))
18801 (unless (org-region-active-p)
18802 (setq beg (point-at-bol))
18803 (beginning-of-line 2)
18804 (while (and (not (eobp)) ;; this is like `next-line'
18805 (get-char-property (1- (point)) 'invisible))
18806 (beginning-of-line 2))
18809 (goto-char (point-at-eol))
18810 (setq end (max end (point)))
18811 (while (re-search-forward re end t)
18812 (if (get-char-property (match-beginning 0) 'invisible)
18816 (defun org-metaup (&optional arg)
18817 "Move subtree up or move table row up.
18818 Calls `org-move-subtree-up' or `org-table-move-row' or
18819 `org-move-item-up', depending on context. See the individual commands
18820 for more information."
18823 ((run-hook-with-args-until-success 'org-metaup-hook))
18824 ((org-region-active-p)
18825 (let* ((a (min (region-beginning) (region-end)))
18826 (b (1- (max (region-beginning) (region-end))))
18827 (c (save-excursion (goto-char a)
18828 (move-beginning-of-line 0)))
18829 (d (save-excursion (goto-char a)
18830 (move-end-of-line 0) (point))))
18831 (transpose-regions a b c d)
18833 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18834 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18835 ((org-at-item-p) (call-interactively 'org-move-item-up))
18836 (t (org-drag-element-backward))))
18838 (defun org-metadown (&optional arg)
18839 "Move subtree down or move table row down.
18840 Calls `org-move-subtree-down' or `org-table-move-row' or
18841 `org-move-item-down', depending on context. See the individual
18842 commands for more information."
18845 ((run-hook-with-args-until-success 'org-metadown-hook))
18846 ((org-region-active-p)
18847 (let* ((a (min (region-beginning) (region-end)))
18848 (b (max (region-beginning) (region-end)))
18849 (c (save-excursion (goto-char b)
18850 (move-beginning-of-line 1)))
18851 (d (save-excursion (goto-char b)
18852 (move-end-of-line 1) (1+ (point)))))
18853 (transpose-regions a b c d)
18855 ((org-at-table-p) (call-interactively 'org-table-move-row))
18856 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18857 ((org-at-item-p) (call-interactively 'org-move-item-down))
18858 (t (org-drag-element-forward))))
18860 (defun org-shiftup (&optional arg)
18861 "Increase item in timestamp or increase priority of current headline.
18862 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18863 depending on context. See the individual commands for more information."
18866 ((run-hook-with-args-until-success 'org-shiftup-hook))
18867 ((and org-support-shift-select (org-region-active-p))
18868 (org-call-for-shift-select 'previous-line))
18869 ((org-at-timestamp-p t)
18870 (call-interactively (if org-edit-timestamp-down-means-later
18871 'org-timestamp-down 'org-timestamp-up)))
18872 ((and (not (eq org-support-shift-select 'always))
18873 org-enable-priority-commands
18874 (org-at-heading-p))
18875 (call-interactively 'org-priority-up))
18876 ((and (not org-support-shift-select) (org-at-item-p))
18877 (call-interactively 'org-previous-item))
18878 ((org-clocktable-try-shift 'up arg))
18879 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18880 (org-support-shift-select
18881 (org-call-for-shift-select 'previous-line))
18882 (t (org-shiftselect-error))))
18884 (defun org-shiftdown (&optional arg)
18885 "Decrease item in timestamp or decrease priority of current headline.
18886 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18887 depending on context. See the individual commands for more information."
18890 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18891 ((and org-support-shift-select (org-region-active-p))
18892 (org-call-for-shift-select 'next-line))
18893 ((org-at-timestamp-p t)
18894 (call-interactively (if org-edit-timestamp-down-means-later
18895 'org-timestamp-up 'org-timestamp-down)))
18896 ((and (not (eq org-support-shift-select 'always))
18897 org-enable-priority-commands
18898 (org-at-heading-p))
18899 (call-interactively 'org-priority-down))
18900 ((and (not org-support-shift-select) (org-at-item-p))
18901 (call-interactively 'org-next-item))
18902 ((org-clocktable-try-shift 'down arg))
18903 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18904 (org-support-shift-select
18905 (org-call-for-shift-select 'next-line))
18906 (t (org-shiftselect-error))))
18908 (defun org-shiftright (&optional arg)
18909 "Cycle the thing at point or in the current line, depending on context.
18910 Depending on context, this does one of the following:
18912 - switch a timestamp at point one day into the future
18913 - on a headline, switch to the next TODO keyword.
18914 - on an item, switch entire list to the next bullet type
18915 - on a property line, switch to the next allowed value
18916 - on a clocktable definition line, move time block into the future"
18919 ((run-hook-with-args-until-success 'org-shiftright-hook))
18920 ((and org-support-shift-select (org-region-active-p))
18921 (org-call-for-shift-select 'forward-char))
18922 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18923 ((and (not (eq org-support-shift-select 'always))
18924 (org-at-heading-p))
18925 (let ((org-inhibit-logging
18926 (not org-treat-S-cursor-todo-selection-as-state-change))
18927 (org-inhibit-blocking
18928 (not org-treat-S-cursor-todo-selection-as-state-change)))
18929 (org-call-with-arg 'org-todo 'right)))
18930 ((or (and org-support-shift-select
18931 (not (eq org-support-shift-select 'always))
18932 (org-at-item-bullet-p))
18933 (and (not org-support-shift-select) (org-at-item-p)))
18934 (org-call-with-arg 'org-cycle-list-bullet nil))
18935 ((and (not (eq org-support-shift-select 'always))
18936 (org-at-property-p))
18937 (call-interactively 'org-property-next-allowed-value))
18938 ((org-clocktable-try-shift 'right arg))
18939 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18940 (org-support-shift-select
18941 (org-call-for-shift-select 'forward-char))
18942 (t (org-shiftselect-error))))
18944 (defun org-shiftleft (&optional arg)
18945 "Cycle the thing at point or in the current line, depending on context.
18946 Depending on context, this does one of the following:
18948 - switch a timestamp at point one day into the past
18949 - on a headline, switch to the previous TODO keyword.
18950 - on an item, switch entire list to the previous bullet type
18951 - on a property line, switch to the previous allowed value
18952 - on a clocktable definition line, move time block into the past"
18955 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18956 ((and org-support-shift-select (org-region-active-p))
18957 (org-call-for-shift-select 'backward-char))
18958 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18959 ((and (not (eq org-support-shift-select 'always))
18960 (org-at-heading-p))
18961 (let ((org-inhibit-logging
18962 (not org-treat-S-cursor-todo-selection-as-state-change))
18963 (org-inhibit-blocking
18964 (not org-treat-S-cursor-todo-selection-as-state-change)))
18965 (org-call-with-arg 'org-todo 'left)))
18966 ((or (and org-support-shift-select
18967 (not (eq org-support-shift-select 'always))
18968 (org-at-item-bullet-p))
18969 (and (not org-support-shift-select) (org-at-item-p)))
18970 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18971 ((and (not (eq org-support-shift-select 'always))
18972 (org-at-property-p))
18973 (call-interactively 'org-property-previous-allowed-value))
18974 ((org-clocktable-try-shift 'left arg))
18975 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18976 (org-support-shift-select
18977 (org-call-for-shift-select 'backward-char))
18978 (t (org-shiftselect-error))))
18980 (defun org-shiftcontrolright ()
18981 "Switch to next TODO set."
18984 ((and org-support-shift-select (org-region-active-p))
18985 (org-call-for-shift-select 'forward-word))
18986 ((and (not (eq org-support-shift-select 'always))
18987 (org-at-heading-p))
18988 (org-call-with-arg 'org-todo 'nextset))
18989 (org-support-shift-select
18990 (org-call-for-shift-select 'forward-word))
18991 (t (org-shiftselect-error))))
18993 (defun org-shiftcontrolleft ()
18994 "Switch to previous TODO set."
18997 ((and org-support-shift-select (org-region-active-p))
18998 (org-call-for-shift-select 'backward-word))
18999 ((and (not (eq org-support-shift-select 'always))
19000 (org-at-heading-p))
19001 (org-call-with-arg 'org-todo 'previousset))
19002 (org-support-shift-select
19003 (org-call-for-shift-select 'backward-word))
19004 (t (org-shiftselect-error))))
19006 (defun org-shiftcontrolup ()
19007 "Change timestamps synchronously up in CLOCK log lines."
19009 (cond ((and (not org-support-shift-select)
19010 (org-at-clock-log-p)
19011 (org-at-timestamp-p t))
19012 (org-clock-timestamps-up))
19013 (t (org-shiftselect-error))))
19015 (defun org-shiftcontroldown ()
19016 "Change timestamps synchronously down in CLOCK log lines."
19018 (cond ((and (not org-support-shift-select)
19019 (org-at-clock-log-p)
19020 (org-at-timestamp-p t))
19021 (org-clock-timestamps-down))
19022 (t (org-shiftselect-error))))
19024 (defun org-ctrl-c-ret ()
19025 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19028 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19029 (t (call-interactively 'org-insert-heading))))
19031 (defun org-find-visible ()
19033 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19034 (get-char-property s 'invisible)))
19036 (defun org-find-invisible ()
19038 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19039 (not (get-char-property s 'invisible))))
19042 (defun org-copy-visible (beg end)
19043 "Copy the visible parts of the region."
19048 (narrow-to-region beg end)
19049 (setq s (goto-char (point-min)))
19050 (while (not (= (point) (point-max)))
19051 (goto-char (org-find-invisible))
19052 (push (buffer-substring s (point)) snippets)
19053 (setq s (goto-char (org-find-visible))))))
19054 (kill-new (apply 'concat (nreverse snippets)))))
19056 (defun org-copy-special ()
19057 "Copy region in table or copy current subtree.
19058 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19059 See the individual commands for more information."
19061 (call-interactively
19062 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19064 (defun org-cut-special ()
19065 "Cut region in table or cut current subtree.
19066 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19067 See the individual commands for more information."
19069 (call-interactively
19070 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19072 (defun org-paste-special (arg)
19073 "Paste rectangular region into table, or past subtree relative to level.
19074 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19075 See the individual commands for more information."
19077 (if (org-at-table-p)
19078 (org-table-paste-rectangle)
19079 (org-paste-subtree arg)))
19081 (defun org-edit-special (&optional arg)
19082 "Call a special editor for the stuff at point.
19083 When at a table, call the formula editor with `org-table-edit-formulas'.
19084 When at the first line of an src example, call `org-edit-src-code'.
19085 When in an #+include line, visit the include file. Otherwise call
19086 `ffap' to visit the file at point."
19088 ;; possibly prep session before editing source
19090 (let* ((info (org-babel-get-src-block-info))
19091 (lang (nth 0 info))
19092 (params (nth 2 info))
19093 (session (cdr (assoc :session params))))
19094 (when (and info session) ;; we are in a source-code block with a session
19096 (intern (concat "org-babel-prep-session:" lang)) session params))))
19097 (cond ;; proceed with `org-edit-special'
19099 (beginning-of-line 1)
19100 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19101 (find-file (org-trim (match-string 1))))
19102 ((org-edit-src-code))
19103 ((org-edit-fixed-width-region))
19104 ((org-at-table.el-p)
19105 (org-edit-src-code))
19106 ((or (org-at-table-p)
19108 (beginning-of-line 1)
19109 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19110 (call-interactively 'org-table-edit-formulas))
19111 (t (call-interactively 'ffap))))
19113 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19114 (defun org-ctrl-c-ctrl-c (&optional arg)
19115 "Set tags in headline, or update according to changed information at point.
19117 This command does many different things, depending on context:
19119 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19120 this is what we do.
19122 - If the cursor is on a statistics cookie, update it.
19124 - If the cursor is in a headline, prompt for tags and insert them
19125 into the current line, aligned to `org-tags-column'. When called
19126 with prefix arg, realign all tags in the current buffer.
19128 - If the cursor is in one of the special #+KEYWORD lines, this
19129 triggers scanning the buffer for these lines and updating the
19132 - If the cursor is inside a table, realign the table. This command
19133 works even if the automatic table editor has been turned off.
19135 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19138 - If the cursor is at a footnote reference or definition, jump to
19139 the corresponding definition or references, respectively.
19141 - If the cursor is a the beginning of a dynamic block, update it.
19143 - If the current buffer is a capture buffer, close note and file it.
19145 - If the cursor is on a <<<target>>>, update radio targets and
19146 corresponding links in this buffer.
19148 - If the cursor is on a numbered item in a plain list, renumber the
19151 - If the cursor is on a checkbox, toggle it.
19153 - If the cursor is on a code block, evaluate it. The variable
19154 `org-confirm-babel-evaluate' can be used to control prompting
19155 before code block evaluation, by default every code block
19156 evaluation requires confirmation. Code block evaluation can be
19157 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19159 (let ((org-enable-table-editor t))
19161 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19162 org-occur-highlights
19163 org-latex-fragment-image-overlays)
19164 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19165 (org-remove-occur-highlights)
19166 (org-remove-latex-fragment-image-overlays)
19167 (message "Temporary highlights/overlays removed from current buffer"))
19168 ((and (local-variable-p 'org-finish-function (current-buffer))
19169 (fboundp org-finish-function))
19170 (funcall org-finish-function))
19171 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19172 ((org-in-regexp org-ts-regexp-both)
19173 (org-timestamp-change 0 'day))
19174 ((or (looking-at org-property-start-re)
19175 (org-at-property-p))
19176 (call-interactively 'org-property-action))
19177 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19178 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19179 (or (org-at-heading-p) (org-at-item-p)))
19180 (call-interactively 'org-update-statistics-cookies))
19181 ((org-at-heading-p) (call-interactively 'org-set-tags))
19182 ((org-at-table.el-p)
19183 (message "Use C-c ' to edit table.el tables"))
19185 (org-table-maybe-eval-formula)
19187 (call-interactively 'org-table-recalculate)
19188 (org-table-maybe-recalculate-line))
19189 (call-interactively 'org-table-align)
19190 (orgtbl-send-table 'maybe))
19191 ((or (org-footnote-at-reference-p)
19192 (org-footnote-at-definition-p))
19193 (call-interactively 'org-footnote-action))
19194 ((org-at-item-checkbox-p)
19195 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19196 ;; list only if at top item.
19197 (let* ((cbox (match-string 1))
19198 (struct (org-list-struct))
19199 (old-struct (copy-tree struct))
19200 (parents (org-list-parents-alist struct))
19201 (orderedp (org-entry-get nil "ORDERED"))
19202 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19204 ;; Use a light version of `org-toggle-checkbox' to avoid
19205 ;; computing list structure twice.
19206 (let ((new-box (cond
19207 ((equal arg '(16)) "[-]")
19208 ((equal arg '(4)) nil)
19209 ((equal "[X]" cbox) "[ ]")
19211 (if (and firstp arg)
19212 ;; If at first item of sub-list, remove check-box from
19213 ;; every item at the same level.
19215 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19216 (org-list-get-all-items
19217 (point-at-bol) struct (org-list-prevs-alist struct)))
19218 (org-list-set-checkbox (point-at-bol) struct new-box)))
19219 ;; Replicate `org-list-write-struct', while grabbing a return
19220 ;; value from `org-list-struct-fix-box'.
19221 (org-list-struct-fix-ind struct parents 2)
19222 (org-list-struct-fix-item-end struct)
19223 (let ((prevs (org-list-prevs-alist struct)))
19224 (org-list-struct-fix-bul struct prevs)
19225 (org-list-struct-fix-ind struct parents)
19227 (org-list-struct-fix-box struct parents prevs orderedp)))
19228 (org-list-struct-apply-struct struct old-struct)
19229 (org-update-checkbox-count-maybe)
19232 "Checkboxes were removed due to unchecked box at line %d"
19233 (org-current-line block-item)))
19234 (when firstp (org-list-send-list 'maybe))))
19236 ;; Cursor at an item: repair list. Do checkbox related actions
19237 ;; only if function was called with an argument. Send list only
19239 (let* ((struct (org-list-struct))
19240 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19243 (setq old-struct (copy-tree struct))
19245 ;; If at first item of sub-list, add check-box to every
19246 ;; item at the same level.
19249 (unless (org-list-get-checkbox pos struct)
19250 (org-list-set-checkbox pos struct "[ ]")))
19251 (org-list-get-all-items
19252 (point-at-bol) struct (org-list-prevs-alist struct)))
19253 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19254 (org-list-write-struct
19255 struct (org-list-parents-alist struct) old-struct)
19256 (when arg (org-update-checkbox-count-maybe))
19257 (when firstp (org-list-send-list 'maybe))))
19258 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19260 (beginning-of-line 1)
19261 (save-excursion (org-update-dblock)))
19263 (let ((case-fold-search t))
19264 (beginning-of-line 1)
19265 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19267 ((or (equal (match-string 1) "TBLFM")
19268 (equal (match-string 1) "tblfm"))
19269 ;; Recalculate the table before this line
19271 (beginning-of-line 1)
19272 (skip-chars-backward " \r\n\t")
19273 (if (org-at-table-p)
19274 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19276 (let ((org-inhibit-startup-visibility-stuff t)
19277 (org-startup-align-all-tables nil))
19278 (when (boundp 'org-table-coordinate-overlays)
19279 (mapc 'delete-overlay org-table-coordinate-overlays)
19280 (setq org-table-coordinate-overlays nil))
19281 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19282 (message "Local setup has been refreshed"))))
19283 ((org-clock-update-time-maybe))
19285 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19286 (error "C-c C-c can do nothing useful at this location"))))))
19288 (defun org-mode-restart ()
19289 "Restart Org-mode, to scan again for special lines.
19290 Also updates the keyword regular expressions."
19293 (message "Org-mode restarted"))
19295 (defun org-kill-note-or-show-branches ()
19296 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19298 (if (not org-finish-function)
19301 (call-interactively 'show-branches))
19302 (let ((org-note-abort t))
19303 (funcall org-finish-function))))
19305 (defun org-return (&optional indent)
19306 "Goto next table row or insert a newline.
19307 Calls `org-table-next-row' or `newline', depending on context.
19308 See the individual commands for more information."
19312 ((or (bobp) (org-in-src-block-p))
19313 (if indent (newline-and-indent) (newline)))
19315 (org-table-justify-field-maybe)
19316 (call-interactively 'org-table-next-row))
19317 ;; when `newline-and-indent' is called within a list, make sure
19318 ;; text moved stays inside the item.
19319 ((and (org-in-item-p) indent)
19320 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19322 (save-match-data (newline))
19323 (org-indent-line-to (length (match-string 0))))
19324 (let ((ind (org-get-indentation)))
19326 (if (org-looking-back org-list-end-re)
19328 (org-indent-line-to ind)))))
19329 ((and org-return-follows-link
19330 (org-at-timestamp-p t)
19331 (not (eq org-ts-what 'after)))
19332 (org-follow-timestamp-link))
19333 ((and org-return-follows-link
19334 (let ((tprop (get-text-property (point) 'face)))
19335 (or (eq tprop 'org-link)
19336 (and (listp tprop) (memq 'org-link tprop)))))
19337 (call-interactively 'org-open-at-point))
19338 ((and (org-at-heading-p)
19340 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19344 (t (if indent (newline-and-indent) (newline))))))
19346 (defun org-return-indent ()
19347 "Goto next table row or insert a newline and indent.
19348 Calls `org-table-next-row' or `newline-and-indent', depending on
19349 context. See the individual commands for more information."
19353 (defun org-ctrl-c-star ()
19354 "Compute table, or change heading status of lines.
19355 Calls `org-table-recalculate' or `org-toggle-heading',
19356 depending on context."
19360 (call-interactively 'org-table-recalculate))
19362 ;; Convert all lines in region to list items
19363 (call-interactively 'org-toggle-heading))))
19365 (defun org-ctrl-c-minus ()
19366 "Insert separator line in table or modify bullet status of line.
19367 Also turns a plain line or a region of lines into list items.
19368 Calls `org-table-insert-hline', `org-toggle-item', or
19369 `org-cycle-list-bullet', depending on context."
19373 (call-interactively 'org-table-insert-hline))
19374 ((org-region-active-p)
19375 (call-interactively 'org-toggle-item))
19377 (call-interactively 'org-cycle-list-bullet))
19379 (call-interactively 'org-toggle-item))))
19381 (defun org-toggle-item (arg)
19382 "Convert headings or normal lines to items, items to normal lines.
19383 If there is no active region, only the current line is considered.
19385 If the first non blank line in the region is an headline, convert
19386 all headlines to items, shifting text accordingly.
19388 If it is an item, convert all items to normal lines.
19390 If it is normal text, change region into an item. With a prefix
19391 argument ARG, change each line in region into an item."
19395 ;; Shift text in current section to IND, from point to END.
19396 ;; The function leaves point to END line.
19398 (let ((min-i 1000) (end (copy-marker end)))
19399 ;; First determine the minimum indentation (MIN-I) of
19403 (while (< (point) end)
19404 (let ((i (org-get-indentation)))
19406 ;; Skip blank lines and inline tasks.
19407 ((looking-at "^[ \t]*$"))
19408 ((looking-at org-outline-regexp-bol))
19409 ;; We can't find less than 0 indentation.
19410 ((zerop i) (throw 'exit (setq min-i 0)))
19411 ((< i min-i) (setq min-i i))))
19413 ;; Then indent each line so that a line indented to
19414 ;; MIN-I becomes indented to IND. Ignore blank lines
19415 ;; and inline tasks in the process.
19416 (let ((delta (- ind min-i)))
19417 (while (< (point) end)
19418 (unless (or (looking-at "^[ \t]*$")
19419 (looking-at org-outline-regexp-bol))
19420 (org-indent-line-to (+ (org-get-indentation) delta)))
19421 (forward-line)))))))
19424 ;; Return beginning of first non-blank line, starting from
19429 (skip-chars-forward " \r\t\n")
19432 ;; Determine boundaries of changes.
19433 (if (org-region-active-p)
19434 (setq beg (funcall skip-blanks (region-beginning))
19435 end (copy-marker (region-end)))
19436 (setq beg (funcall skip-blanks (point-at-bol))
19437 end (copy-marker (point-at-eol))))
19438 ;; Depending on the starting line, choose an action on the text
19439 ;; between BEG and END.
19440 (org-with-limited-levels
19444 ;; Case 1. Start at an item: de-itemize. Note that it only
19445 ;; happens when a region is active: `org-ctrl-c-minus'
19446 ;; would call `org-cycle-list-bullet' otherwise.
19448 (while (< (point) end)
19449 (when (org-at-item-p)
19450 (skip-chars-forward " \t")
19451 (delete-region (point) (match-end 0)))
19453 ;; Case 2. Start at an heading: convert to items.
19454 ((org-at-heading-p)
19455 (let* ((bul (org-list-bullet-string "-"))
19456 (bul-len (length bul))
19457 ;; Indentation of the first heading. It should be
19458 ;; relative to the indentation of its parent, if any.
19459 (start-ind (save-excursion
19461 ((not org-adapt-indentation) 0)
19462 ((not (outline-previous-heading)) 0)
19463 (t (length (match-string 0))))))
19464 ;; Level of first heading. Further headings will be
19465 ;; compared to it to determine hierarchy in the list.
19466 (ref-level (org-reduced-level (org-outline-level))))
19467 (while (< (point) end)
19468 (let* ((level (org-reduced-level (org-outline-level)))
19469 (delta (max 0 (- level ref-level))))
19470 ;; If current headline is less indented than the first
19471 ;; one, set it as reference, in order to preserve
19473 (when (< level ref-level) (setq ref-level level))
19474 (replace-match bul t t)
19475 (org-indent-line-to (+ start-ind (* delta bul-len)))
19476 ;; Ensure all text down to END (or SECTION-END) belongs
19477 ;; to the newly created item.
19478 (let ((section-end (save-excursion
19479 (or (outline-next-heading) (point)))))
19481 (funcall shift-text
19482 (+ start-ind (* (1+ delta) bul-len))
19483 (min end section-end)))))))
19484 ;; Case 3. Normal line with ARG: turn each non-item line into
19487 (while (< (point) end)
19488 (unless (or (org-at-heading-p) (org-at-item-p))
19489 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19491 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19493 ;; Case 4. Normal line without ARG: make the first line of
19494 ;; region an item, and shift indentation of others
19495 ;; lines to set them as item's body.
19496 (t (let* ((bul (org-list-bullet-string "-"))
19497 (bul-len (length bul))
19498 (ref-ind (org-get-indentation)))
19499 (skip-chars-forward " \t")
19502 (while (< (point) end)
19503 ;; Ensure that lines less indented than first one
19504 ;; still get included in item body.
19505 (funcall shift-text
19506 (+ ref-ind bul-len)
19507 (min end (save-excursion (or (outline-next-heading)
19509 (forward-line)))))))))
19511 (defun org-toggle-heading (&optional nstars)
19512 "Convert headings to normal text, or items or text to headings.
19513 If there is no active region, only the current line is considered.
19515 With a \\[universal-argument] prefix, convert the whole list at
19516 point into heading.
19520 - If the first non blank line is an headline, remove the stars
19521 from all headlines in the region.
19523 - If it is a normal line turn each and every normal line (i.e. not an
19524 heading or an item) in the region into a heading.
19526 - If it is a plain list item, turn all plain list items into headings.
19528 When converting a line into a heading, the number of stars is chosen
19529 such that the lines become children of the current entry. However,
19530 when a prefix argument is given, its value determines the number of
19535 ;; Return beginning of first non-blank line, starting from
19540 (while (org-at-comment-p) (forward-line))
19541 (skip-chars-forward " \r\t\n")
19544 ;; Determine boundaries of changes. If a universal prefix has
19545 ;; been given, put the list in a region. If region ends at a bol,
19546 ;; do not consider the last line to be in the region.
19548 (when (and current-prefix-arg (org-at-item-p))
19549 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19550 (org-mark-element))
19552 (if (org-region-active-p)
19553 (setq beg (funcall skip-blanks (region-beginning))
19554 end (copy-marker (save-excursion
19555 (goto-char (region-end))
19556 (if (bolp) (point) (point-at-eol)))))
19557 (setq beg (funcall skip-blanks (point-at-bol))
19558 end (copy-marker (point-at-eol))))
19559 ;; Ensure inline tasks don't count as headings.
19560 (org-with-limited-levels
19564 ;; Case 1. Started at an heading: de-star headings.
19565 ((org-at-heading-p)
19566 (while (< (point) end)
19567 (when (org-at-heading-p t)
19568 (looking-at org-outline-regexp) (replace-match "")
19571 ;; Case 2. Started at an item: change items into headlines.
19572 ;; One star will be added by `org-list-to-subtree'.
19574 (let* ((stars (make-string
19576 ;; subtract the star that will be added again by
19577 ;; `org-list-to-subtree'
19578 (1- (prefix-numeric-value current-prefix-arg))
19579 (or (org-current-level) 0))
19582 (cond (nstars "") ; stars from prefix only
19583 ((equal stars "") "") ; before first heading
19584 (org-odd-levels-only "*") ; inside heading, odd
19585 (t "")))) ; inside heading, oddeven
19586 (while (< (point) end)
19587 (when (org-at-item-p)
19588 ;; Pay attention to cases when region ends before list.
19589 (let* ((struct (org-list-struct))
19590 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19592 (narrow-to-region (point) list-end)
19594 (org-list-to-subtree
19595 (org-list-parse-list t)
19596 '(:istart (concat stars add-stars (funcall get-stars depth))
19597 :icount (concat stars add-stars (funcall get-stars depth)))))))
19600 ;; Case 3. Started at normal text: make every line an heading,
19601 ;; skipping headlines and items.
19602 (t (let* ((stars (make-string
19604 (prefix-numeric-value current-prefix-arg)
19605 (or (org-current-level) 0))
19608 (cond (nstars "") ; stars from prefix only
19609 ((equal stars "") "*") ; before first heading
19610 (org-odd-levels-only "**") ; inside heading, odd
19611 (t "*"))) ; inside heading, oddeven
19612 (rpl (concat stars add-stars " ")))
19613 (while (< (point) end)
19614 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19615 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19616 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19617 (forward-line)))))))
19618 (unless toggled (message "Cannot toggle heading from here"))))
19620 (defun org-meta-return (&optional arg)
19621 "Insert a new heading or wrap a region in a table.
19622 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19623 See the individual commands for more information."
19626 ((run-hook-with-args-until-success 'org-metareturn-hook))
19627 ((or (org-at-drawer-p) (org-at-property-p))
19628 (newline-and-indent))
19630 (call-interactively 'org-table-wrap-region))
19631 (t (call-interactively 'org-insert-heading))))
19635 (defsubst org-in-subtree-not-table-p ()
19636 "Are we in a subtree and not in a table?"
19637 (and (not (org-before-first-heading-p))
19638 (not (org-at-table-p))))
19640 ;; Define the Org-mode menus
19641 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19643 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19644 ["Next Field" org-cycle (org-at-table-p)]
19645 ["Previous Field" org-shifttab (org-at-table-p)]
19646 ["Next Row" org-return (org-at-table-p)]
19648 ["Blank Field" org-table-blank-field (org-at-table-p)]
19649 ["Edit Field" org-table-edit-field (org-at-table-p)]
19650 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19653 ["Move Column Left" org-metaleft (org-at-table-p)]
19654 ["Move Column Right" org-metaright (org-at-table-p)]
19655 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19656 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19658 ["Move Row Up" org-metaup (org-at-table-p)]
19659 ["Move Row Down" org-metadown (org-at-table-p)]
19660 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19661 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19662 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19664 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19666 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19667 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19668 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19669 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19672 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19673 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19674 ["Edit Formulas" org-edit-special (org-at-table-p)]
19676 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19677 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19678 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19680 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19682 ["Sum Column/Rectangle" org-table-sum
19683 (or (org-at-table-p) (org-region-active-p))]
19684 ["Which Column?" org-table-current-column (org-at-table-p)])
19686 org-table-toggle-formula-debugger
19687 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19688 ["Show Col/Row Numbers"
19689 org-table-toggle-coordinate-overlays
19691 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19693 ["Create" org-table-create (and (not (org-at-table-p))
19694 org-enable-table-editor)]
19695 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19696 ["Import from File" org-table-import (not (org-at-table-p))]
19697 ["Export to File" org-table-export (org-at-table-p)]
19699 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19701 (easy-menu-define org-org-menu org-mode-map "Org menu"
19704 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19705 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19706 ["Sparse Tree..." org-sparse-tree t]
19707 ["Reveal Context" org-reveal t]
19708 ["Show All" show-all t]
19710 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19712 ["New Heading" org-insert-heading t]
19713 ("Navigate Headings"
19714 ["Up" outline-up-heading t]
19715 ["Next" outline-next-visible-heading t]
19716 ["Previous" outline-previous-visible-heading t]
19717 ["Next Same Level" outline-forward-same-level t]
19718 ["Previous Same Level" outline-backward-same-level t]
19720 ["Jump" org-goto t])
19722 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19724 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19725 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19727 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19728 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19729 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19731 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19733 ["Copy visible text" org-copy-visible t]
19735 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19736 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19737 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19738 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19740 ["Sort Region/Children" org-sort t]
19742 ["Convert to odd levels" org-convert-to-odd-levels t]
19743 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19745 ["Emphasis..." org-emphasize t]
19746 ["Edit Source Example" org-edit-special t]
19748 ["Footnote new/jump" org-footnote-action t]
19749 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19751 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19753 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19754 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19755 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19759 ["Store Link (Global)" org-store-link t]
19760 ["Find existing link to here" org-occur-link-in-agenda-files t]
19761 ["Insert Link" org-insert-link t]
19762 ["Follow Link" org-open-at-point t]
19764 ["Next link" org-next-link t]
19765 ["Previous link" org-previous-link t]
19767 ["Descriptive Links"
19768 org-toggle-link-display
19770 :selected org-descriptive-links
19773 org-toggle-link-display
19775 :selected (not org-descriptive-links)])
19778 ["TODO/DONE/-" org-todo t]
19780 ["Next keyword" org-shiftright (org-at-heading-p)]
19781 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19782 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19783 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19784 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19785 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19786 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19788 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19789 :selected org-enforce-todo-dependencies :style toggle :active t]
19790 "Settings for tree at point"
19791 ["Do Children sequentially" org-toggle-ordered-property :style radio
19792 :selected (org-entry-get nil "ORDERED")
19793 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19794 ["Do Children parallel" org-toggle-ordered-property :style radio
19795 :selected (not (org-entry-get nil "ORDERED"))
19796 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19798 ["Set Priority" org-priority t]
19799 ["Priority Up" org-shiftup t]
19800 ["Priority Down" org-shiftdown t]
19802 ["Get news from all feeds" org-feed-update-all t]
19803 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19804 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19805 ("TAGS and Properties"
19806 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19807 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19809 ["Set property" org-set-property (not (org-before-first-heading-p))]
19810 ["Column view of properties" org-columns t]
19811 ["Insert Column View DBlock" org-insert-columns-dblock t])
19812 ("Dates and Scheduling"
19813 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19814 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19816 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19817 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19818 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19819 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19820 ["Compute Time Range" org-evaluate-time-range t]
19821 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19822 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19824 ["Custom time format" org-toggle-time-stamp-overlays
19825 :style radio :selected org-display-custom-times]
19827 ["Goto Calendar" org-goto-calendar t]
19828 ["Date from Calendar" org-date-from-calendar t]
19830 ["Start/Restart Timer" org-timer-start t]
19831 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19832 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19833 ["Insert Timer String" org-timer t]
19834 ["Insert Timer Item" org-timer-item t])
19836 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19837 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19838 ["Clock out" org-clock-out t]
19839 ["Clock cancel" org-clock-cancel t]
19841 ["Mark as default task" org-clock-mark-default-task t]
19842 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19843 ["Goto running clock" org-clock-goto t]
19845 ["Display times" org-clock-display t]
19846 ["Create clock table" org-clock-report t]
19848 ["Record DONE time"
19849 (progn (setq org-log-done (not org-log-done))
19850 (message "Switching to %s will %s record a timestamp"
19851 (car org-done-keywords)
19852 (if org-log-done "automatically" "not")))
19853 :style toggle :selected org-log-done])
19855 ["Agenda Command..." org-agenda t]
19856 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19857 ("File List for Agenda")
19858 ("Special views current file"
19859 ["TODO Tree" org-show-todo-tree t]
19860 ["Check Deadlines" org-check-deadlines t]
19861 ["Timeline" org-timeline t]
19862 ["Tags/Property tree" org-match-sparse-tree t])
19864 ["Export/Publish..." org-export t]
19866 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19867 :selected org-cdlatex-mode]
19868 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19869 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19870 ["Modify math symbol" org-cdlatex-math-modify
19871 (org-inside-LaTeX-fragment-p)]
19872 ["Insert citation" org-reftex-citation t]
19874 ["Template for BEAMER" (progn (require 'org-beamer)
19875 (org-insert-beamer-options-template)) t])
19878 ["Push Files and Views" org-mobile-push t]
19879 ["Get Captured and Flagged" org-mobile-pull t]
19880 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19882 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19885 ["Show Version" org-version t]
19886 ["Info Documentation" org-info t])
19888 ["Browse Org Group" org-customize t]
19890 ["Expand This Menu" org-create-customize-menu
19891 (fboundp 'customize-menu-create)])
19892 ["Send bug report" org-submit-bug-report t]
19895 ["Refresh setup current buffer" org-mode-restart t]
19896 ["Reload Org (after update)" org-reload t]
19897 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19900 (defun org-info (&optional node)
19901 "Read documentation for Org-mode in the info system.
19902 With optional NODE, go directly to that node."
19904 (info (format "(org)%s" (or node ""))))
19907 (defun org-submit-bug-report ()
19908 "Submit a bug report on Org-mode via mail.
19910 Don't hesitate to report any problems or inaccurate documentation.
19912 If you don't have setup sending mail from (X)Emacs, please copy the
19913 output buffer into your mail program, as it gives us important
19914 information about your Org-mode version and configuration."
19916 (require 'reporter)
19917 (org-load-modules-maybe)
19918 (org-require-autoloaded-modules)
19919 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19920 (reporter-submit-bug-report
19921 "emacs-orgmode@gnu.org"
19922 (org-version nil 'full)
19924 (save-window-excursion
19925 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19926 (delete-other-windows)
19928 (insert "You are about to submit a bug report to the Org-mode mailing list.
19930 We would like to add your full Org-mode and Outline configuration to the
19931 bug report. This greatly simplifies the work of the maintainer and
19932 other experts on the mailing list.
19934 HOWEVER, some variables you have customized may contain private
19935 information. The names of customers, colleagues, or friends, might
19936 appear in the form of file names, tags, todo states, or search strings.
19937 If you answer yes to the prompt, you might want to check and remove
19938 such private information before sending the email.")
19939 (add-text-properties (point-min) (point-max) '(face org-warning))
19940 (when (yes-or-no-p "Include your Org-mode configuration ")
19944 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19945 (or (and (symbol-value v)
19946 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19948 (get v 'custom-type) (get v 'standard-value)
19949 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19951 (kill-buffer (get-buffer "*Warn about privacy*"))
19954 "Remember to cover the basics, that is, what you expected to happen and
19955 what in fact did happen. You don't know how to make a good report? See
19957 http://orgmode.org/manual/Feedback.html#Feedback
19959 Your bug report will be posted to the Org-mode mailing list.
19960 ------------------------------------------------------------------------")
19962 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19963 (replace-match "\\1Bug: \\3 [\\2]")))))
19966 (defun org-install-agenda-files-menu ()
19967 (let ((bl (buffer-list)))
19970 (set-buffer (pop bl))
19971 (if (derived-mode-p 'org-mode) (setq bl nil)))
19972 (when (derived-mode-p 'org-mode)
19974 '("Org") "File List for Agenda"
19977 ["Edit File List" (org-edit-agenda-file-list) t]
19978 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19979 ["Remove Current File from List" org-remove-file t]
19980 ["Cycle through agenda files" org-cycle-agenda-files t]
19981 ["Occur in all agenda files" org-occur-in-agenda-files t]
19983 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19987 (defun org-require-autoloaded-modules ()
19990 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19991 org-docbook org-exp org-html org-icalendar
19993 org-publish org-remember org-table
19994 org-timer org-xoxo)))
19997 (defun org-reload (&optional uncompiled)
19998 "Reload all org lisp files.
19999 With prefix arg UNCOMPILED, load the uncompiled versions."
20001 (require 'loadhist)
20002 (let* ((org-dir (org-find-library-dir "org"))
20003 (babel-dir (or (org-find-library-dir "ob") org-dir))
20004 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20005 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20006 (remove-re (mapconcat 'identity
20007 (mapcar (lambda (f) (concat "^" f "$"))
20008 (list (if (featurep 'xemacs)
20010 "org-colview-xemacs")
20011 "org" "org-loaddefs" "org-version"))
20013 (feats (delete-dups
20014 (mapcar 'file-name-sans-extension
20015 (mapcar 'file-name-nondirectory
20017 (mapcar 'feature-file
20024 (if (and (string-match feature-re f)
20025 (not (string-match remove-re f)))
20029 (list "org-version" "org")))
20030 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20034 (mapcar (lambda (f)
20036 (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20037 (unless (string= org-dir babel-dir)
20038 (load (concat babel-dir f) 'noerror nil nil 'mustsuffix))
20039 (unless (string= org-dir contrib-dir)
20040 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20041 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20042 ;; fallback to load-path, report as a possible error
20043 (message "Had to fall back onto load-path, something is not quite right...")
20046 (if (not load-misses)
20047 (message "Successfully reloaded Org\n%s" (org-version nil 'full))
20048 (message "Some error occured while reloading Org features\n%s\nPlease check *Messages*!\n%s"
20049 load-misses (org-version nil 'full)))))
20052 (defun org-customize ()
20053 "Call the customize function with org as argument."
20055 (org-load-modules-maybe)
20056 (org-require-autoloaded-modules)
20057 (customize-browse 'org))
20059 (defun org-create-customize-menu ()
20060 "Create a full customization menu for Org-mode, insert it into the menu."
20062 (org-load-modules-maybe)
20063 (org-require-autoloaded-modules)
20064 (if (fboundp 'customize-menu-create)
20067 '("Org") "Customize"
20068 `(["Browse Org group" org-customize t]
20070 ,(customize-menu-create 'org)
20071 ["Set" Custom-set t]
20072 ["Save" Custom-save t]
20073 ["Reset to Current" Custom-reset-current t]
20074 ["Reset to Saved" Custom-reset-saved t]
20075 ["Reset to Standard Settings" Custom-reset-standard t]))
20076 (message "\"Org\"-menu now contains full customization menu"))
20077 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20079 ;;;; Miscellaneous stuff
20081 ;;; Generally useful functions
20083 (defun org-get-at-bol (property)
20084 "Get text property PROPERTY at beginning of line."
20085 (get-text-property (point-at-bol) property))
20087 (defun org-find-text-property-in-string (prop s)
20088 "Return the first non-nil value of property PROP in string S."
20089 (or (get-text-property 0 prop s)
20090 (get-text-property (or (next-single-property-change 0 prop s) 0)
20093 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20094 "Display the given MESSAGE as a warning."
20095 (if (fboundp 'display-warning)
20096 (display-warning 'org message
20097 (if (featurep 'xemacs) 'warning :warning))
20098 (let ((buf (get-buffer-create "*Org warnings*")))
20099 (with-current-buffer buf
20100 (goto-char (point-max))
20101 (insert "Warning (Org): " message)
20104 (display-buffer buf)
20107 (defun org-eval (form)
20108 "Eval FORM and return result."
20109 (condition-case error
20111 (error (format "%%![Error: %s]" error))))
20113 (defun org-in-clocktable-p ()
20114 "Check if the cursor is in a clocktable."
20115 (let ((pos (point)) start)
20118 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20119 (setq start (match-beginning 0))
20120 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20121 (>= (match-end 0) pos)
20124 (defun org-in-commented-line ()
20125 "Is point in a line starting with `#'?"
20126 (equal (char-after (point-at-bol)) ?#))
20128 (defun org-in-indented-comment-line ()
20129 "Is point in a line starting with `#' after some white space?"
20132 (goto-char (point-at-bol))
20133 (looking-at "[ \t]*#"))))
20135 (defun org-in-verbatim-emphasis ()
20137 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20139 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20140 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20141 (if (and marker (marker-buffer marker)
20142 (buffer-live-p (marker-buffer marker)))
20144 (org-pop-to-buffer-same-window (marker-buffer marker))
20145 (if (or (> marker (point-max)) (< marker (point-min)))
20148 (org-show-context 'org-goto))
20150 (bookmark-jump bookmark)
20151 (error "Cannot find location"))))
20153 (defun org-quote-csv-field (s)
20154 "Quote field for inclusion in CSV material."
20155 (if (string-match "[\",]" s)
20156 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20159 (defun org-force-self-insert (N)
20160 "Needed to enforce self-insert under remapping."
20162 (self-insert-command N))
20164 (defun org-string-width (s)
20165 "Compute width of string, ignoring invisible characters.
20166 This ignores character with invisibility property `org-link', and also
20167 characters with property `org-cwidth', because these will become invisible
20168 upon the next fontification round."
20170 (when (or (eq t buffer-invisibility-spec)
20171 (assq 'org-link buffer-invisibility-spec))
20172 (while (setq b (text-property-any 0 (length s)
20173 'invisible 'org-link s))
20174 (setq s (concat (substring s 0 b)
20175 (substring s (or (next-single-property-change
20176 b 'invisible s) (length s)))))))
20177 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20178 (setq s (concat (substring s 0 b)
20179 (substring s (or (next-single-property-change
20180 b 'org-cwidth s) (length s))))))
20181 (setq l (string-width s) b -1)
20182 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20183 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20186 (defun org-shorten-string (s maxlength)
20187 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20188 If the string is shorter or has length MAXLENGTH, just return the
20189 original string. If it is longer, the functions finds a space in the
20190 string, breaks this string off at that locations and adds three dots
20191 as ellipsis. Including the ellipsis, the string will not be longer
20192 than MAXLENGTH. If finding a good breaking point in the string does
20193 not work, the string is just chopped off in the middle of a word
20195 (if (<= (length s) maxlength)
20197 (let* ((n (max (- maxlength 4) 1))
20198 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20199 (if (string-match re s)
20200 (concat (match-string 1 s) "...")
20201 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20203 (defun org-get-indentation (&optional line)
20204 "Get the indentation of the current line, interpreting tabs.
20205 When LINE is given, assume it represents a line and compute its indentation."
20207 (if (string-match "^ *" (org-remove-tabs line))
20210 (beginning-of-line 1)
20211 (skip-chars-forward " \t")
20212 (current-column))))
20214 (defun org-get-string-indentation (s)
20215 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20216 (let ((n -1) (i 0) (w tab-width) c)
20218 (while (< (setq n (1+ n)) (length s))
20219 (setq c (aref s n))
20220 (cond ((= c ?\ ) (setq i (1+ i)))
20221 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20222 (t (throw 'exit t)))))
20225 (defun org-remove-tabs (s &optional width)
20226 "Replace tabulators in S with spaces.
20227 Assumes that s is a single line, starting in column 0."
20228 (setq width (or width tab-width))
20229 (while (string-match "\t" s)
20230 (setq s (replace-match
20232 (- (* width (/ (+ (match-beginning 0) width) width))
20233 (match-beginning 0)) ?\ )
20237 (defun org-fix-indentation (line ind)
20238 "Fix indentation in LINE.
20239 IND is a cons cell with target and minimum indentation.
20240 If the current indentation in LINE is smaller than the minimum,
20241 leave it alone. If it is larger than ind, set it to the target."
20242 (let* ((l (org-remove-tabs line))
20243 (i (org-get-indentation l))
20244 (i1 (car ind)) (i2 (cdr ind)))
20245 (if (>= i i2) (setq l (substring line i2)))
20247 (concat (make-string i1 ?\ ) l)
20250 (defun org-remove-indentation (code &optional n)
20251 "Remove the maximum common indentation from the lines in CODE.
20252 N may optionally be the number of spaces to remove."
20255 (org-do-remove-indentation n)
20258 (defun org-do-remove-indentation (&optional n)
20259 "Remove the maximum common indentation from the buffer."
20260 (untabify (point-min) (point-max))
20261 (let ((min 10000) re)
20264 (goto-char (point-min))
20265 (while (re-search-forward "^ *[^ \n]" nil t)
20266 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20267 (unless (or (= min 0) (= min 10000))
20268 (setq re (format "^ \\{%d\\}" min))
20269 (goto-char (point-min))
20270 (while (re-search-forward re nil t)
20275 (defun org-fill-template (template alist)
20276 "Find each %key of ALIST in TEMPLATE and replace it."
20277 (let ((case-fold-search nil)
20279 (setq alist (sort (copy-sequence alist)
20280 (lambda (a b) (< (length (car a)) (length (car b))))))
20281 (while (setq entry (pop alist))
20283 (replace-regexp-in-string
20284 (concat "%" (regexp-quote (car entry)))
20285 (or (cdr entry) "") template t t)))
20288 (defun org-base-buffer (buffer)
20289 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20292 (or (buffer-base-buffer buffer)
20295 (defun org-trim (s)
20296 "Remove whitespace at beginning and end of string."
20297 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20298 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20301 (defun org-wrap (string &optional width lines)
20302 "Wrap string to either a number of lines, or a width in characters.
20303 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20304 that costs. If there is a word longer than WIDTH, the text is actually
20305 wrapped to the length of that word.
20306 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20307 many lines, whatever width that takes.
20308 The return value is a list of lines, without newlines at the end."
20309 (let* ((words (org-split-string string "[ \t\n]+"))
20310 (maxword (apply 'max (mapcar 'org-string-width words)))
20313 (org-do-wrap words (max maxword width)))
20316 (setq ll (org-do-wrap words maxword))
20317 (if (<= (length ll) lines)
20320 (while (> (length ll) lines)
20322 (setq ll (org-do-wrap words w)))
20324 (t (error "Cannot wrap this")))))
20326 (defun org-do-wrap (words width)
20327 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20330 (setq line (pop words))
20331 (while (and words (< (+ (length line) (length (car words))) width))
20332 (setq line (concat line " " (pop words))))
20333 (setq lines (push line lines)))
20336 (defun org-split-string (string &optional separators)
20337 "Splits STRING into substrings at SEPARATORS.
20338 No empty strings are returned if there are matches at the beginning
20339 and end of string."
20340 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20344 (while (and (string-match rexp string
20346 (= start (match-beginning 0))
20347 (< start (length string)))
20349 (< (match-beginning 0) (length string)))
20351 (or (eq (match-beginning 0) 0)
20352 (and (eq (match-beginning 0) (match-end 0))
20353 (eq (match-beginning 0) start))
20355 (cons (substring string start (match-beginning 0))
20357 (setq start (match-end 0)))
20358 (or (eq start (length string))
20360 (cons (substring string start)
20364 (defun org-quote-vert (s)
20365 "Replace \"|\" with \"\\vert\"."
20366 (while (string-match "|" s)
20367 (setq s (replace-match "\\vert" t t s)))
20370 (defun org-uuidgen-p (s)
20371 "Is S an ID created by UUIDGEN?"
20372 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20374 (defun org-in-src-block-p nil
20375 "Whether point is in a code source block."
20377 (when (setq ov (overlays-at (point)))
20378 (memq 'org-block-background
20379 (overlay-properties
20382 (defun org-context ()
20383 "Return a list of contexts of the current cursor position.
20384 If several contexts apply, all are returned.
20385 Each context entry is a list with a symbol naming the context, and
20386 two positions indicating start and end of the context. Possible
20389 :headline anywhere in a headline
20390 :headline-stars on the leading stars in a headline
20391 :todo-keyword on a TODO keyword (including DONE) in a headline
20392 :tags on the TAGS in a headline
20393 :priority on the priority cookie in a headline
20394 :item on the first line of a plain list item
20395 :item-bullet on the bullet/number of a plain list item
20396 :checkbox on the checkbox in a plain list item
20397 :table in an org-mode table
20398 :table-special on a special filed in a table
20399 :table-table in a table.el table
20400 :clocktable in a clocktable
20401 :src-block in a source block
20402 :link on a hyperlink
20403 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20404 :target on a <<target>>
20405 :radio-target on a <<<radio-target>>>
20406 :latex-fragment on a LaTeX fragment
20407 :latex-preview on a LaTeX fragment with overlaid preview image
20409 This function expects the position to be visible because it uses font-lock
20410 faces as a help to recognize the following contexts: :table-special, :link,
20412 (let* ((f (get-text-property (point) 'face))
20413 (faces (if (listp f) f (list f)))
20414 (case-fold-search t)
20415 (p (point)) clist o)
20416 ;; First the large context
20418 ((org-at-heading-p t)
20419 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20421 (beginning-of-line 1)
20422 (looking-at org-todo-line-tags-regexp))
20423 (push (org-point-in-group p 1 :headline-stars) clist)
20424 (push (org-point-in-group p 2 :todo-keyword) clist)
20425 (push (org-point-in-group p 4 :tags) clist))
20427 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20428 (if (looking-at "\\[#[A-Z0-9]\\]")
20429 (push (org-point-in-group p 0 :priority) clist)))
20432 (push (org-point-in-group p 2 :item-bullet) clist)
20433 (push (list :item (point-at-bol)
20434 (save-excursion (org-end-of-item) (point)))
20436 (and (org-at-item-checkbox-p)
20437 (push (org-point-in-group p 0 :checkbox) clist)))
20440 (push (list :table (org-table-begin) (org-table-end)) clist)
20441 (if (memq 'org-formula faces)
20442 (push (list :table-special
20443 (previous-single-property-change p 'face)
20444 (next-single-property-change p 'face)) clist)))
20445 ((org-at-table-p 'any)
20446 (push (list :table-table) clist)))
20449 (let ((case-fold-search t))
20450 ;; New the "medium" contexts: clocktables, source blocks
20451 (cond ((org-in-clocktable-p)
20452 (push (list :clocktable
20453 (and (or (looking-at "#\\+BEGIN: clocktable")
20454 (search-backward "#+BEGIN: clocktable" nil t))
20455 (match-beginning 0))
20456 (and (re-search-forward "#\\+END:?" nil t)
20457 (match-end 0))) clist))
20458 ((org-in-src-block-p)
20459 (push (list :src-block
20460 (and (or (looking-at "#\\+BEGIN_SRC")
20461 (search-backward "#+BEGIN_SRC" nil t))
20462 (match-beginning 0))
20463 (and (search-forward "#+END_SRC" nil t)
20464 (match-beginning 0))) clist))))
20467 ;; Now the small context
20469 ((org-at-timestamp-p)
20470 (push (org-point-in-group p 0 :timestamp) clist))
20471 ((memq 'org-link faces)
20473 (previous-single-property-change p 'face)
20474 (next-single-property-change p 'face)) clist))
20475 ((memq 'org-special-keyword faces)
20476 (push (list :keyword
20477 (previous-single-property-change p 'face)
20478 (next-single-property-change p 'face)) clist))
20480 (push (org-point-in-group p 0 :target) clist)
20481 (goto-char (1- (match-beginning 0)))
20482 (if (looking-at org-radio-target-regexp)
20483 (push (org-point-in-group p 0 :radio-target) clist))
20485 ((setq o (car (delq nil
20488 (if (memq x org-latex-fragment-image-overlays) x))
20489 (overlays-at (point))))))
20490 (push (list :latex-fragment
20491 (overlay-start o) (overlay-end o)) clist)
20492 (push (list :latex-preview
20493 (overlay-start o) (overlay-end o)) clist))
20494 ((org-inside-LaTeX-fragment-p)
20495 ;; FIXME: positions wrong.
20496 (push (list :latex-fragment (point) (point)) clist)))
20498 (setq clist (nreverse (delq nil clist)))
20501 ;; FIXME: Compare with at-regexp-p Do we need both?
20502 (defun org-in-regexp (re &optional nlines visually)
20503 "Check if point is inside a match of regexp.
20504 Normally only the current line is checked, but you can include NLINES extra
20505 lines both before and after point into the search.
20506 If VISUALLY is set, require that the cursor is not after the match but
20507 really on, so that the block visually is on the match."
20509 (let ((pos (point))
20510 (eol (point-at-eol (+ 1 (or nlines 0))))
20511 (inc (if visually 1 0)))
20513 (beginning-of-line (- 1 (or nlines 0)))
20514 (while (re-search-forward re eol t)
20515 (if (and (<= (match-beginning 0) pos)
20516 (>= (+ inc (match-end 0)) pos))
20517 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20519 (defun org-at-regexp-p (regexp)
20520 "Is point inside a match of REGEXP in the current line?"
20523 (let ((pos (point)) (end (point-at-eol)))
20524 (beginning-of-line 1)
20525 (while (re-search-forward regexp end t)
20526 (if (and (<= (match-beginning 0) pos)
20527 (>= (match-end 0) pos))
20531 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20532 "Non-nil when point is between matches of START-RE and END-RE.
20534 Also return a non-nil value when point is on one of the matches.
20536 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20537 buffer positions. Default values are the positions of headlines
20538 surrounding the point.
20540 The functions returns a cons cell whose car (resp. cdr) is the
20541 position before START-RE (resp. after END-RE)."
20543 (let ((pos (point))
20544 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20545 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20548 ;; Point is on a block when on START-RE or if START-RE can be
20549 ;; found before it...
20550 (and (or (org-at-regexp-p start-re)
20551 (re-search-backward start-re limit-up t))
20552 (setq beg (match-beginning 0))
20553 ;; ... and END-RE after it...
20554 (goto-char (match-end 0))
20555 (re-search-forward end-re limit-down t)
20556 (> (setq end (match-end 0)) pos)
20557 ;; ... without another START-RE in-between.
20558 (goto-char (match-beginning 0))
20559 (not (re-search-backward start-re (1+ beg) t))
20561 (cons beg end))))))
20563 (defun org-in-block-p (names)
20564 "Non-nil when point belongs to a block whose name belongs to NAMES.
20566 NAMES is a list of strings containing names of blocks.
20568 Return first block name matched, or nil. Beware that in case of
20569 nested blocks, the returned name may not belong to the closest
20573 (let ((case-fold-search t)
20574 (lim-up (save-excursion (outline-previous-heading)))
20575 (lim-down (save-excursion (outline-next-heading))))
20576 (mapc (lambda (name)
20577 (let ((n (regexp-quote name)))
20578 (when (org-between-regexps-p
20579 (concat "^[ \t]*#\\+begin_" n)
20580 (concat "^[ \t]*#\\+end_" n)
20586 (defun org-occur-in-agenda-files (regexp &optional nlines)
20587 "Call `multi-occur' with buffers for all agenda files."
20588 (interactive "sOrg-files matching: \np")
20589 (let* ((files (org-agenda-files))
20590 (tnames (mapcar 'file-truename files))
20591 (extra org-agenda-text-search-extra-files)
20593 (when (eq (car extra) 'agenda-archives)
20594 (setq extra (cdr extra))
20595 (setq files (org-add-archive-files files)))
20596 (while (setq f (pop extra))
20597 (unless (member (file-truename f) tnames)
20598 (add-to-list 'files f 'append)
20599 (add-to-list 'tnames (file-truename f) 'append)))
20601 (mapcar (lambda (x)
20602 (with-current-buffer
20603 (or (get-file-buffer x) (find-file-noselect x))
20609 (if (boundp 'occur-mode-find-occurrence-hook)
20611 (add-hook 'occur-mode-find-occurrence-hook
20613 (when (derived-mode-p 'org-mode)
20616 (defadvice occur-mode-goto-occurrence
20617 (after org-occur-reveal activate)
20618 (and (derived-mode-p 'org-mode) (org-reveal)))
20619 (defadvice occur-mode-goto-occurrence-other-window
20620 (after org-occur-reveal activate)
20621 (and (derived-mode-p 'org-mode) (org-reveal)))
20622 (defadvice occur-mode-display-occurrence
20623 (after org-occur-reveal activate)
20624 (when (derived-mode-p 'org-mode)
20625 (let ((pos (occur-mode-find-occurrence)))
20626 (with-current-buffer (marker-buffer pos)
20631 (defun org-occur-link-in-agenda-files ()
20632 "Create a link and search for it in the agendas.
20633 The link is not stored in `org-stored-links', it is just created
20634 for the search purpose."
20636 (let ((link (condition-case nil
20637 (org-store-link nil)
20638 (error "Unable to create a link to here"))))
20639 (org-occur-in-agenda-files (regexp-quote link))))
20641 (defun org-uniquify (list)
20642 "Remove duplicate elements from LIST."
20644 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20647 (defun org-delete-all (elts list)
20648 "Remove all elements in ELTS from LIST."
20650 (setq list (delete (pop elts) list)))
20653 (defun org-count (cl-item cl-seq)
20654 "Count the number of occurrences of ITEM in SEQ.
20655 Taken from `count' in cl-seq.el with all keyword arguments removed."
20656 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20657 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20658 (while (< cl-start cl-end)
20659 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20660 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20661 (setq cl-start (1+ cl-start)))
20664 (defun org-remove-if (predicate seq)
20665 "Remove everything from SEQ that fulfills PREDICATE."
20669 (if (not (funcall predicate e)) (push e res)))
20672 (defun org-remove-if-not (predicate seq)
20673 "Remove everything from SEQ that does not fulfill PREDICATE."
20677 (if (funcall predicate e) (push e res)))
20680 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20681 "Reduce two-argument FUNCTION across SEQ.
20682 Taken from `reduce' in cl-seq.el with all keyword arguments but
20683 \":initial-value\" removed."
20684 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20685 (cadr (memq :initial-value cl-keys)))
20686 (cl-seq (pop cl-seq))
20687 (t (funcall cl-func)))))
20689 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20692 (defun org-back-over-empty-lines ()
20693 "Move backwards over whitespace, to the beginning of the first empty line.
20694 Returns the number of empty lines passed."
20695 (let ((pos (point)))
20696 (if (cdr (assoc 'heading org-blank-before-new-entry))
20697 (skip-chars-backward " \t\n\r")
20699 (forward-line -1)))
20700 (beginning-of-line 2)
20701 (goto-char (min (point) pos))
20702 (count-lines (point) pos)))
20704 (defun org-skip-whitespace ()
20705 (skip-chars-forward " \t\n\r"))
20707 (defun org-point-in-group (point group &optional context)
20708 "Check if POINT is in match-group GROUP.
20709 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20710 match. If the match group does not exist or point is not inside it,
20712 (and (match-beginning group)
20713 (>= point (match-beginning group))
20714 (<= point (match-end group))
20716 (list context (match-beginning group) (match-end group))
20719 (defun org-switch-to-buffer-other-window (&rest args)
20720 "Switch to buffer in a second window on the current frame.
20721 In particular, do not allow pop-up frames.
20722 Returns the newly created buffer."
20723 (let (pop-up-frames special-display-buffer-names special-display-regexps
20724 special-display-function)
20725 (apply 'switch-to-buffer-other-window args)))
20727 (defun org-combine-plists (&rest plists)
20728 "Create a single property list from all plists in PLISTS.
20729 The process starts by copying the first list, and then setting properties
20730 from the other lists. Settings in the last list are the most significant
20731 ones and overrule settings in the other lists."
20732 (let ((rtn (copy-sequence (pop plists)))
20735 (setq ls (pop plists))
20737 (setq p (pop ls) v (pop ls))
20738 (setq rtn (plist-put rtn p v))))
20741 (defun org-replace-escapes (string table)
20742 "Replace %-escapes in STRING with values in TABLE.
20743 TABLE is an association list with keys like \"%a\" and string values.
20744 The sequences in STRING may contain normal field width and padding information,
20745 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20746 so values can contain further %-escapes if they are define later in TABLE."
20747 (let ((tbl (copy-alist table))
20748 (case-fold-search nil)
20751 (while (setq e (pop tbl))
20752 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20753 (when (and (cdr e) (string-match re (cdr e)))
20754 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20756 (add-text-properties 0 3 (list 'sref sref) safe)
20757 (setcdr e (replace-match safe t t (cdr e)))))
20758 (while (string-match re string)
20759 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20761 (setq string (replace-match rpl t t string))))
20762 (while (setq pchg (next-property-change pchg string))
20763 (let ((sref (get-text-property pchg 'sref string)))
20764 (when (and sref (string-match "SREF" string pchg))
20765 (setq string (replace-match sref t t string)))))
20768 (defun org-sublist (list start end)
20769 "Return a section of LIST, from START to END.
20770 Counting starts at 1."
20771 (let (rtn (c start))
20772 (setq list (nthcdr (1- start) list))
20773 (while (and list (<= c end))
20774 (push (pop list) rtn)
20778 (defun org-find-base-buffer-visiting (file)
20779 "Like `find-buffer-visiting' but always return the base buffer and
20780 not an indirect buffer."
20781 (let ((buf (or (get-file-buffer file)
20782 (find-buffer-visiting file))))
20784 (or (buffer-base-buffer buf) buf)
20787 (defun org-image-file-name-regexp (&optional extensions)
20788 "Return regexp matching the file names of images.
20789 If EXTENSIONS is given, only match these."
20790 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20791 (image-file-name-regexp)
20792 (let ((image-file-name-extensions
20794 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20795 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20797 (regexp-opt (nconc (mapcar 'upcase
20798 image-file-name-extensions)
20799 image-file-name-extensions)
20803 (defun org-file-image-p (file &optional extensions)
20804 "Return non-nil if FILE is an image."
20806 (string-match (org-image-file-name-regexp extensions) file)))
20808 (defun org-get-cursor-date ()
20809 "Return the date at cursor in as a time.
20810 This works in the calendar and in the agenda, anywhere else it just
20811 returns the current time."
20812 (let (date day defd)
20814 ((eq major-mode 'calendar-mode)
20815 (setq date (calendar-cursor-to-date)
20816 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20817 ((eq major-mode 'org-agenda-mode)
20818 (setq day (get-text-property (point) 'day))
20820 (setq date (calendar-gregorian-from-absolute day)
20821 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20823 (or defd (current-time))))
20825 (defun org-mark-subtree (&optional up)
20826 "Mark the current subtree.
20827 This puts point at the start of the current subtree, and mark at
20828 the end. If a numeric prefix UP is given, move up into the
20829 hierarchy of headlines by UP levels before marking the subtree."
20831 (org-with-limited-levels
20832 (cond ((org-at-heading-p) (beginning-of-line))
20833 ((org-before-first-heading-p) (error "Not in a subtree"))
20834 (t (outline-previous-visible-heading 1))))
20835 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20836 (if (org-called-interactively-p 'any)
20837 (call-interactively 'org-mark-element)
20838 (org-mark-element)))
20843 ;; Macros are expanded with `org-macro-replace-all', which relies
20844 ;; internally on `org-macro-expand'.
20846 ;; Default templates for expansion are stored in the buffer-local
20847 ;; variable `org-macro-templates'. This variable is updated by
20848 ;; `org-macro-initialize-templates'.
20850 ;; Along with macros defined through #+MACRO: keyword, default
20851 ;; templates include the following hard-coded macros:
20852 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
20853 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
20855 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
20856 ;; {{{title}}} will also be provided.
20859 (defvar org-macro-templates nil
20860 "Alist containing all macro templates in current buffer.
20861 Associations are in the shape of (NAME . TEMPLATE) where NAME
20862 stands for macro's name and template for its replacement value,
20863 both as strings. This is an internal variable. Do not set it
20864 directly, use instead:
20866 #+MACRO: name template")
20867 (make-variable-buffer-local 'org-macro-templates)
20869 (defun org-macro-expand (macro templates)
20870 "Return expanded MACRO, as a string.
20871 MACRO is an object, obtained, for example, with
20872 `org-element-context'. TEMPLATES is an alist of templates used
20873 for expansion. See `org-macro-templates' for a buffer-local
20874 default value. Return nil if no template was found."
20876 ;; Macro names are case-insensitive.
20877 (cdr (assoc-string (org-element-property :key macro) templates t))))
20879 (let ((value (replace-regexp-in-string
20882 (or (nth (1- (string-to-number (substring arg 1)))
20883 (org-element-property :args macro))
20884 ;; No argument provided: remove
20888 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20889 (when (string-match "\\`(eval\\>" value)
20890 (setq value (eval (read value))))
20892 (format "%s" (or value ""))))))
20894 (defun org-macro-replace-all (templates)
20895 "Replace all macros in current buffer by their expansion.
20896 TEMPLATES is an alist of templates used for expansion. See
20897 `org-macro-templates' for a buffer-local default value."
20899 (goto-char (point-min))
20900 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20901 (let ((object (org-element-context)))
20902 (when (eq (org-element-type object) 'macro)
20903 (let ((value (org-macro-expand object templates)))
20906 (org-element-property :begin object)
20907 ;; Preserve white spaces after the macro.
20908 (progn (goto-char (org-element-property :end object))
20909 (skip-chars-backward " \t")
20911 ;; Leave point before replacement in case of recursive
20913 (save-excursion (insert value)))))))))
20915 (defun org-macro-initialize-templates ()
20916 "Collect macro templates defined in current buffer.
20917 Templates are stored in buffer-local variable
20918 `org-macro-templates'. In addition to buffer-defined macros, the
20919 function installs the following ones: \"property\", \"date\",
20920 \"time\". and, if appropriate, \"input-file\" and
20921 \"modification-time\"."
20922 (let ((case-fold-search t)
20925 ;; Add CELL to `org-macro-templates' if there's no
20926 ;; association matching its name already. Otherwise,
20927 ;; replace old association with the new one in that
20929 (let ((old-template (assoc (car cell) org-macro-templates)))
20930 (if old-template (setcdr old-template (cdr cell))
20931 (push cell org-macro-templates))))))
20932 ;; Install buffer-local macros.
20933 (org-with-wide-buffer
20934 (goto-char (point-min))
20935 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20936 (let ((element (org-element-at-point)))
20937 (when (eq (org-element-type element) 'keyword)
20938 (let ((value (org-element-property :value element)))
20939 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20940 (funcall set-template
20941 (cons (match-string 1 value)
20942 (or (match-string 2 value) "")))))))))
20943 ;; Install hard-coded macros.
20944 (mapc (lambda (cell) (funcall set-template cell))
20946 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20947 (cons "time" "(eval (format-time-string \"$1\"))")))
20948 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
20949 (when (and visited-file (file-exists-p visited-file))
20950 (mapc (lambda (cell) (funcall set-template cell))
20952 (cons "input-file" (file-name-nondirectory visited-file))
20953 (cons "modification-time"
20954 (format "(eval (format-time-string \"$1\" '%s))"
20956 (nth 5 (file-attributes visited-file)))))))))))
20961 (defun org-indent-line ()
20962 "Indent line depending on context."
20964 (let* ((pos (point))
20965 (itemp (org-at-item-p))
20966 (case-fold-search t)
20967 (org-drawer-regexp (or org-drawer-regexp "\000"))
20968 (inline-task-p (and (featurep 'org-inlinetask)
20969 (org-inlinetask-in-task-p)))
20970 (inline-re (and inline-task-p
20971 (org-inlinetask-outline-regexp)))
20973 (if (and orgstruct-is-++ (eq pos (point)))
20974 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20975 (indent-according-to-mode))
20976 (beginning-of-line 1)
20979 ((looking-at org-outline-regexp) (setq column 0))
20981 ((looking-at "#\\+include:") (setq column 0))
20982 ;; Footnote definition
20983 ((looking-at org-footnote-definition-re) (setq column 0))
20984 ;; Literal examples
20985 ((looking-at "[ \t]*:\\( \\|$\\)")
20986 (setq column (org-get-indentation))) ; do nothing
20988 ((ignore-errors (goto-char (org-in-item-p)))
20989 (setq column (if itemp
20990 (org-get-indentation)
20991 (org-list-item-body-column (point))))
20994 ((and (looking-at "[ \t]*:END:")
20995 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20997 (goto-char (1- (match-beginning 1)))
20998 (setq column (current-column))))
21000 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21002 (re-search-backward
21003 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21004 (setq column (org-get-indentation (match-string 0))))
21005 ((and (not (looking-at "[ \t]*#\\+begin_"))
21006 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21008 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21010 (cond ((equal (downcase (match-string 1)) "src")
21011 ;; src blocks: let `org-edit-src-exit' handle them
21012 (org-get-indentation))
21013 ((equal (downcase (match-string 1)) "example")
21014 (max (org-get-indentation)
21015 (org-get-indentation (match-string 0))))
21017 (org-get-indentation (match-string 0))))))
21018 ;; This line has nothing special, look at the previous relevant
21019 ;; line to compute indentation
21021 (beginning-of-line 0)
21022 (while (and (not (bobp))
21023 (not (looking-at org-drawer-regexp))
21024 ;; When point started in an inline task, do not move
21025 ;; above task starting line.
21026 (not (and inline-task-p (looking-at inline-re)))
21027 ;; Skip drawers, blocks, empty lines, verbatim,
21028 ;; comments, tables, footnotes definitions, lists,
21030 (or (and (looking-at "[ \t]*:END:")
21031 (re-search-backward org-drawer-regexp nil t))
21032 (and (looking-at "[ \t]*#\\+end_")
21033 (re-search-backward "[ \t]*#\\+begin_"nil t))
21034 (looking-at "[ \t]*[\n:#|]")
21035 (looking-at org-footnote-definition-re)
21036 (and (ignore-errors (goto-char (org-in-item-p)))
21038 (org-list-get-top-point (org-list-struct))))
21039 (and (not inline-task-p)
21040 (featurep 'org-inlinetask)
21041 (org-inlinetask-in-task-p)
21042 (or (org-inlinetask-goto-beginning) t))))
21043 (beginning-of-line 0))
21045 ;; There was an heading above.
21046 ((looking-at "\\*+[ \t]+")
21047 (if (not org-adapt-indentation)
21049 (goto-char (match-end 0))
21050 (setq column (current-column))))
21051 ;; A drawer had started and is unfinished
21052 ((looking-at org-drawer-regexp)
21053 (goto-char (1- (match-beginning 1)))
21054 (setq column (current-column)))
21055 ;; Else, nothing noticeable found: get indentation and go on.
21056 (t (setq column (org-get-indentation))))))
21057 ;; Now apply indentation and move cursor accordingly
21059 (if (<= (current-column) (current-indentation))
21060 (org-indent-line-to column)
21061 (save-excursion (org-indent-line-to column)))
21062 ;; Special polishing for properties, see `org-property-format'
21063 (setq column (current-column))
21064 (beginning-of-line 1)
21066 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21067 (replace-match (concat (match-string 1)
21068 (format org-property-format
21069 (match-string 2) (match-string 3)))
21071 (org-move-to-column column))))
21073 (defun org-indent-drawer ()
21074 "Indent the drawer at point."
21077 (e (and (save-excursion (re-search-forward ":END:" nil t))
21082 (when (overlays-at (point))
21083 (member 'invisible (overlay-properties
21084 (car (overlays-at (point)))))))))
21085 (when folded (org-cycle))
21086 (indent-for-tab-command)
21087 (while (and (move-beginning-of-line 2) (< (point) e))
21088 (indent-for-tab-command))
21090 (when folded (org-cycle)))
21091 (message "Drawer at point indented"))
21093 (defun org-indent-block ()
21094 "Indent the block at point."
21097 (case-fold-search t)
21098 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21103 (when (overlays-at (point))
21104 (member 'invisible (overlay-properties
21105 (car (overlays-at (point)))))))))
21106 (when folded (org-cycle))
21107 (indent-for-tab-command)
21108 (while (and (move-beginning-of-line 2) (< (point) e))
21109 (indent-for-tab-command))
21111 (when folded (org-cycle)))
21112 (message "Block at point indented"))
21114 (defun org-indent-region (start end)
21118 (let ((line-end (org-current-line end)))
21120 (while (< (org-current-line) line-end)
21121 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21122 (t (call-interactively 'org-indent-line)))
21123 (move-beginning-of-line 2)))))
21128 ;; We use our own fill-paragraph and auto-fill functions.
21130 ;; `org-fill-paragraph' relies on adaptive filling and context
21131 ;; checking. Appropriate `fill-prefix' is computed with
21132 ;; `org-adaptive-fill-function'.
21134 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21135 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21136 ;; `org-adaptive-fill-function' value. Internally,
21137 ;; `org-comment-line-break-function' breaks the line.
21139 ;; `org-setup-filling' installs filling and auto-filling related
21140 ;; variables during `org-mode' initialization.
21142 (defun org-setup-filling ()
21144 ;; Prevent auto-fill from inserting unwanted new items.
21145 (when (boundp 'fill-nobreak-predicate)
21147 'fill-nobreak-predicate
21149 (append fill-nobreak-predicate
21150 '(org-fill-paragraph-separate-nobreak-p
21151 org-fill-line-break-nobreak-p)))))
21152 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21153 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21154 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21155 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21157 (defvar org-element-paragraph-separate) ; org-element.el
21158 (defun org-fill-paragraph-separate-nobreak-p ()
21159 "Non-nil when a line break at point would insert a new item."
21160 (looking-at (substring org-element-paragraph-separate 1)))
21162 (defun org-fill-line-break-nobreak-p ()
21163 "Non-nil when a line break at point would create an Org line break."
21165 (skip-chars-backward "[ \t]")
21166 (skip-chars-backward "\\\\")
21167 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21169 (declare-function message-in-body-p "message" ())
21170 (defvar org-element--affiliated-re) ; From org-element.el
21171 (defun org-adaptive-fill-function ()
21172 "Compute a fill prefix for the current line.
21173 Return fill prefix, as a string, or nil if current line isn't
21174 meant to be filled."
21175 (org-with-wide-buffer
21176 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21177 ;; FIXME: This is really the job of orgstruct++-mode
21178 (let* ((p (line-beginning-position))
21179 (element (save-excursion (beginning-of-line)
21180 (org-element-at-point)))
21181 (type (org-element-type element))
21184 (goto-char (org-element-property :begin element))
21185 (while (looking-at org-element--affiliated-re) (forward-line))
21187 (unless (< p post-affiliated)
21189 (comment (looking-at "[ \t]*# ?") (match-string 0))
21190 (footnote-definition "")
21192 (make-string (org-list-item-body-column post-affiliated) ? ))
21194 ;; Fill prefix is usually the same as the current line,
21195 ;; except if the paragraph is at the beginning of an item.
21196 (let ((parent (org-element-property :parent element)))
21197 (cond ((eq (org-element-type parent) 'item)
21198 (make-string (org-list-item-body-column
21199 (org-element-property :begin parent))
21201 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21205 ;; Only fill contents if P is within block boundaries.
21206 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21209 (cend (save-excursion
21210 (goto-char (org-element-property :end element))
21211 (skip-chars-backward " \r\t\n")
21212 (line-beginning-position))))
21213 (when (and (>= p cbeg) (< p cend))
21214 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21218 (declare-function message-goto-body "message" ())
21219 (defvar message-cite-prefix-regexp) ; From message.el
21220 (defvar org-element-all-objects) ; From org-element.el
21221 (defun org-fill-paragraph (&optional justify)
21222 "Fill element at point, when applicable.
21224 This function only applies to comment blocks, comments, example
21225 blocks and paragraphs. Also, as a special case, re-align table
21226 when point is at one.
21228 If JUSTIFY is non-nil (interactively, with prefix argument),
21229 justify as well. If `sentence-end-double-space' is non-nil, then
21230 period followed by one space does not end a sentence, so don't
21231 break a line there. The variable `fill-column' controls the
21234 For convenience, when point is at a plain list, an item or
21235 a footnote definition, try to fill the first paragraph within."
21236 ;; Falls back on message-fill-paragraph when necessary
21238 (if (and (derived-mode-p 'message-mode)
21239 (or (not (message-in-body-p))
21240 (save-excursion (move-beginning-of-line 1)
21241 (looking-at message-cite-prefix-regexp))))
21242 (let ((fill-paragraph-function
21243 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21244 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21245 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21246 (paragraph-separate
21247 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21248 (fill-paragraph nil))
21250 ;; Move to end of line in order to get the first paragraph
21251 ;; within a plain list or a footnote definition.
21253 (let ((element (org-element-at-point)))
21254 ;; First check if point is in a blank line at the beginning of
21255 ;; the buffer. In that case, ignore filling.
21256 (if (< (point) (org-element-property :begin element)) t
21257 (case (org-element-type element)
21258 ;; Align Org tables, leave table.el tables as-is.
21259 (table-row (org-table-align) t)
21261 (when (eq (org-element-property :type element) 'org)
21265 ;; Paragraphs may contain `line-break' type objects.
21266 (let ((beg (max (point-min)
21267 (org-element-property :contents-begin element)))
21268 (end (min (point-max)
21269 (org-element-property :contents-end element))))
21270 ;; Do nothing if point is at an affiliated keyword.
21271 (if (< (point) beg) t
21272 (when (derived-mode-p 'message-mode)
21273 ;; In `message-mode', do not fill following
21274 ;; citation in current paragraph nor text before
21276 (let ((body-start (save-excursion (message-goto-body))))
21277 (when body-start (setq beg (max body-start beg))))
21278 (when (save-excursion
21280 (concat "^" message-cite-prefix-regexp) end t))
21281 (setq end (match-beginning 0))))
21282 ;; Fill paragraph, taking line breaks into
21283 ;; consideration. For that, slice the paragraph
21284 ;; using line breaks as separators, and fill the
21285 ;; parts in reverse order to avoid messing with
21291 (fill-region-as-paragraph pos (point) justify)
21293 ;; Find the list of ending positions for line
21294 ;; breaks in the current paragraph. Add paragraph
21295 ;; beginning to include first slice.
21300 (org-element--parse-objects
21301 beg end nil org-element-all-objects)
21303 (lambda (lb) (org-element-property :end lb)))))))
21305 ;; Contents of `comment-block' type elements should be
21306 ;; filled as plain text, but only if point is within block
21309 (let* ((case-fold-search t)
21310 (beg (save-excursion
21311 (goto-char (org-element-property :begin element))
21312 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21315 (end (save-excursion
21316 (goto-char (org-element-property :end element))
21317 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21318 (line-beginning-position))))
21319 (when (and (>= (point) beg) (< (point) end))
21320 (fill-region-as-paragraph
21323 (re-search-backward "^[ \t]*$" beg 'move)
21324 (line-beginning-position))
21326 (beginning-of-line)
21327 (re-search-forward "^[ \t]*$" end 'move)
21328 (line-beginning-position))
21332 (comment (fill-comment-paragraph justify))
21333 ;; Ignore every other element.
21334 (otherwise t)))))))
21336 (defun org-auto-fill-function ()
21337 "Auto-fill function."
21338 ;; Check if auto-filling is meaningful.
21339 (let ((fc (current-fill-column)))
21340 (when (and fc (> (current-column) fc))
21341 (let ((fill-prefix (org-adaptive-fill-function)))
21342 (when fill-prefix (do-auto-fill))))))
21344 (defun org-comment-line-break-function (&optional soft)
21345 "Break line at point and indent, continuing comment if within one.
21346 The inserted newline is marked hard if variable
21347 `use-hard-newlines' is true, unless optional argument SOFT is
21349 (if soft (insert-and-inherit ?\n) (newline 1))
21350 (save-excursion (forward-char -1) (delete-horizontal-space))
21351 (delete-horizontal-space)
21352 (indent-to-left-margin)
21353 (insert-before-markers-and-inherit fill-prefix))
21358 ;; Org comments syntax is quite complex. It requires the entire line
21359 ;; to be just a comment. Also, even with the right syntax at the
21360 ;; beginning of line, some some elements (i.e. verse-block or
21361 ;; example-block) don't accept comments. Usual Emacs comment commands
21362 ;; cannot cope with those requirements. Therefore, Org replaces them.
21364 ;; Org still relies on `comment-dwim', but cannot trust
21365 ;; `comment-only-p'. So, `comment-region-function' and
21366 ;; `uncomment-region-function' both point
21367 ;; to`org-comment-or-uncomment-region'. Eventually,
21368 ;; `org-insert-comment' takes care of insertion of comments at the
21369 ;; beginning of line.
21371 ;; `org-setup-comments-handling' install comments related variables
21372 ;; during `org-mode' initialization.
21374 (defun org-setup-comments-handling ()
21376 (org-set-local 'comment-use-syntax nil)
21377 (org-set-local 'comment-start "# ")
21378 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21379 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21380 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21381 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21383 (defun org-insert-comment ()
21384 "Insert an empty comment above current line.
21385 If the line is empty, insert comment at its beginning."
21386 (beginning-of-line)
21387 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21391 (defvar comment-empty-lines) ; From newcomment.el.
21392 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21393 "Comment or uncomment each non-blank line in the region.
21394 Uncomment each non-blank line between BEG and END if it only
21395 contains commented lines. Otherwise, comment them."
21398 (narrow-to-region (save-excursion (goto-char beg)
21399 (skip-chars-forward " \r\t\n" end)
21400 (line-beginning-position))
21401 (save-excursion (goto-char end)
21402 (skip-chars-backward " \r\t\n" beg)
21403 (line-end-position)))
21405 ;; UNCOMMENTP is non-nil when every non blank line between
21406 ;; BEG and END is a comment.
21408 (goto-char (point-min))
21409 (while (and (not (eobp))
21410 (let ((element (org-element-at-point)))
21411 (and (eq (org-element-type element) 'comment)
21412 (goto-char (min (point-max)
21413 (org-element-property
21414 :end element)))))))
21417 ;; Only blank lines and comments in region: uncomment it.
21419 (goto-char (point-min))
21420 (while (not (eobp))
21421 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21422 (replace-match "" nil nil nil 1))
21424 ;; Comment each line in region.
21425 (let ((min-indent (point-max)))
21426 ;; First find the minimum indentation across all lines.
21428 (goto-char (point-min))
21429 (while (and (not (eobp)) (not (zerop min-indent)))
21430 (unless (looking-at "[ \t]*$")
21431 (setq min-indent (min min-indent (current-indentation))))
21433 ;; Then loop over all lines.
21435 (goto-char (point-min))
21436 (while (not (eobp))
21437 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21438 (org-move-to-column min-indent t)
21439 (insert comment-start))
21440 (forward-line))))))))
21445 (defun org-toggle-fixed-width-section (arg)
21446 "Toggle the fixed-width export.
21447 If there is no active region, the QUOTE keyword at the current headline is
21448 inserted or removed. When present, it causes the text between this headline
21449 and the next to be exported as fixed-width text, and unmodified.
21450 If there is an active region, this command adds or removes a colon as the
21451 first character of this line. If the first character of a line is a colon,
21452 this line is also exported in fixed-width font."
21455 (regionp (org-region-active-p))
21456 (beg (if regionp (region-beginning) (point)))
21457 (end (if regionp (region-end)))
21458 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21459 (case-fold-search nil)
21460 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21465 (setq cc (current-column))
21466 (beginning-of-line 1)
21467 (setq off (looking-at re))
21468 (while (> nlines 0)
21469 (setq nlines (1- nlines))
21470 (beginning-of-line 1)
21473 (org-move-to-column cc t)
21476 ((and off (looking-at re))
21477 (replace-match "" t t nil 1))
21478 ((not off) (org-move-to-column cc t) (insert ": ")))
21481 (org-back-to-heading)
21483 ((looking-at (format org-heading-keyword-regexp-format
21485 (goto-char (match-end 1))
21486 (looking-at (concat " +" org-quote-string))
21487 (replace-match "" t t)
21488 (when (eolp) (insert " ")))
21489 ((looking-at org-outline-regexp)
21490 (goto-char (match-end 0))
21491 (insert org-quote-string " ")))))))
21493 (defun org-reftex-citation ()
21494 "Use reftex-citation to insert a citation into the buffer.
21495 This looks for a line like
21497 #+BIBLIOGRAPHY: foo plain option:-d
21499 and derives from it that foo.bib is the bibliography file relevant
21500 for this document. It then installs the necessary environment for RefTeX
21501 to work in this buffer and calls `reftex-citation' to insert a citation
21504 Export of such citations to both LaTeX and HTML is handled by the contributed
21505 package org-exp-bibtex by Taru Karttunen."
21507 (let ((reftex-docstruct-symbol 'rds)
21508 (reftex-cite-format "\\cite{%l}")
21513 (let ((case-fold-search t)
21514 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21515 (if (not (save-excursion
21516 (or (re-search-forward re nil t)
21517 (re-search-backward re nil t))))
21518 (error "No bibliography defined in file")
21519 (setq bib (concat (match-string 1) ".bib")
21520 rds (list (list 'bib bib)))))))
21521 (call-interactively 'reftex-citation)))
21523 ;;;; Functions extending outline functionality
21525 (defun org-beginning-of-line (&optional arg)
21526 "Go to the beginning of the current line. If that is invisible, continue
21527 to a visible line beginning. This makes the function of C-a more intuitive.
21528 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21529 first attempt, and only move to after the tags when the cursor is already
21530 beyond the end of the headline."
21532 (let ((pos (point))
21533 (special (if (consp org-special-ctrl-a/e)
21534 (car org-special-ctrl-a/e)
21535 org-special-ctrl-a/e))
21537 (if (org-bound-and-true-p line-move-visual)
21538 (beginning-of-visual-line 1)
21539 (beginning-of-line 1))
21540 (if (and arg (fboundp 'move-beginning-of-line))
21541 (call-interactively 'move-beginning-of-line)
21545 (if (org-truely-invisible-p)
21546 (while (and (not (bobp)) (org-truely-invisible-p))
21548 (beginning-of-line 1))
21549 (forward-char 1))))
21552 ((and (looking-at org-complex-heading-regexp)
21553 (= (char-after (match-end 1)) ?\ ))
21554 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21558 (cond ((> pos refpos) refpos)
21559 ((= pos (point)) refpos)
21561 (cond ((> pos (point)) (point))
21562 ((not (eq last-command this-command)) (point))
21565 ;; Being at an item and not looking at an the item means point
21566 ;; was previously moved to beginning of a visual line, which
21567 ;; doesn't contain the item. Therefore, do nothing special,
21569 (when (looking-at org-list-full-item-re)
21570 ;; Set special position at first white space character after
21571 ;; bullet, and check-box, if any.
21572 (let ((after-bullet
21573 (let ((box (match-end 3)))
21574 (if (not box) (match-end 1)
21575 (let ((after (char-after box)))
21576 (if (and after (= after ? )) (1+ box) box))))))
21577 ;; Special case: Move point to special position when
21578 ;; currently after it or at beginning of line.
21580 (when (or (> pos after-bullet) (= (point) pos))
21581 (goto-char after-bullet))
21582 ;; Reversed case: Move point to special position when
21583 ;; point was already at beginning of line and command is
21585 (when (and (= (point) pos) (eq last-command this-command))
21586 (goto-char after-bullet))))))))
21588 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21590 (defun org-end-of-line (&optional arg)
21591 "Go to the end of the line.
21592 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21593 first attempt, and only move to after the tags when the cursor is already
21594 beyond the end of the headline."
21596 (let ((special (if (consp org-special-ctrl-a/e)
21597 (cdr org-special-ctrl-a/e)
21598 org-special-ctrl-a/e)))
21600 ((or (not special) arg
21601 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21602 (call-interactively
21603 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21604 ((fboundp 'move-end-of-line) 'move-end-of-line)
21605 (t 'end-of-line))))
21606 ((org-at-heading-p)
21607 (let ((pos (point)))
21608 (beginning-of-line 1)
21609 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21611 (if (or (< pos (match-beginning 1))
21612 (= pos (match-end 0)))
21613 (goto-char (match-beginning 1))
21614 (goto-char (match-end 0)))
21615 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21616 (goto-char (match-end 0))
21617 (goto-char (match-beginning 1))))
21618 (call-interactively (if (fboundp 'move-end-of-line)
21622 (move-end-of-line 1)
21623 (when (overlays-at (1- (point))) (backward-char 1)))
21624 ;; At an item: Move before any hidden text.
21625 (t (call-interactively
21626 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21627 ((fboundp 'move-end-of-line) 'move-end-of-line)
21628 (t 'end-of-line)))))
21630 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21632 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21633 (define-key org-mode-map "\C-e" 'org-end-of-line)
21635 (defun org-backward-sentence (&optional arg)
21636 "Go to beginning of sentence, or beginning of table field.
21637 This will call `backward-sentence' or `org-table-beginning-of-field',
21638 depending on context."
21641 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21642 (t (call-interactively 'backward-sentence))))
21644 (defun org-forward-sentence (&optional arg)
21645 "Go to end of sentence, or end of table field.
21646 This will call `forward-sentence' or `org-table-end-of-field',
21647 depending on context."
21650 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21651 (t (call-interactively 'forward-sentence))))
21653 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21654 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21656 (defun org-kill-line (&optional arg)
21657 "Kill line, to tags or end of line."
21660 ((or (not org-special-ctrl-k)
21662 (not (org-at-heading-p)))
21663 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21664 org-ctrl-k-protect-subtree)
21665 (if (or (eq org-ctrl-k-protect-subtree 'error)
21666 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21667 (error "C-k aborted - would kill hidden subtree")))
21668 (call-interactively
21669 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21670 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21671 (kill-region (point) (match-beginning 1))
21672 (org-set-tags nil t))
21673 (t (kill-region (point) (point-at-eol)))))
21675 (define-key org-mode-map "\C-k" 'org-kill-line)
21677 (defun org-yank (&optional arg)
21678 "Yank. If the kill is a subtree, treat it specially.
21679 This command will look at the current kill and check if is a single
21680 subtree, or a series of subtrees[1]. If it passes the test, and if the
21681 cursor is at the beginning of a line or after the stars of a currently
21682 empty headline, then the yank is handled specially. How exactly depends
21683 on the value of the following variables, both set by default.
21685 org-yank-folded-subtrees
21686 When set, the subtree(s) will be folded after insertion, but only
21687 if doing so would now swallow text after the yanked text.
21689 org-yank-adjusted-subtrees
21690 When set, the subtree will be promoted or demoted in order to
21691 fit into the local outline tree structure, which means that the level
21692 will be adjusted so that it becomes the smaller one of the two
21693 *visible* surrounding headings.
21695 Any prefix to this command will cause `yank' to be called directly with
21696 no special treatment. In particular, a simple \\[universal-argument] prefix \
21698 plainly yank the text as it is.
21700 \[1] The test checks if the first non-white line is a heading
21701 and if there are no other headings with fewer stars."
21703 (org-yank-generic 'yank arg))
21705 (defun org-yank-generic (command arg)
21706 "Perform some yank-like command.
21708 This function implements the behavior described in the `org-yank'
21709 documentation. However, it has been generalized to work for any
21710 interactive command with similar behavior."
21712 ;; pretend to be command COMMAND
21713 (setq this-command command)
21716 (call-interactively command)
21718 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21719 (and (org-kill-is-subtree-p)
21721 (and (looking-at "[ \t]*$")
21724 (buffer-substring (point-at-bol) (point)))))))
21727 ((and subtreep org-yank-folded-subtrees)
21728 (let ((beg (point))
21730 (if (and subtreep org-yank-adjusted-subtrees)
21731 (org-paste-subtree nil nil 'for-yank)
21732 (call-interactively command))
21736 (when (and (bolp) subtreep
21737 (not (setq swallowp
21738 (org-yank-folding-would-swallow-text beg end))))
21739 (org-with-limited-levels
21740 (or (looking-at org-outline-regexp)
21741 (re-search-forward org-outline-regexp-bol end t))
21742 (while (and (< (point) end) (looking-at org-outline-regexp))
21744 (org-cycle-show-empty-lines 'folded)
21745 (condition-case nil
21746 (outline-forward-same-level 1)
21747 (error (goto-char end))))))
21750 "Inserted text not folded because that would swallow text"))
21753 (skip-chars-forward " \t\n\r")
21754 (beginning-of-line 1)
21755 (push-mark beg 'nomsg)))
21756 ((and subtreep org-yank-adjusted-subtrees)
21757 (let ((beg (point-at-bol)))
21758 (org-paste-subtree nil nil 'for-yank)
21759 (push-mark beg 'nomsg)))
21761 (call-interactively command))))))
21763 (defun org-yank-folding-would-swallow-text (beg end)
21764 "Would hide-subtree at BEG swallow any text after END?"
21766 (org-with-limited-levels
21769 (when (or (looking-at org-outline-regexp)
21770 (re-search-forward org-outline-regexp-bol end t))
21771 (setq level (org-outline-level)))
21773 (skip-chars-forward " \t\r\n\v\f")
21775 (and (bolp) (looking-at org-outline-regexp)
21776 (<= (org-outline-level) level)))
21777 nil ; Nothing would be swallowed
21778 t))))) ; something would swallow
21780 (define-key org-mode-map "\C-y" 'org-yank)
21782 (defun org-truely-invisible-p ()
21783 "Check if point is at a character currently not visible.
21784 This version does not only check the character property, but also
21786 ;; Early versions of noutline don't have `outline-invisible-p'.
21787 (if (org-bound-and-true-p visible-mode)
21789 (outline-invisible-p)))
21791 (defun org-invisible-p2 ()
21792 "Check if point is at a character currently not visible."
21794 (if (and (eolp) (not (bobp))) (backward-char 1))
21795 ;; Early versions of noutline don't have `outline-invisible-p'.
21796 (outline-invisible-p)))
21798 (defun org-back-to-heading (&optional invisible-ok)
21799 "Call `outline-back-to-heading', but provide a better error message."
21800 (condition-case nil
21801 (outline-back-to-heading invisible-ok)
21802 (error (error "Before first headline at position %d in buffer %s"
21803 (point) (current-buffer)))))
21805 (defun org-before-first-heading-p ()
21806 "Before first heading?"
21809 (null (re-search-backward org-outline-regexp-bol nil t))))
21811 (defun org-at-heading-p (&optional ignored)
21812 (outline-on-heading-p t))
21813 ;; Compatibility alias with Org versions < 7.8.03
21814 (defalias 'org-on-heading-p 'org-at-heading-p)
21816 (defun org-at-comment-p nil
21817 "Is cursor in a line starting with a # character?"
21819 (beginning-of-line)
21820 (looking-at "^#")))
21822 (defun org-at-drawer-p nil
21823 "Is cursor at a drawer keyword?"
21825 (move-beginning-of-line 1)
21826 (looking-at org-drawer-regexp)))
21828 (defun org-at-block-p nil
21829 "Is cursor at a block keyword?"
21831 (move-beginning-of-line 1)
21832 (looking-at org-block-regexp)))
21834 (defun org-point-at-end-of-empty-headline ()
21835 "If point is at the end of an empty headline, return t, else nil.
21836 If the heading only contains a TODO keyword, it is still still considered
21838 (and (looking-at "[ \t]*$")
21839 (when org-todo-line-regexp
21841 (beginning-of-line 1)
21842 (let ((case-fold-search nil))
21843 (looking-at org-todo-line-regexp)
21844 (string= (match-string 3) ""))))))
21846 (defun org-at-heading-or-item-p ()
21847 (or (org-at-heading-p) (org-at-item-p)))
21849 (defun org-at-target-p ()
21850 (or (org-in-regexp org-radio-target-regexp)
21851 (org-in-regexp org-target-regexp)))
21852 ;; Compatibility alias with Org versions < 7.8.03
21853 (defalias 'org-on-target-p 'org-at-target-p)
21855 (defun org-up-heading-all (arg)
21856 "Move to the heading line of which the present line is a subheading.
21857 This function considers both visible and invisible heading lines.
21858 With argument, move up ARG levels."
21859 (if (fboundp 'outline-up-heading-all)
21860 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21861 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21863 (defun org-up-heading-safe ()
21864 "Move to the heading line of which the present line is a subheading.
21865 This version will not throw an error. It will return the level of the
21866 headline found, or nil if no higher level is found.
21868 Also, this function will be a lot faster than `outline-up-heading',
21869 because it relies on stars being the outline starters. This can really
21870 make a significant difference in outlines with very many siblings."
21871 (let (start-level re)
21872 (org-back-to-heading t)
21873 (setq start-level (funcall outline-level))
21874 (if (equal start-level 1)
21876 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21877 (if (re-search-backward re nil t)
21878 (funcall outline-level)))))
21880 (defun org-first-sibling-p ()
21881 "Is this heading the first child of its parents?"
21883 (let ((re org-outline-regexp-bol)
21885 (unless (org-at-heading-p t)
21886 (error "Not at a heading"))
21887 (setq level (funcall outline-level))
21889 (if (not (re-search-backward re nil t))
21891 (setq l (funcall outline-level))
21894 (defun org-goto-sibling (&optional previous)
21895 "Goto the next sibling, even if it is invisible.
21896 When PREVIOUS is set, go to the previous sibling instead. Returns t
21897 when a sibling was found. When none is found, return nil and don't
21899 (let ((fun (if previous 're-search-backward 're-search-forward))
21901 (re org-outline-regexp-bol)
21903 (when (condition-case nil (org-back-to-heading t) (error nil))
21904 (setq level (funcall outline-level))
21906 (or previous (forward-char 1))
21907 (while (funcall fun re nil t)
21908 (setq l (funcall outline-level))
21909 (when (< l level) (goto-char pos) (throw 'exit nil))
21910 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21914 (defun org-show-siblings ()
21915 "Show all siblings of the current headline."
21917 (while (org-goto-sibling) (org-flag-heading nil)))
21919 (while (org-goto-sibling 'previous)
21920 (org-flag-heading nil))))
21922 (defun org-goto-first-child ()
21923 "Goto the first child, even if it is invisible.
21924 Return t when a child was found. Otherwise don't move point and
21926 (let (level (pos (point)) (re org-outline-regexp-bol))
21927 (when (condition-case nil (org-back-to-heading t) (error nil))
21928 (setq level (outline-level))
21930 (if (and (re-search-forward re nil t) (> (outline-level) level))
21931 (progn (goto-char (match-beginning 0)) t)
21932 (goto-char pos) nil))))
21934 (defun org-show-hidden-entry ()
21935 "Show an entry where even the heading is hidden."
21939 (defun org-flag-heading (flag &optional entry)
21940 "Flag the current heading. FLAG non-nil means make invisible.
21941 When ENTRY is non-nil, show the entire entry."
21943 (org-back-to-heading t)
21944 ;; Check if we should show the entire entry
21949 (and (outline-next-heading)
21950 (org-flag-heading nil))))
21951 (outline-flag-region (max (point-min) (1- (point)))
21952 (save-excursion (outline-end-of-heading) (point))
21955 (defun org-get-next-sibling ()
21956 "Move to next heading of the same level, and return point.
21957 If there is no such heading, return nil.
21958 This is like outline-next-sibling, but invisible headings are ok."
21959 (let ((level (funcall outline-level)))
21960 (outline-next-heading)
21961 (while (and (not (eobp)) (> (funcall outline-level) level))
21962 (outline-next-heading))
21963 (if (or (eobp) (< (funcall outline-level) level))
21967 (defun org-get-last-sibling ()
21968 "Move to previous heading of the same level, and return point.
21969 If there is no such heading, return nil."
21970 (let ((opoint (point))
21971 (level (funcall outline-level)))
21972 (outline-previous-heading)
21973 (when (and (/= (point) opoint) (outline-on-heading-p t))
21974 (while (and (> (funcall outline-level) level)
21976 (outline-previous-heading))
21977 (if (< (funcall outline-level) level)
21981 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21982 "Goto to the end of a subtree."
21983 ;; This contains an exact copy of the original function, but it uses
21984 ;; `org-back-to-heading', to make it work also in invisible
21985 ;; trees. And is uses an invisible-ok argument.
21986 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21987 ;; Furthermore, when used inside Org, finding the end of a large subtree
21988 ;; with many children and grandchildren etc, this can be much faster
21989 ;; than the outline version.
21990 (org-back-to-heading invisible-ok)
21992 (level (funcall outline-level)))
21993 (if (and (derived-mode-p 'org-mode) (< level 1000))
21994 ;; A true heading (not a plain list item), in Org-mode
21995 ;; This means we can easily find the end by looking
21996 ;; only for the right number of stars. Using a regexp to do
21997 ;; this is so much faster than using a Lisp loop.
21998 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22000 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22001 ;; something else, do it the slow way
22002 (while (and (not (eobp))
22003 (or first (> (funcall outline-level) level)))
22005 (outline-next-heading)))
22007 (if (memq (preceding-char) '(?\n ?\^M))
22009 ;; Go to end of line before heading
22011 (if (memq (preceding-char) '(?\n ?\^M))
22012 ;; leave blank line before heading
22013 (forward-char -1))))))
22016 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22017 "Use Org version in org-mode, for dramatic speed-up."
22018 (if (derived-mode-p 'org-mode)
22020 (org-end-of-subtree nil t)
22021 (unless (eobp) (backward-char 1)))
22024 (defun org-end-of-meta-data-and-drawers ()
22025 "Jump to the first text after meta data and drawers in the current entry.
22026 This will move over empty lines, lines with planning time stamps,
22027 clocking lines, and drawers."
22028 (org-back-to-heading t)
22029 (let ((end (save-excursion (outline-next-heading) (point)))
22030 (re (concat "\\(" org-drawer-regexp "\\)"
22031 "\\|" "[ \t]*" org-keyword-time-regexp)))
22033 (while (re-search-forward re end t)
22034 (if (not (match-end 1))
22035 ;; empty or planning line
22037 ;; a drawer, find the end
22038 (re-search-forward "^[ \t]*:END:" end 'move)
22040 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22043 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22044 "Move forward to the arg'th subheading at same level as this one.
22045 Stop at the first and last subheadings of a superior heading.
22046 Normally this only looks at visible headings, but when INVISIBLE-OK is
22047 non-nil it will also look at invisible ones."
22049 (org-back-to-heading invisible-ok)
22051 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22052 (re (format "^\\*\\{1,%d\\} " level))
22056 (while (and (re-search-forward re nil 'move)
22057 (setq l (- (match-end 0) (match-beginning 0) 1))
22060 (progn (backward-char 1) (outline-invisible-p)))
22061 (if (< l level) (setq arg 1)))
22062 (setq arg (1- arg)))
22063 (beginning-of-line 1)))
22065 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22066 "Move backward to the arg'th subheading at same level as this one.
22067 Stop at the first and last subheadings of a superior heading."
22069 (org-back-to-heading)
22071 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22072 (re (format "^\\*\\{1,%d\\} " level))
22075 (while (and (re-search-backward re nil 'move)
22076 (setq l (- (match-end 0) (match-beginning 0) 1))
22079 (outline-invisible-p))
22080 (if (< l level) (setq arg 1)))
22081 (setq arg (1- arg)))))
22083 (defun org-forward-element ()
22084 "Move forward by one element.
22085 Move to the next element at the same level, when possible."
22087 (cond ((eobp) (error "Cannot move further down"))
22088 ((org-with-limited-levels (org-at-heading-p))
22089 (let ((origin (point)))
22090 (org-forward-heading-same-level 1)
22091 (unless (org-with-limited-levels (org-at-heading-p))
22093 (error "Cannot move further down"))))
22095 (let* ((elem (org-element-at-point))
22096 (end (org-element-property :end elem))
22097 (parent (org-element-property :parent elem)))
22098 (if (and parent (= (org-element-property :contents-end parent) end))
22099 (goto-char (org-element-property :end parent))
22100 (goto-char end))))))
22102 (defun org-backward-element ()
22103 "Move backward by one element.
22104 Move to the previous element at the same level, when possible."
22106 (cond ((bobp) (error "Cannot move further up"))
22107 ((org-with-limited-levels (org-at-heading-p))
22108 ;; At an headline, move to the previous one, if any, or stay
22110 (let ((origin (point)))
22111 (org-backward-heading-same-level 1)
22112 (unless (org-with-limited-levels (org-at-heading-p))
22114 (error "Cannot move further up"))))
22116 (let* ((trail (org-element-at-point 'keep-trail))
22118 (prev-elem (nth 1 trail))
22119 (beg (org-element-property :begin elem)))
22121 ;; Move to beginning of current element if point isn't
22123 ((/= (point) beg) (goto-char beg))
22124 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22125 ((org-before-first-heading-p) (goto-char (point-min)))
22126 (t (org-back-to-heading)))))))
22128 (defun org-up-element ()
22129 "Move to upper element."
22131 (if (org-with-limited-levels (org-at-heading-p))
22132 (unless (org-up-heading-safe) (error "No surrounding element"))
22133 (let* ((elem (org-element-at-point))
22134 (parent (org-element-property :parent elem)))
22135 (if parent (goto-char (org-element-property :begin parent))
22136 (if (org-with-limited-levels (org-before-first-heading-p))
22137 (error "No surrounding element")
22138 (org-with-limited-levels (org-back-to-heading)))))))
22140 (defvar org-element-greater-elements)
22141 (defun org-down-element ()
22142 "Move to inner element."
22144 (let ((element (org-element-at-point)))
22146 ((memq (org-element-type element) '(plain-list table))
22147 (goto-char (org-element-property :contents-begin element))
22149 ((memq (org-element-type element) org-element-greater-elements)
22150 ;; If contents are hidden, first disclose them.
22151 (when (org-element-property :hiddenp element) (org-cycle))
22152 (goto-char (or (org-element-property :contents-begin element)
22153 (error "No content for this element"))))
22154 (t (error "No inner element")))))
22156 (defun org-drag-element-backward ()
22157 "Move backward element at point."
22159 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22160 (let* ((trail (org-element-at-point 'keep-trail))
22162 (prev-elem (nth 1 trail)))
22163 ;; Error out if no previous element or previous element is
22164 ;; a parent of the current one.
22165 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22166 (error "Cannot drag element backward")
22167 (let ((pos (point)))
22168 (org-element-swap-A-B prev-elem elem)
22169 (goto-char (+ (org-element-property :begin prev-elem)
22170 (- pos (org-element-property :begin elem)))))))))
22172 (defun org-drag-element-forward ()
22173 "Move forward element at point."
22175 (let* ((pos (point))
22176 (elem (org-element-at-point)))
22177 (when (= (point-max) (org-element-property :end elem))
22178 (error "Cannot drag element forward"))
22179 (goto-char (org-element-property :end elem))
22180 (let ((next-elem (org-element-at-point)))
22181 (when (or (org-element-nested-p elem next-elem)
22182 (and (eq (org-element-type next-elem) 'headline)
22183 (not (eq (org-element-type elem) 'headline))))
22185 (error "Cannot drag element forward"))
22186 ;; Compute new position of point: it's shifted by NEXT-ELEM
22187 ;; body's length (without final blanks) and by the length of
22188 ;; blanks between ELEM and NEXT-ELEM.
22189 (let ((size-next (- (save-excursion
22190 (goto-char (org-element-property :end next-elem))
22191 (skip-chars-backward " \r\t\n")
22193 ;; Small correction if buffer doesn't end
22194 ;; with a newline character.
22195 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22196 (org-element-property :begin next-elem)))
22197 (size-blank (- (org-element-property :end elem)
22199 (goto-char (org-element-property :end elem))
22200 (skip-chars-backward " \r\t\n")
22203 (org-element-swap-A-B elem next-elem)
22204 (goto-char (+ pos size-next size-blank))))))
22206 (defun org-mark-element ()
22207 "Put point at beginning of this element, mark at end.
22209 Interactively, if this command is repeated or (in Transient Mark
22210 mode) if the mark is active, it marks the next element after the
22211 ones already marked."
22213 (let (deactivate-mark)
22214 (if (and (org-called-interactively-p 'any)
22215 (or (and (eq last-command this-command) (mark t))
22216 (and transient-mark-mode mark-active)))
22220 (goto-char (org-element-property :end (org-element-at-point)))))
22221 (let ((element (org-element-at-point)))
22223 (push-mark (org-element-property :end element) t t)
22224 (goto-char (org-element-property :begin element))))))
22226 (defun org-narrow-to-element ()
22227 "Narrow buffer to current element."
22229 (let ((elem (org-element-at-point)))
22231 ((eq (car elem) 'headline)
22233 (org-element-property :begin elem)
22234 (org-element-property :end elem)))
22235 ((memq (car elem) org-element-greater-elements)
22237 (org-element-property :contents-begin elem)
22238 (org-element-property :contents-end elem)))
22241 (org-element-property :begin elem)
22242 (org-element-property :end elem))))))
22244 (defun org-transpose-element ()
22245 "Transpose current and previous elements, keeping blank lines between.
22246 Point is moved after both elements."
22248 (org-skip-whitespace)
22249 (let ((end (org-element-property :end (org-element-at-point))))
22250 (org-drag-element-backward)
22253 (defun org-unindent-buffer ()
22254 "Un-indent the visible part of the buffer.
22255 Relative indentation (between items, inside blocks, etc.) isn't
22258 (unless (eq major-mode 'org-mode)
22259 (error "Cannot un-indent a buffer not in Org mode"))
22260 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22261 unindent-tree ; For byte-compiler.
22267 (if (memq (org-element-type element) '(headline section))
22268 (funcall unindent-tree (org-element-contents element))
22272 (org-element-property :begin element)
22273 (org-element-property :end element))
22274 (org-do-remove-indentation)))))
22275 (reverse contents))))))
22276 (funcall unindent-tree (org-element-contents parse-tree))))
22278 (defun org-show-subtree ()
22279 "Show everything after this heading at deeper levels."
22281 (outline-flag-region
22284 (org-end-of-subtree t t))
22287 (defun org-show-entry ()
22288 "Show the body directly following this heading.
22289 Show the heading too, if it is currently invisible."
22292 (condition-case nil
22294 (org-back-to-heading t)
22295 (outline-flag-region
22296 (max (point-min) (1- (point)))
22298 (if (re-search-forward
22299 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22300 (match-beginning 1)
22303 (org-cycle-hide-drawers 'children))
22306 (defun org-make-options-regexp (kwds &optional extra)
22307 "Make a regular expression for keyword lines."
22310 (mapconcat 'regexp-quote kwds "\\|")
22311 (if extra (concat "\\|" extra))
22312 "\\):[ \t]*\\(.*\\)"))
22314 ;; Make isearch reveal the necessary context
22315 (defun org-isearch-end ()
22316 "Reveal context after isearch exits."
22317 (when isearch-success ; only if search was successful
22318 (if (featurep 'xemacs)
22319 ;; Under XEmacs, the hook is run in the correct place,
22320 ;; we directly show the context.
22321 (org-show-context 'isearch)
22322 ;; In Emacs the hook runs *before* restoring the overlays.
22323 ;; So we have to use a one-time post-command-hook to do this.
22324 ;; (Emacs 22 has a special variable, see function `org-mode')
22325 (unless (and (boundp 'isearch-mode-end-hook-quit)
22326 isearch-mode-end-hook-quit)
22327 ;; Only when the isearch was not quitted.
22328 (org-add-hook 'post-command-hook 'org-isearch-post-command
22329 'append 'local)))))
22331 (defun org-isearch-post-command ()
22332 "Remove self from hook, and show context."
22333 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22334 (org-show-context 'isearch))
22337 ;;;; Integration with and fixes for other packages
22341 (defvar org-imenu-markers nil
22342 "All markers currently used by Imenu.")
22343 (make-variable-buffer-local 'org-imenu-markers)
22345 (defun org-imenu-new-marker (&optional pos)
22346 "Return a new marker for use by Imenu, and remember the marker."
22347 (let ((m (make-marker)))
22348 (move-marker m (or pos (point)))
22349 (push m org-imenu-markers)
22352 (defun org-imenu-get-tree ()
22353 "Produce the index for Imenu."
22354 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22355 (setq org-imenu-markers nil)
22356 (let* ((n org-imenu-depth)
22357 (re (concat "^" (org-get-limited-outline-regexp)))
22358 (subs (make-vector (1+ n) nil))
22364 (goto-char (point-max))
22365 (while (re-search-backward re nil t)
22366 (setq level (org-reduced-level (funcall outline-level)))
22367 (when (and (<= level n)
22368 (looking-at org-complex-heading-regexp))
22369 (setq head (org-link-display-format
22370 (org-match-string-no-properties 4))
22371 m (org-imenu-new-marker))
22372 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22373 (if (>= level last-level)
22374 (push (cons head m) (aref subs level))
22375 (push (cons head (aref subs (1+ level))) (aref subs level))
22376 (loop for i from (1+ level) to n do (aset subs i nil)))
22377 (setq last-level level)))))
22380 (eval-after-load "imenu"
22382 (add-hook 'imenu-after-jump-hook
22384 (if (derived-mode-p 'org-mode)
22385 (org-show-context 'org-goto))))))
22387 (defun org-link-display-format (link)
22388 "Replace a link with either the description, or the link target
22389 if no description is present"
22391 (if (string-match org-bracket-link-analytic-regexp link)
22392 (replace-match (if (match-end 5)
22393 (match-string 5 link)
22394 (concat (match-string 1 link)
22395 (match-string 3 link)))
22399 (defun org-toggle-link-display ()
22400 "Toggle the literal or descriptive display of links."
22402 (if org-descriptive-links
22403 (progn (org-remove-from-invisibility-spec '(org-link))
22404 (org-restart-font-lock)
22405 (setq org-descriptive-links nil))
22406 (progn (add-to-invisibility-spec '(org-link))
22407 (org-restart-font-lock)
22408 (setq org-descriptive-links t))))
22410 ;; Speedbar support
22412 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22413 "Overlay marking the agenda restriction line in speedbar.")
22414 (overlay-put org-speedbar-restriction-lock-overlay
22415 'face 'org-agenda-restriction-lock)
22416 (overlay-put org-speedbar-restriction-lock-overlay
22417 'help-echo "Agendas are currently limited to this item.")
22418 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22420 (defun org-speedbar-set-agenda-restriction ()
22421 "Restrict future agenda commands to the location at point in speedbar.
22422 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22424 (require 'org-agenda)
22425 (let (p m tp np dir txt)
22427 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22429 (setq m (get-text-property p 'org-imenu-marker))
22430 (with-current-buffer (marker-buffer m)
22432 (org-agenda-set-restriction-lock 'subtree)))
22433 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22434 'speedbar-function 'speedbar-find-file))
22435 (setq tp (previous-single-property-change
22436 (1+ p) 'speedbar-function)
22437 np (next-single-property-change
22438 tp 'speedbar-function)
22439 dir (speedbar-line-directory)
22440 txt (buffer-substring-no-properties (or tp (point-min))
22441 (or np (point-max))))
22442 (with-current-buffer (find-file-noselect
22443 (let ((default-directory dir))
22444 (expand-file-name txt)))
22445 (unless (derived-mode-p 'org-mode)
22446 (error "Cannot restrict to non-Org-mode file"))
22447 (org-agenda-set-restriction-lock 'file)))
22448 (t (error "Don't know how to restrict Org-mode's agenda")))
22449 (move-overlay org-speedbar-restriction-lock-overlay
22450 (point-at-bol) (point-at-eol))
22451 (setq current-prefix-arg nil)
22452 (org-agenda-maybe-redo)))
22454 (eval-after-load "speedbar"
22456 (speedbar-add-supported-extension ".org")
22457 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22458 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22459 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22460 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22461 (add-hook 'speedbar-visiting-tag-hook
22462 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22464 ;;; Fixes and Hacks for problems with other packages
22466 ;; Make flyspell not check words in links, to not mess up our keymap
22467 (defun org-mode-flyspell-verify ()
22468 "Don't let flyspell put overlays at active buttons, or on
22469 {todo,all-time,additional-option-like}-keywords."
22470 (let ((pos (max (1- (point)) (point-min)))
22471 (word (thing-at-point 'word)))
22472 (and (not (get-text-property pos 'keymap))
22473 (not (get-text-property pos 'org-no-flyspell))
22474 (not (member word org-todo-keywords-1))
22475 (not (member word org-all-time-keywords))
22476 (not (member word org-options-keywords))
22477 (not (member word (mapcar 'car org-startup-options)))
22478 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22480 (defun org-remove-flyspell-overlays-in (beg end)
22481 "Remove flyspell overlays in region."
22482 (and (org-bound-and-true-p flyspell-mode)
22483 (fboundp 'flyspell-delete-region-overlays)
22484 (flyspell-delete-region-overlays beg end))
22485 (add-text-properties beg end '(org-no-flyspell t)))
22487 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22488 (eval-after-load "bookmark"
22489 '(if (boundp 'bookmark-after-jump-hook)
22490 ;; We can use the hook
22491 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22492 ;; Hook not available, use advice
22493 (defadvice bookmark-jump (after org-make-visible activate)
22494 "Make the position visible."
22495 (org-bookmark-jump-unhide))))
22497 ;; Make sure saveplace shows the location if it was hidden
22498 (eval-after-load "saveplace"
22499 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22500 "Make the position visible."
22501 (org-bookmark-jump-unhide)))
22503 ;; Make sure ecb shows the location if it was hidden
22504 (eval-after-load "ecb"
22505 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22506 "Make hierarchy visible when jumping into location from ECB tree buffer."
22507 (if (derived-mode-p 'org-mode)
22508 (org-show-context))))
22510 (defun org-bookmark-jump-unhide ()
22511 "Unhide the current position, to show the bookmark location."
22512 (and (derived-mode-p 'org-mode)
22513 (or (outline-invisible-p)
22514 (save-excursion (goto-char (max (point-min) (1- (point))))
22515 (outline-invisible-p)))
22516 (org-show-context 'bookmark-jump)))
22518 ;; Make session.el ignore our circular variable
22519 (eval-after-load "session"
22520 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22522 ;;;; Experimental code
22524 (defun org-closed-in-range ()
22525 "Sparse tree of items closed in a certain time range.
22526 Still experimental, may disappear in the future."
22528 ;; Get the time interval from the user.
22529 (let* ((time1 (org-float-time
22530 (org-read-date nil 'to-time nil "Starting date: ")))
22531 (time2 (org-float-time
22532 (org-read-date nil 'to-time nil "End date:")))
22533 ;; callback function
22534 (callback (lambda ()
22537 (apply 'encode-time
22538 (org-parse-time-string
22539 (match-string 1))))))
22540 ;; check if time in interval
22541 (and (>= time time1) (<= time time2))))))
22542 ;; make tree, check each match with the callback
22543 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22549 (run-hooks 'org-load-hook)
22551 ;;; org.el ends here