org.el (org-mode): Try to set the org-hide face correctly
[org-mode.git] / lisp / org.el
blob79eddeb5aebbe674ceff209610b9baf00e84fbbc
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.
5 ;;
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
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
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
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
64 ;;; Code:
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
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
118 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
120 ;; load languages based on value of `org-babel-load-languages'
121 (defvar org-babel-load-languages)
122 ;;;###autoload
123 (defun org-babel-do-load-languages (sym value)
124 "Load the languages defined in `org-babel-load-languages'."
125 (set-default sym value)
126 (mapc (lambda (pair)
127 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
128 (if active
129 (progn
130 (require (intern (concat "ob-" lang))))
131 (progn
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-execute:" lang)))
134 (funcall 'fmakunbound
135 (intern (concat "org-babel-expand-body:" lang)))))))
136 org-babel-load-languages))
138 (defcustom org-babel-load-languages '((emacs-lisp . t))
139 "Languages which can be evaluated in Org-mode buffers.
140 This list can be used to load support for any of the languages
141 below, note that each language will depend on a different set of
142 system executables and/or Emacs modes. When a language is
143 \"loaded\", then code blocks in that language can be evaluated
144 with `org-babel-execute-src-block' bound by default to C-c
145 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
146 be set to remove code block evaluation from the C-c C-c
147 keybinding. By default only Emacs Lisp (which has no
148 requirements) is loaded."
149 :group 'org-babel
150 :set 'org-babel-do-load-languages
151 :version "24.1"
152 :type '(alist :tag "Babel Languages"
153 :key-type
154 (choice
155 (const :tag "Awk" awk)
156 (const :tag "C" C)
157 (const :tag "R" R)
158 (const :tag "Asymptote" asymptote)
159 (const :tag "Calc" calc)
160 (const :tag "Clojure" clojure)
161 (const :tag "CSS" css)
162 (const :tag "Ditaa" ditaa)
163 (const :tag "Dot" dot)
164 (const :tag "Emacs Lisp" emacs-lisp)
165 (const :tag "Fortran" fortran)
166 (const :tag "Gnuplot" gnuplot)
167 (const :tag "Haskell" haskell)
168 (const :tag "IO" io)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "LaTeX" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Lisp" lisp)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scala" scala)
188 (const :tag "Scheme" scheme)
189 (const :tag "Screen" screen)
190 (const :tag "Shell Script" sh)
191 (const :tag "Shen" shen)
192 (const :tag "Sql" sql)
193 (const :tag "Sqlite" sqlite))
194 :value-type (boolean :tag "Activate" :value t)))
196 ;;;; Customization variables
197 (defcustom org-clone-delete-id nil
198 "Remove ID property of clones of a subtree.
199 When non-nil, clones of a subtree don't inherit the ID property.
200 Otherwise they inherit the ID property with a new unique
201 identifier."
202 :type 'boolean
203 :version "24.1"
204 :group 'org-id)
206 ;;; Version
207 (require 'org-compat)
208 (org-check-version)
209 ;;;###autoload
210 (defun org-version (&optional here full message)
211 "Show the org-mode version in the echo area.
212 With prefix argument HERE, insert it at point.
213 When FULL is non-nil, use a verbose version string.
214 When MESSAGE is non-nil, display a message with the version."
215 (interactive "P")
216 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
217 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
218 (org-trash (or
219 (and (fboundp 'org-release) (fboundp 'org-git-version))
220 (load (concat org-dir "org-version.el")
221 'noerror 'nomessage 'nosuffix)))
222 (org-version (org-release))
223 (git-version (org-git-version))
224 (version (format "Org-mode version %s (%s @ %s)"
225 org-version
226 git-version
227 (if org-install-dir
228 (if (string= org-dir org-install-dir)
229 org-install-dir
230 (concat "mixed installation! " org-install-dir " and " org-dir))
231 "org-install.el can not be found!")))
232 (_version (if full version org-version)))
233 (if (org-called-interactively-p 'interactive)
234 (if here
235 (insert version)
236 (message version))
237 (if message (message _version))
238 _version)))
240 (defconst org-version (org-version))
242 ;;; Compatibility constants
244 ;;; The custom variables
246 (defgroup org nil
247 "Outline-based notes management and organizer."
248 :tag "Org"
249 :group 'outlines
250 :group 'calendar)
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
254 :group 'org
255 :type 'hook)
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
259 :group 'org
260 :type 'hook)
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
264 :group 'org
265 :version "24.1"
266 :type 'hook)
268 (defvar org-modules) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force)
273 "Load all extensions listed in `org-modules'."
274 (when (or force (not org-modules-loaded))
275 (mapc (lambda (ext)
276 (condition-case nil (require ext)
277 (error (message "Problems while trying to load feature `%s'" ext))))
278 org-modules)
279 (setq org-modules-loaded t)))
281 (defun org-set-modules (var value)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
283 (set var value)
284 (when (featurep 'org)
285 (org-load-modules-maybe 'force)))
287 (when (org-bound-and-true-p org-modules)
288 (let ((a (member 'org-infojs org-modules)))
289 (and a (setcar a 'org-jsinfo))))
291 (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)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
302 (provide 'org-xyz)"
303 :group 'org
304 :set 'org-set-modules
305 :type
306 '(set :greedy t
307 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
308 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
309 (const :tag " crypt: Encryption of subtrees" org-crypt)
310 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
311 (const :tag " docview: Links to doc-view buffers" org-docview)
312 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
313 (const :tag " id: Global IDs for identifying entries" org-id)
314 (const :tag " info: Links to Info nodes" org-info)
315 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
316 (const :tag " habit: Track your consistency with habits" org-habit)
317 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
318 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
319 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
320 (const :tag " mew Links to Mew folders/messages" org-mew)
321 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
322 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
323 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
324 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
325 (const :tag " vm: Links to VM folders/messages" org-vm)
326 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
327 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
328 (const :tag " mouse: Additional mouse support" org-mouse)
329 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
332 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
333 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
334 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
335 (const :tag "C collector: Collect properties into tables" org-collector)
336 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
337 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
338 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
339 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
340 (const :tag "C eval: Include command output as text" org-eval)
341 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
342 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
343 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
344 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
345 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
347 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
349 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
350 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
351 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
352 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
353 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
354 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
355 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
356 (const :tag "C mtags: Support for muse-like tags" org-mtags)
357 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
358 (const :tag "C registry: A registry for Org-mode links" org-registry)
359 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
360 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
361 (const :tag "C secretary: Team management with org-mode" org-secretary)
362 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
363 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
364 (const :tag "C track: Keep up with Org-mode development" org-track)
365 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
366 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
367 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
407 :group 'org
408 :type '(choice
409 (const :tag "Never" nil)
410 (const :tag "When outside special context" t)
411 (const :tag "Everywhere except timestamps" always)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type '(choice (const :tag "Don't loop" nil)
432 (const :tag "All headlines in active region" t)
433 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
434 (string :tag "Tags/Property/Todo matcher"))
435 :version "24.1"
436 :group 'org-todo
437 :group 'org-archive)
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
441 :tag "Org Startup"
442 :group 'org)
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
451 #+STARTUP: content
452 #+STARTUP: showeverything"
453 :group 'org-startup
454 :type '(choice
455 (const :tag "nofold: show all" nil)
456 (const :tag "fold: overview" t)
457 (const :tag "content: all headlines" content)
458 (const :tag "show everything, even drawers" showeverything)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
464 :group 'org-startup
465 :type 'boolean)
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: indent
473 #+STARTUP: noindent"
474 :group 'org-structure
475 :type '(choice
476 (const :tag "Not" nil)
477 (const :tag "Globally (slow on startup in large files)" t)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
502 :group 'org-startup
503 :group 'org-export-translation
504 :version "24.1"
505 :type '(choice
506 (const :tag "Always interpret" t)
507 (const :tag "Only with braces" {})
508 (const :tag "Never interpret" nil)))
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
519 #+STARTUP: beamer"
520 :group 'org-startup
521 :version "24.1"
522 :type 'boolean)
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
530 #+STARTUP: align
531 #+STARTUP: noalign"
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
551 has been set."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
563 `org-disputed-keys'.
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
567 become effective."
568 :group 'org-startup
569 :type 'boolean)
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
580 it work for ESC."
581 :group 'org-startup
582 :type 'boolean)
584 (if (fboundp 'defvaralias)
585 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
587 (defcustom org-disputed-keys
588 '(([(shift up)] . [(meta p)])
589 ([(shift down)] . [(meta n)])
590 ([(shift left)] . [(meta -)])
591 ([(shift right)] . [(meta +)])
592 ([(control shift right)] . [(meta shift +)])
593 ([(control shift left)] . [(meta shift -)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
601 :group 'org-startup
602 :type 'alist)
604 (defun org-key (key)
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x)) nkey))
612 org-disputed-keys)))
613 (setq key (if x (cdr x) key))))
614 (when (featurep 'xemacs)
615 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
616 key)
618 (defun org-find-if (predicate seq)
619 (catch 'exit
620 (while seq
621 (if (funcall predicate (car seq))
622 (throw 'exit (car seq))
623 (pop seq)))))
625 (defun org-defkey (keymap key def)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap (org-key key) def))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
635 effective."
636 :group 'org-startup
637 :type '(choice (const :tag "Default" nil)
638 (face :tag "Face" :value org-warning)
639 (string :tag "String" :value "...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
646 :tag "Org Keywords"
647 :group 'org)
649 (defcustom org-deadline-string "DEADLINE:"
650 "String to mark deadline entries.
651 A deadline is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-deadline].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-scheduled-string "SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-closed-string "CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-clock-string "CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
678 org-scheduled-string "\\|"
679 org-deadline-string "\\|"
680 org-closed-string "\\|"
681 org-clock-string "\\)")
682 "Matches a line with planning or clock info.")
684 (defcustom org-comment-string "COMMENT"
685 "Entries starting with this keyword will never be exported.
686 An entry can be toggled between COMMENT and normal with
687 \\[org-toggle-comment].
688 Changes become only effective after restarting Emacs."
689 :group 'org-keywords
690 :type 'string)
692 (defcustom org-quote-string "QUOTE"
693 "Entries starting with this keyword will be exported in fixed-width font.
694 Quoting applies only to the text in the entry following the headline, and does
695 not extend beyond the next headline, even if that is lower level.
696 An entry can be toggled between QUOTE and normal with
697 \\[org-toggle-fixed-width-section]."
698 :group 'org-keywords
699 :type 'string)
701 (defconst org-repeat-re
702 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
703 "Regular expression for specifying repeated events.
704 After a match, group 1 contains the repeat expression.")
706 (defgroup org-structure nil
707 "Options concerning the general structure of Org-mode files."
708 :tag "Org Structure"
709 :group 'org)
711 (defgroup org-reveal-location nil
712 "Options about how to make context of a location visible."
713 :tag "Org Reveal Location"
714 :group 'org-structure)
716 (defconst org-context-choice
717 '(choice
718 (const :tag "Always" t)
719 (const :tag "Never" nil)
720 (repeat :greedy t :tag "Individual contexts"
721 (cons
722 (choice :tag "Context"
723 (const agenda)
724 (const org-goto)
725 (const occur-tree)
726 (const tags-tree)
727 (const link-search)
728 (const mark-goto)
729 (const bookmark-jump)
730 (const isearch)
731 (const default))
732 (boolean))))
733 "Contexts for the reveal options.")
735 (defcustom org-show-hierarchy-above '((default . t))
736 "Non-nil means show full hierarchy when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the hierarchy of headings
739 above the exposed location is shown.
740 Turning this off for example for sparse trees makes them very compact.
741 Instead of t, this can also be an alist specifying this option for different
742 contexts. Valid contexts are
743 agenda when exposing an entry from the agenda
744 org-goto when using the command `org-goto' on key C-c C-j
745 occur-tree when using the command `org-occur' on key C-c /
746 tags-tree when constructing a sparse tree based on tags matches
747 link-search when exposing search matches associated with a link
748 mark-goto when exposing the jump goal of a mark
749 bookmark-jump when exposing a bookmark location
750 isearch when exiting from an incremental search
751 default default for all contexts not set explicitly"
752 :group 'org-reveal-location
753 :type org-context-choice)
755 (defcustom org-show-following-heading '((default . nil))
756 "Non-nil means show following heading when revealing a location.
757 Org-mode often shows locations in an org-mode file which might have
758 been invisible before. When this is set, the heading following the
759 match is shown.
760 Turning this off for example for sparse trees makes them very compact,
761 but makes it harder to edit the location of the match. In such a case,
762 use the command \\[org-reveal] to show more context.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. See `org-show-hierarchy-above' for valid contexts."
765 :group 'org-reveal-location
766 :type org-context-choice)
768 (defcustom org-show-siblings '((default . nil) (isearch t))
769 "Non-nil means show all sibling heading when revealing a location.
770 Org-mode often shows locations in an org-mode file which might have
771 been invisible before. When this is set, the sibling of the current entry
772 heading are all made visible. If `org-show-hierarchy-above' is t,
773 the same happens on each level of the hierarchy above the current entry.
775 By default this is on for the isearch context, off for all other contexts.
776 Turning this off for example for sparse trees makes them very compact,
777 but makes it harder to edit the location of the match. In such a case,
778 use the command \\[org-reveal] to show more context.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. See `org-show-hierarchy-above' for valid contexts."
781 :group 'org-reveal-location
782 :type org-context-choice)
784 (defcustom org-show-entry-below '((default . nil))
785 "Non-nil means show the entry below a headline when revealing a location.
786 Org-mode often shows locations in an org-mode file which might have
787 been invisible before. When this is set, the text below the headline that is
788 exposed is also shown.
790 By default this is off for all contexts.
791 Instead of t, this can also be an alist specifying this option for different
792 contexts. See `org-show-hierarchy-above' for valid contexts."
793 :group 'org-reveal-location
794 :type org-context-choice)
796 (defcustom org-indirect-buffer-display 'other-window
797 "How should indirect tree buffers be displayed?
798 This applies to indirect buffers created with the commands
799 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
800 Valid values are:
801 current-window Display in the current window
802 other-window Just display in another window.
803 dedicated-frame Create one new frame, and re-use it each time.
804 new-frame Make a new frame each time. Note that in this case
805 previously-made indirect buffers are kept, and you need to
806 kill these buffers yourself."
807 :group 'org-structure
808 :group 'org-agenda-windows
809 :type '(choice
810 (const :tag "In current window" current-window)
811 (const :tag "In current frame, other window" other-window)
812 (const :tag "Each time a new frame" new-frame)
813 (const :tag "One dedicated frame" dedicated-frame)))
815 (defcustom org-use-speed-commands nil
816 "Non-nil means activate single letter commands at beginning of a headline.
817 This may also be a function to test for appropriate locations where speed
818 commands should be active."
819 :group 'org-structure
820 :type '(choice
821 (const :tag "Never" nil)
822 (const :tag "At beginning of headline stars" t)
823 (function)))
825 (defcustom org-speed-commands-user nil
826 "Alist of additional speed commands.
827 This list will be checked before `org-speed-commands-default'
828 when the variable `org-use-speed-commands' is non-nil
829 and when the cursor is at the beginning of a headline.
830 The car if each entry is a string with a single letter, which must
831 be assigned to `self-insert-command' in the global map.
832 The cdr is either a command to be called interactively, a function
833 to be called, or a form to be evaluated.
834 An entry that is just a list with a single string will be interpreted
835 as a descriptive headline that will be added when listing the speed
836 commands in the Help buffer using the `?' speed command."
837 :group 'org-structure
838 :type '(repeat :value ("k" . ignore)
839 (choice :value ("k" . ignore)
840 (list :tag "Descriptive Headline" (string :tag "Headline"))
841 (cons :tag "Letter and Command"
842 (string :tag "Command letter")
843 (choice
844 (function)
845 (sexp))))))
847 (defgroup org-cycle nil
848 "Options concerning visibility cycling in Org-mode."
849 :tag "Org Cycle"
850 :group 'org-structure)
852 (defcustom org-cycle-skip-children-state-if-no-children t
853 "Non-nil means skip CHILDREN state in entries that don't have any."
854 :group 'org-cycle
855 :type 'boolean)
857 (defcustom org-cycle-max-level nil
858 "Maximum level which should still be subject to visibility cycling.
859 Levels higher than this will, for cycling, be treated as text, not a headline.
860 When `org-odd-levels-only' is set, a value of N in this variable actually
861 means 2N-1 stars as the limiting headline.
862 When nil, cycle all levels.
863 Note that the limiting level of cycling is also influenced by
864 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
865 `org-inlinetask-min-level' is, cycling will be limited to levels one less
866 than its value."
867 :group 'org-cycle
868 :type '(choice
869 (const :tag "No limit" nil)
870 (integer :tag "Maximum level")))
872 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
873 "Names of drawers. Drawers are not opened by cycling on the headline above.
874 Drawers only open with a TAB on the drawer line itself. A drawer looks like
875 this:
876 :DRAWERNAME:
877 .....
878 :END:
879 The drawer \"PROPERTIES\" is special for capturing properties through
880 the property API.
882 Drawers can be defined on the per-file basis with a line like:
884 #+DRAWERS: HIDDEN STATE PROPERTIES"
885 :group 'org-structure
886 :group 'org-cycle
887 :type '(repeat (string :tag "Drawer Name")))
889 (defcustom org-hide-block-startup nil
890 "Non-nil means entering Org-mode will fold all blocks.
891 This can also be set in on a per-file basis with
893 #+STARTUP: hideblocks
894 #+STARTUP: showblocks"
895 :group 'org-startup
896 :group 'org-cycle
897 :type 'boolean)
899 (defcustom org-cycle-global-at-bob nil
900 "Cycle globally if cursor is at beginning of buffer and not at a headline.
901 This makes it possible to do global cycling without having to use S-TAB or
902 \\[universal-argument] TAB. For this special case to work, the first line \
903 of the buffer
904 must not be a headline - it may be empty or some other text. When used in
905 this way, `org-cycle-hook' is disables temporarily, to make sure the
906 cursor stays at the beginning of the buffer.
907 When this option is nil, don't do anything special at the beginning
908 of the buffer."
909 :group 'org-cycle
910 :type 'boolean)
912 (defcustom org-cycle-level-after-item/entry-creation t
913 "Non-nil means cycle entry level or item indentation in new empty entries.
915 When the cursor is at the end of an empty headline, i.e with only stars
916 and maybe a TODO keyword, TAB will then switch the entry to become a child,
917 and then all possible ancestor states, before returning to the original state.
918 This makes data entry extremely fast: M-RET to create a new headline,
919 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
921 When the cursor is at the end of an empty plain list item, one TAB will
922 make it a subitem, two or more tabs will back up to make this an item
923 higher up in the item hierarchy."
924 :group 'org-cycle
925 :type 'boolean)
927 (defcustom org-cycle-emulate-tab t
928 "Where should `org-cycle' emulate TAB.
929 nil Never
930 white Only in completely white lines
931 whitestart Only at the beginning of lines, before the first non-white char
932 t Everywhere except in headlines
933 exc-hl-bol Everywhere except at the start of a headline
934 If TAB is used in a place where it does not emulate TAB, the current subtree
935 visibility is cycled."
936 :group 'org-cycle
937 :type '(choice (const :tag "Never" nil)
938 (const :tag "Only in completely white lines" white)
939 (const :tag "Before first char in a line" whitestart)
940 (const :tag "Everywhere except in headlines" t)
941 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
944 (defcustom org-cycle-separator-lines 2
945 "Number of empty lines needed to keep an empty line between collapsed trees.
946 If you leave an empty line between the end of a subtree and the following
947 headline, this empty line is hidden when the subtree is folded.
948 Org-mode will leave (exactly) one empty line visible if the number of
949 empty lines is equal or larger to the number given in this variable.
950 So the default 2 means at least 2 empty lines after the end of a subtree
951 are needed to produce free space between a collapsed subtree and the
952 following headline.
954 If the number is negative, and the number of empty lines is at least -N,
955 all empty lines are shown.
957 Special case: when 0, never leave empty lines in collapsed view."
958 :group 'org-cycle
959 :type 'integer)
960 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
962 (defcustom org-pre-cycle-hook nil
963 "Hook that is run before visibility cycling is happening.
964 The function(s) in this hook must accept a single argument which indicates
965 the new state that will be set right after running this hook. The
966 argument is a symbol. Before a global state change, it can have the values
967 `overview', `content', or `all'. Before a local state change, it can have
968 the values `folded', `children', or `subtree'."
969 :group 'org-cycle
970 :type 'hook)
972 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
973 org-cycle-hide-drawers
974 org-cycle-show-empty-lines
975 org-optimize-window-after-visibility-change)
976 "Hook that is run after `org-cycle' has changed the buffer visibility.
977 The function(s) in this hook must accept a single argument which indicates
978 the new state that was set by the most recent `org-cycle' command. The
979 argument is a symbol. After a global state change, it can have the values
980 `overview', `content', or `all'. After a local state change, it can have
981 the values `folded', `children', or `subtree'."
982 :group 'org-cycle
983 :type 'hook)
985 (defgroup org-edit-structure nil
986 "Options concerning structure editing in Org-mode."
987 :tag "Org Edit Structure"
988 :group 'org-structure)
990 (defcustom org-odd-levels-only nil
991 "Non-nil means skip even levels and only use odd levels for the outline.
992 This has the effect that two stars are being added/taken away in
993 promotion/demotion commands. It also influences how levels are
994 handled by the exporters.
995 Changing it requires restart of `font-lock-mode' to become effective
996 for fontification also in regions already fontified.
997 You may also set this on a per-file basis by adding one of the following
998 lines to the buffer:
1000 #+STARTUP: odd
1001 #+STARTUP: oddeven"
1002 :group 'org-edit-structure
1003 :group 'org-appearance
1004 :type 'boolean)
1006 (defcustom org-adapt-indentation t
1007 "Non-nil means adapt indentation to outline node level.
1009 When this variable is set, Org assumes that you write outlines by
1010 indenting text in each node to align with the headline (after the stars).
1011 The following issues are influenced by this variable:
1013 - When this is set and the *entire* text in an entry is indented, the
1014 indentation is increased by one space in a demotion command, and
1015 decreased by one in a promotion command. If any line in the entry
1016 body starts with text at column 0, indentation is not changed at all.
1018 - Property drawers and planning information is inserted indented when
1019 this variable s set. When nil, they will not be indented.
1021 - TAB indents a line relative to context. The lines below a headline
1022 will be indented when this variable is set.
1024 Note that this is all about true indentation, by adding and removing
1025 space characters. See also `org-indent.el' which does level-dependent
1026 indentation in a virtual way, i.e. at display time in Emacs."
1027 :group 'org-edit-structure
1028 :type 'boolean)
1030 (defcustom org-special-ctrl-a/e nil
1031 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1033 When t, `C-a' will bring back the cursor to the beginning of the
1034 headline text, i.e. after the stars and after a possible TODO
1035 keyword. In an item, this will be the position after bullet and
1036 check-box, if any. When the cursor is already at that position,
1037 another `C-a' will bring it to the beginning of the line.
1039 `C-e' will jump to the end of the headline, ignoring the presence
1040 of tags in the headline. A second `C-e' will then jump to the
1041 true end of the line, after any tags. This also means that, when
1042 this variable is non-nil, `C-e' also will never jump beyond the
1043 end of the heading of a folded section, i.e. not after the
1044 ellipses.
1046 When set to the symbol `reversed', the first `C-a' or `C-e' works
1047 normally, going to the true line boundary first. Only a directly
1048 following, identical keypress will bring the cursor to the
1049 special positions.
1051 This may also be a cons cell where the behavior for `C-a' and
1052 `C-e' is set separately."
1053 :group 'org-edit-structure
1054 :type '(choice
1055 (const :tag "off" nil)
1056 (const :tag "on: after stars/bullet and before tags first" t)
1057 (const :tag "reversed: true line boundary first" reversed)
1058 (cons :tag "Set C-a and C-e separately"
1059 (choice :tag "Special C-a"
1060 (const :tag "off" nil)
1061 (const :tag "on: after stars/bullet first" t)
1062 (const :tag "reversed: before stars/bullet first" reversed))
1063 (choice :tag "Special C-e"
1064 (const :tag "off" nil)
1065 (const :tag "on: before tags first" t)
1066 (const :tag "reversed: after tags first" reversed)))))
1067 (if (fboundp 'defvaralias)
1068 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1070 (defcustom org-special-ctrl-k nil
1071 "Non-nil means `C-k' will behave specially in headlines.
1072 When nil, `C-k' will call the default `kill-line' command.
1073 When t, the following will happen while the cursor is in the headline:
1075 - When the cursor is at the beginning of a headline, kill the entire
1076 line and possible the folded subtree below the line.
1077 - When in the middle of the headline text, kill the headline up to the tags.
1078 - When after the headline text, kill the tags."
1079 :group 'org-edit-structure
1080 :type 'boolean)
1082 (defcustom org-ctrl-k-protect-subtree nil
1083 "Non-nil means, do not delete a hidden subtree with C-k.
1084 When set to the symbol `error', simply throw an error when C-k is
1085 used to kill (part-of) a headline that has hidden text behind it.
1086 Any other non-nil value will result in a query to the user, if it is
1087 OK to kill that hidden subtree. When nil, kill without remorse."
1088 :group 'org-edit-structure
1089 :version "24.1"
1090 :type '(choice
1091 (const :tag "Do not protect hidden subtrees" nil)
1092 (const :tag "Protect hidden subtrees with a security query" t)
1093 (const :tag "Never kill a hidden subtree with C-k" error)))
1095 (defcustom org-catch-invisible-edits nil
1096 "Check if in invisible region before inserting or deleting a character.
1097 Valid values are:
1099 nil Do not check, so just do invisible edits.
1100 error Throw an error and do nothing.
1101 show Make point visible, and do the requested edit.
1102 show-and-error Make point visible, then throw an error and abort the edit.
1103 smart Make point visible, and do insertion/deletion if it is
1104 adjacent to visible text and the change feels predictable.
1105 Never delete a previously invisible character or add in the
1106 middle or right after an invisible region. Basically, this
1107 allows insertion and backward-delete right before ellipses.
1108 FIXME: maybe in this case we should not even show?"
1109 :group 'org-edit-structure
1110 :version "24.1"
1111 :type '(choice
1112 (const :tag "Do not check" nil)
1113 (const :tag "Throw error when trying to edit" error)
1114 (const :tag "Unhide, but do not do the edit" show-and-error)
1115 (const :tag "Show invisible part and do the edit" show)
1116 (const :tag "Be smart and do the right thing" smart)))
1118 (defcustom org-yank-folded-subtrees t
1119 "Non-nil means when yanking subtrees, fold them.
1120 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1121 it starts with a heading and all other headings in it are either children
1122 or siblings, then fold all the subtrees. However, do this only if no
1123 text after the yank would be swallowed into a folded tree by this action."
1124 :group 'org-edit-structure
1125 :type 'boolean)
1127 (defcustom org-yank-adjusted-subtrees nil
1128 "Non-nil means when yanking subtrees, adjust the level.
1129 With this setting, `org-paste-subtree' is used to insert the subtree, see
1130 this function for details."
1131 :group 'org-edit-structure
1132 :type 'boolean)
1134 (defcustom org-M-RET-may-split-line '((default . t))
1135 "Non-nil means M-RET will split the line at the cursor position.
1136 When nil, it will go to the end of the line before making a
1137 new line.
1138 You may also set this option in a different way for different
1139 contexts. Valid contexts are:
1141 headline when creating a new headline
1142 item when creating a new item
1143 table in a table field
1144 default the value to be used for all contexts not explicitly
1145 customized"
1146 :group 'org-structure
1147 :group 'org-table
1148 :type '(choice
1149 (const :tag "Always" t)
1150 (const :tag "Never" nil)
1151 (repeat :greedy t :tag "Individual contexts"
1152 (cons
1153 (choice :tag "Context"
1154 (const headline)
1155 (const item)
1156 (const table)
1157 (const default))
1158 (boolean)))))
1161 (defcustom org-insert-heading-respect-content nil
1162 "Non-nil means insert new headings after the current subtree.
1163 When nil, the new heading is created directly after the current line.
1164 The commands \\[org-insert-heading-respect-content] and
1165 \\[org-insert-todo-heading-respect-content] turn this variable on
1166 for the duration of the command."
1167 :group 'org-structure
1168 :type 'boolean)
1170 (defcustom org-blank-before-new-entry '((heading . auto)
1171 (plain-list-item . auto))
1172 "Should `org-insert-heading' leave a blank line before new heading/item?
1173 The value is an alist, with `heading' and `plain-list-item' as CAR,
1174 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1175 which case Org will look at the surrounding headings/items and try to
1176 make an intelligent decision whether to insert a blank line or not.
1178 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1179 set, the setting here is ignored and no empty line is inserted, to avoid
1180 breaking the list structure."
1181 :group 'org-edit-structure
1182 :type '(list
1183 (cons (const heading)
1184 (choice (const :tag "Never" nil)
1185 (const :tag "Always" t)
1186 (const :tag "Auto" auto)))
1187 (cons (const plain-list-item)
1188 (choice (const :tag "Never" nil)
1189 (const :tag "Always" t)
1190 (const :tag "Auto" auto)))))
1192 (defcustom org-insert-heading-hook nil
1193 "Hook being run after inserting a new heading."
1194 :group 'org-edit-structure
1195 :type 'hook)
1197 (defcustom org-enable-fixed-width-editor t
1198 "Non-nil means lines starting with \":\" are treated as fixed-width.
1199 This currently only means they are never auto-wrapped.
1200 When nil, such lines will be treated like ordinary lines.
1201 See also the QUOTE keyword."
1202 :group 'org-edit-structure
1203 :type 'boolean)
1205 (defcustom org-goto-auto-isearch t
1206 "Non-nil means typing characters in `org-goto' starts incremental search."
1207 :group 'org-edit-structure
1208 :type 'boolean)
1210 (defgroup org-sparse-trees nil
1211 "Options concerning sparse trees in Org-mode."
1212 :tag "Org Sparse Trees"
1213 :group 'org-structure)
1215 (defcustom org-highlight-sparse-tree-matches t
1216 "Non-nil means highlight all matches that define a sparse tree.
1217 The highlights will automatically disappear the next time the buffer is
1218 changed by an edit command."
1219 :group 'org-sparse-trees
1220 :type 'boolean)
1222 (defcustom org-remove-highlights-with-change t
1223 "Non-nil means any change to the buffer will remove temporary highlights.
1224 Such highlights are created by `org-occur' and `org-clock-display'.
1225 When nil, `C-c C-c needs to be used to get rid of the highlights.
1226 The highlights created by `org-preview-latex-fragment' always need
1227 `C-c C-c' to be removed."
1228 :group 'org-sparse-trees
1229 :group 'org-time
1230 :type 'boolean)
1233 (defcustom org-occur-hook '(org-first-headline-recenter)
1234 "Hook that is run after `org-occur' has constructed a sparse tree.
1235 This can be used to recenter the window to show as much of the structure
1236 as possible."
1237 :group 'org-sparse-trees
1238 :type 'hook)
1240 (defgroup org-imenu-and-speedbar nil
1241 "Options concerning imenu and speedbar in Org-mode."
1242 :tag "Org Imenu and Speedbar"
1243 :group 'org-structure)
1245 (defcustom org-imenu-depth 2
1246 "The maximum level for Imenu access to Org-mode headlines.
1247 This also applied for speedbar access."
1248 :group 'org-imenu-and-speedbar
1249 :type 'integer)
1251 (defgroup org-table nil
1252 "Options concerning tables in Org-mode."
1253 :tag "Org Table"
1254 :group 'org)
1256 (defcustom org-enable-table-editor 'optimized
1257 "Non-nil means lines starting with \"|\" are handled by the table editor.
1258 When nil, such lines will be treated like ordinary lines.
1260 When equal to the symbol `optimized', the table editor will be optimized to
1261 do the following:
1262 - Automatic overwrite mode in front of whitespace in table fields.
1263 This makes the structure of the table stay in tact as long as the edited
1264 field does not exceed the column width.
1265 - Minimize the number of realigns. Normally, the table is aligned each time
1266 TAB or RET are pressed to move to another field. With optimization this
1267 happens only if changes to a field might have changed the column width.
1268 Optimization requires replacing the functions `self-insert-command',
1269 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1270 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1271 very good at guessing when a re-align will be necessary, but you can always
1272 force one with \\[org-ctrl-c-ctrl-c].
1274 If you would like to use the optimized version in Org-mode, but the
1275 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1277 This variable can be used to turn on and off the table editor during a session,
1278 but in order to toggle optimization, a restart is required.
1280 See also the variable `org-table-auto-blank-field'."
1281 :group 'org-table
1282 :type '(choice
1283 (const :tag "off" nil)
1284 (const :tag "on" t)
1285 (const :tag "on, optimized" optimized)))
1287 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1288 (version<= emacs-version "24.1"))
1289 "Non-nil means cluster self-insert commands for undo when possible.
1290 If this is set, then, like in the Emacs command loop, 20 consecutive
1291 characters will be undone together.
1292 This is configurable, because there is some impact on typing performance."
1293 :group 'org-table
1294 :type 'boolean)
1296 (defcustom org-table-tab-recognizes-table.el t
1297 "Non-nil means TAB will automatically notice a table.el table.
1298 When it sees such a table, it moves point into it and - if necessary -
1299 calls `table-recognize-table'."
1300 :group 'org-table-editing
1301 :type 'boolean)
1303 (defgroup org-link nil
1304 "Options concerning links in Org-mode."
1305 :tag "Org Link"
1306 :group 'org)
1308 (defvar org-link-abbrev-alist-local nil
1309 "Buffer-local version of `org-link-abbrev-alist', which see.
1310 The value of this is taken from the #+LINK lines.")
1311 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1313 (defcustom org-link-abbrev-alist nil
1314 "Alist of link abbreviations.
1315 The car of each element is a string, to be replaced at the start of a link.
1316 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1317 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1319 [[linkkey:tag][description]]
1321 The 'linkkey' must be a word word, starting with a letter, followed
1322 by letters, numbers, '-' or '_'.
1324 If REPLACE is a string, the tag will simply be appended to create the link.
1325 If the string contains \"%s\", the tag will be inserted there. If the string
1326 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1327 at that point (see the function `url-hexify-string'). If the string contains
1328 the specifier \"%(my-function)\", then the custom function `my-function' will
1329 be invoked: this function takes the tag as its only argument and must return
1330 a string.
1332 REPLACE may also be a function that will be called with the tag as the
1333 only argument to create the link, which should be returned as a string.
1335 See the manual for examples."
1336 :group 'org-link
1337 :type '(repeat
1338 (cons
1339 (string :tag "Protocol")
1340 (choice
1341 (string :tag "Format")
1342 (function)))))
1344 (defcustom org-descriptive-links t
1345 "Non-nil means Org will display descriptive links.
1346 E.g. [[http://orgmode.org][Org website]] will be displayed as
1347 \"Org Website\", hiding the link itself and just displaying its
1348 description. When set to `nil', Org will display the full links
1349 literally.
1351 You can interactively set the value of this variable by calling
1352 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1353 :group 'org-link
1354 :type 'boolean)
1356 (defcustom org-link-file-path-type 'adaptive
1357 "How the path name in file links should be stored.
1358 Valid values are:
1360 relative Relative to the current directory, i.e. the directory of the file
1361 into which the link is being inserted.
1362 absolute Absolute path, if possible with ~ for home directory.
1363 noabbrev Absolute path, no abbreviation of home directory.
1364 adaptive Use relative path for files in the current directory and sub-
1365 directories of it. For other files, use an absolute path."
1366 :group 'org-link
1367 :type '(choice
1368 (const relative)
1369 (const absolute)
1370 (const noabbrev)
1371 (const adaptive)))
1373 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1374 "Types of links that should be activated in Org-mode files.
1375 This is a list of symbols, each leading to the activation of a certain link
1376 type. In principle, it does not hurt to turn on most link types - there may
1377 be a small gain when turning off unused link types. The types are:
1379 bracket The recommended [[link][description]] or [[link]] links with hiding.
1380 angle Links in angular brackets that may contain whitespace like
1381 <bbdb:Carsten Dominik>.
1382 plain Plain links in normal text, no whitespace, like http://google.com.
1383 radio Text that is matched by a radio target, see manual for details.
1384 tag Tag settings in a headline (link to tag search).
1385 date Time stamps (link to calendar).
1386 footnote Footnote labels.
1388 Changing this variable requires a restart of Emacs to become effective."
1389 :group 'org-link
1390 :type '(set :greedy t
1391 (const :tag "Double bracket links" bracket)
1392 (const :tag "Angular bracket links" angle)
1393 (const :tag "Plain text links" plain)
1394 (const :tag "Radio target matches" radio)
1395 (const :tag "Tags" tag)
1396 (const :tag "Timestamps" date)
1397 (const :tag "Footnotes" footnote)))
1399 (defcustom org-make-link-description-function nil
1400 "Function to use to generate link descriptions from links.
1401 If nil the link location will be used. This function must take
1402 two parameters; the first is the link and the second the
1403 description `org-insert-link' has generated, and should return the
1404 description to use."
1405 :group 'org-link
1406 :type 'function)
1408 (defgroup org-link-store nil
1409 "Options concerning storing links in Org-mode."
1410 :tag "Org Store Link"
1411 :group 'org-link)
1413 (defcustom org-url-hexify-p t
1414 "When non-nil, hexify URL when creating a link."
1415 :type 'boolean
1416 ;; :version "24.3"
1417 :group 'org-link-store)
1419 (defcustom org-email-link-description-format "Email %c: %.30s"
1420 "Format of the description part of a link to an email or usenet message.
1421 The following %-escapes will be replaced by corresponding information:
1423 %F full \"From\" field
1424 %f name, taken from \"From\" field, address if no name
1425 %T full \"To\" field
1426 %t first name in \"To\" field, address if no name
1427 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1428 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1429 %s subject
1430 %d date
1431 %m message-id.
1433 You may use normal field width specification between the % and the letter.
1434 This is for example useful to limit the length of the subject.
1436 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1437 :group 'org-link-store
1438 :type 'string)
1440 (defcustom org-from-is-user-regexp
1441 (let (r1 r2)
1442 (when (and user-mail-address (not (string= user-mail-address "")))
1443 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1444 (when (and user-full-name (not (string= user-full-name "")))
1445 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1446 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1447 "Regexp matched against the \"From:\" header of an email or usenet message.
1448 It should match if the message is from the user him/herself."
1449 :group 'org-link-store
1450 :type 'regexp)
1452 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1453 "Non-nil means storing a link to an Org file will use entry IDs.
1455 Note that before this variable is even considered, org-id must be loaded,
1456 so please customize `org-modules' and turn it on.
1458 The variable can have the following values:
1460 t Create an ID if needed to make a link to the current entry.
1462 create-if-interactive
1463 If `org-store-link' is called directly (interactively, as a user
1464 command), do create an ID to support the link. But when doing the
1465 job for remember, only use the ID if it already exists. The
1466 purpose of this setting is to avoid proliferation of unwanted
1467 IDs, just because you happen to be in an Org file when you
1468 call `org-capture' that automatically and preemptively creates a
1469 link. If you do want to get an ID link in a remember template to
1470 an entry not having an ID, create it first by explicitly creating
1471 a link to it, using `C-c C-l' first.
1473 create-if-interactive-and-no-custom-id
1474 Like create-if-interactive, but do not create an ID if there is
1475 a CUSTOM_ID property defined in the entry. This is the default.
1477 use-existing
1478 Use existing ID, do not create one.
1480 nil Never use an ID to make a link, instead link using a text search for
1481 the headline text."
1482 :group 'org-link-store
1483 :type '(choice
1484 (const :tag "Create ID to make link" t)
1485 (const :tag "Create if storing link interactively"
1486 create-if-interactive)
1487 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1488 create-if-interactive-and-no-custom-id)
1489 (const :tag "Only use existing" use-existing)
1490 (const :tag "Do not use ID to create link" nil)))
1492 (defcustom org-context-in-file-links t
1493 "Non-nil means file links from `org-store-link' contain context.
1494 A search string will be added to the file name with :: as separator and
1495 used to find the context when the link is activated by the command
1496 `org-open-at-point'. When this option is t, the entire active region
1497 will be placed in the search string of the file link. If set to a
1498 positive integer, only the first n lines of context will be stored.
1500 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1501 negates this setting for the duration of the command."
1502 :group 'org-link-store
1503 :type '(choice boolean integer))
1505 (defcustom org-keep-stored-link-after-insertion nil
1506 "Non-nil means keep link in list for entire session.
1508 The command `org-store-link' adds a link pointing to the current
1509 location to an internal list. These links accumulate during a session.
1510 The command `org-insert-link' can be used to insert links into any
1511 Org-mode file (offering completion for all stored links). When this
1512 option is nil, every link which has been inserted once using \\[org-insert-link]
1513 will be removed from the list, to make completing the unused links
1514 more efficient."
1515 :group 'org-link-store
1516 :type 'boolean)
1518 (defgroup org-link-follow nil
1519 "Options concerning following links in Org-mode."
1520 :tag "Org Follow Link"
1521 :group 'org-link)
1523 (defcustom org-link-translation-function nil
1524 "Function to translate links with different syntax to Org syntax.
1525 This can be used to translate links created for example by the Planner
1526 or emacs-wiki packages to Org syntax.
1527 The function must accept two parameters, a TYPE containing the link
1528 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1529 which is everything after the link protocol. It should return a cons
1530 with possibly modified values of type and path.
1531 Org contains a function for this, so if you set this variable to
1532 `org-translate-link-from-planner', you should be able follow many
1533 links created by planner."
1534 :group 'org-link-follow
1535 :type 'function)
1537 (defcustom org-follow-link-hook nil
1538 "Hook that is run after a link has been followed."
1539 :group 'org-link-follow
1540 :type 'hook)
1542 (defcustom org-tab-follows-link nil
1543 "Non-nil means on links TAB will follow the link.
1544 Needs to be set before org.el is loaded.
1545 This really should not be used, it does not make sense, and the
1546 implementation is bad."
1547 :group 'org-link-follow
1548 :type 'boolean)
1550 (defcustom org-return-follows-link nil
1551 "Non-nil means on links RET will follow the link."
1552 :group 'org-link-follow
1553 :type 'boolean)
1555 (defcustom org-mouse-1-follows-link
1556 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1557 "Non-nil means mouse-1 on a link will follow the link.
1558 A longer mouse click will still set point. Does not work on XEmacs.
1559 Needs to be set before org.el is loaded."
1560 :group 'org-link-follow
1561 :type 'boolean)
1563 (defcustom org-mark-ring-length 4
1564 "Number of different positions to be recorded in the ring.
1565 Changing this requires a restart of Emacs to work correctly."
1566 :group 'org-link-follow
1567 :type 'integer)
1569 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1570 "Non-nil means internal links in Org files must exactly match a headline.
1571 When nil, the link search tries to match a phrase with all words
1572 in the search text."
1573 :group 'org-link-follow
1574 :version "24.1"
1575 :type '(choice
1576 (const :tag "Use fuzzy text search" nil)
1577 (const :tag "Match only exact headline" t)
1578 (const :tag "Match exact headline or query to create it"
1579 query-to-create)))
1581 (defcustom org-link-frame-setup
1582 '((vm . vm-visit-folder-other-frame)
1583 (vm-imap . vm-visit-imap-folder-other-frame)
1584 (gnus . org-gnus-no-new-news)
1585 (file . find-file-other-window)
1586 (wl . wl-other-frame))
1587 "Setup the frame configuration for following links.
1588 When following a link with Emacs, it may often be useful to display
1589 this link in another window or frame. This variable can be used to
1590 set this up for the different types of links.
1591 For VM, use any of
1592 `vm-visit-folder'
1593 `vm-visit-folder-other-window'
1594 `vm-visit-folder-other-frame'
1595 For Gnus, use any of
1596 `gnus'
1597 `gnus-other-frame'
1598 `org-gnus-no-new-news'
1599 For FILE, use any of
1600 `find-file'
1601 `find-file-other-window'
1602 `find-file-other-frame'
1603 For Wanderlust use any of
1604 `wl'
1605 `wl-other-frame'
1606 For the calendar, use the variable `calendar-setup'.
1607 For BBDB, it is currently only possible to display the matches in
1608 another window."
1609 :group 'org-link-follow
1610 :type '(list
1611 (cons (const vm)
1612 (choice
1613 (const vm-visit-folder)
1614 (const vm-visit-folder-other-window)
1615 (const vm-visit-folder-other-frame)))
1616 (cons (const gnus)
1617 (choice
1618 (const gnus)
1619 (const gnus-other-frame)
1620 (const org-gnus-no-new-news)))
1621 (cons (const file)
1622 (choice
1623 (const find-file)
1624 (const find-file-other-window)
1625 (const find-file-other-frame)))
1626 (cons (const wl)
1627 (choice
1628 (const wl)
1629 (const wl-other-frame)))))
1631 (defcustom org-display-internal-link-with-indirect-buffer nil
1632 "Non-nil means use indirect buffer to display infile links.
1633 Activating internal links (from one location in a file to another location
1634 in the same file) normally just jumps to the location. When the link is
1635 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1636 is displayed in
1637 another window. When this option is set, the other window actually displays
1638 an indirect buffer clone of the current buffer, to avoid any visibility
1639 changes to the current buffer."
1640 :group 'org-link-follow
1641 :type 'boolean)
1643 (defcustom org-open-non-existing-files nil
1644 "Non-nil means `org-open-file' will open non-existing files.
1645 When nil, an error will be generated.
1646 This variable applies only to external applications because they
1647 might choke on non-existing files. If the link is to a file that
1648 will be opened in Emacs, the variable is ignored."
1649 :group 'org-link-follow
1650 :type 'boolean)
1652 (defcustom org-open-directory-means-index-dot-org nil
1653 "Non-nil means a link to a directory really means to index.org.
1654 When nil, following a directory link will run dired or open a finder/explorer
1655 window on that directory."
1656 :group 'org-link-follow
1657 :type 'boolean)
1659 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1660 "Function and arguments to call for following mailto links.
1661 This is a list with the first element being a Lisp function, and the
1662 remaining elements being arguments to the function. In string arguments,
1663 %a will be replaced by the address, and %s will be replaced by the subject
1664 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1665 :group 'org-link-follow
1666 :type '(choice
1667 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1668 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1669 (const :tag "message-mail" (message-mail "%a" "%s"))
1670 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1672 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1673 "Non-nil means ask for confirmation before executing shell links.
1674 Shell links can be dangerous: just think about a link
1676 [[shell:rm -rf ~/*][Google Search]]
1678 This link would show up in your Org-mode document as \"Google Search\",
1679 but really it would remove your entire home directory.
1680 Therefore we advise against setting this variable to nil.
1681 Just change it to `y-or-n-p' if you want to confirm with a
1682 single keystroke rather than having to type \"yes\"."
1683 :group 'org-link-follow
1684 :type '(choice
1685 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1686 (const :tag "with y-or-n (faster)" y-or-n-p)
1687 (const :tag "no confirmation (dangerous)" nil)))
1688 (put 'org-confirm-shell-link-function
1689 'safe-local-variable
1690 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1692 (defcustom org-confirm-shell-link-not-regexp ""
1693 "A regexp to skip confirmation for shell links."
1694 :group 'org-link-follow
1695 :version "24.1"
1696 :type 'regexp)
1698 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1699 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1700 Elisp links can be dangerous: just think about a link
1702 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1704 This link would show up in your Org-mode document as \"Google Search\",
1705 but really it would remove your entire home directory.
1706 Therefore we advise against setting this variable to nil.
1707 Just change it to `y-or-n-p' if you want to confirm with a
1708 single keystroke rather than having to type \"yes\"."
1709 :group 'org-link-follow
1710 :type '(choice
1711 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1712 (const :tag "with y-or-n (faster)" y-or-n-p)
1713 (const :tag "no confirmation (dangerous)" nil)))
1714 (put 'org-confirm-shell-link-function
1715 'safe-local-variable
1716 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1718 (defcustom org-confirm-elisp-link-not-regexp ""
1719 "A regexp to skip confirmation for Elisp links."
1720 :group 'org-link-follow
1721 :version "24.1"
1722 :type 'regexp)
1724 (defconst org-file-apps-defaults-gnu
1725 '((remote . emacs)
1726 (system . mailcap)
1727 (t . mailcap))
1728 "Default file applications on a UNIX or GNU/Linux system.
1729 See `org-file-apps'.")
1731 (defconst org-file-apps-defaults-macosx
1732 '((remote . emacs)
1733 (t . "open %s")
1734 (system . "open %s")
1735 ("ps.gz" . "gv %s")
1736 ("eps.gz" . "gv %s")
1737 ("dvi" . "xdvi %s")
1738 ("fig" . "xfig %s"))
1739 "Default file applications on a MacOS X system.
1740 The system \"open\" is known as a default, but we use X11 applications
1741 for some files for which the OS does not have a good default.
1742 See `org-file-apps'.")
1744 (defconst org-file-apps-defaults-windowsnt
1745 (list
1746 '(remote . emacs)
1747 (cons t
1748 (list (if (featurep 'xemacs)
1749 'mswindows-shell-execute
1750 'w32-shell-execute)
1751 "open" 'file))
1752 (cons 'system
1753 (list (if (featurep 'xemacs)
1754 'mswindows-shell-execute
1755 'w32-shell-execute)
1756 "open" 'file)))
1757 "Default file applications on a Windows NT system.
1758 The system \"open\" is used for most files.
1759 See `org-file-apps'.")
1761 (defcustom org-file-apps
1763 (auto-mode . emacs)
1764 ("\\.mm\\'" . default)
1765 ("\\.x?html?\\'" . default)
1766 ("\\.pdf\\'" . default)
1768 "External applications for opening `file:path' items in a document.
1769 Org-mode uses system defaults for different file types, but
1770 you can use this variable to set the application for a given file
1771 extension. The entries in this list are cons cells where the car identifies
1772 files and the cdr the corresponding command. Possible values for the
1773 file identifier are
1774 \"string\" A string as a file identifier can be interpreted in different
1775 ways, depending on its contents:
1777 - Alphanumeric characters only:
1778 Match links with this file extension.
1779 Example: (\"pdf\" . \"evince %s\")
1780 to open PDFs with evince.
1782 - Regular expression: Match links where the
1783 filename matches the regexp. If you want to
1784 use groups here, use shy groups.
1786 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1787 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1788 to open *.html and *.xhtml with firefox.
1790 - Regular expression which contains (non-shy) groups:
1791 Match links where the whole link, including \"::\", and
1792 anything after that, matches the regexp.
1793 In a custom command string, %1, %2, etc. are replaced with
1794 the parts of the link that were matched by the groups.
1795 For backwards compatibility, if a command string is given
1796 that does not use any of the group matches, this case is
1797 handled identically to the second one (i.e. match against
1798 file name only).
1799 In a custom lisp form, you can access the group matches with
1800 (match-string n link).
1802 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1803 to open [[file:document.pdf::5]] with evince at page 5.
1805 `directory' Matches a directory
1806 `remote' Matches a remote file, accessible through tramp or efs.
1807 Remote files most likely should be visited through Emacs
1808 because external applications cannot handle such paths.
1809 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1810 so all files Emacs knows how to handle. Using this with
1811 command `emacs' will open most files in Emacs. Beware that this
1812 will also open html files inside Emacs, unless you add
1813 (\"html\" . default) to the list as well.
1814 t Default for files not matched by any of the other options.
1815 `system' The system command to open files, like `open' on Windows
1816 and Mac OS X, and mailcap under GNU/Linux. This is the command
1817 that will be selected if you call `C-c C-o' with a double
1818 \\[universal-argument] \\[universal-argument] prefix.
1820 Possible values for the command are:
1821 `emacs' The file will be visited by the current Emacs process.
1822 `default' Use the default application for this file type, which is the
1823 association for t in the list, most likely in the system-specific
1824 part.
1825 This can be used to overrule an unwanted setting in the
1826 system-specific variable.
1827 `system' Use the system command for opening files, like \"open\".
1828 This command is specified by the entry whose car is `system'.
1829 Most likely, the system-specific version of this variable
1830 does define this command, but you can overrule/replace it
1831 here.
1832 string A command to be executed by a shell; %s will be replaced
1833 by the path to the file.
1834 sexp A Lisp form which will be evaluated. The file path will
1835 be available in the Lisp variable `file'.
1836 For more examples, see the system specific constants
1837 `org-file-apps-defaults-macosx'
1838 `org-file-apps-defaults-windowsnt'
1839 `org-file-apps-defaults-gnu'."
1840 :group 'org-link-follow
1841 :type '(repeat
1842 (cons (choice :value ""
1843 (string :tag "Extension")
1844 (const :tag "System command to open files" system)
1845 (const :tag "Default for unrecognized files" t)
1846 (const :tag "Remote file" remote)
1847 (const :tag "Links to a directory" directory)
1848 (const :tag "Any files that have Emacs modes"
1849 auto-mode))
1850 (choice :value ""
1851 (const :tag "Visit with Emacs" emacs)
1852 (const :tag "Use default" default)
1853 (const :tag "Use the system command" system)
1854 (string :tag "Command")
1855 (sexp :tag "Lisp form")))))
1857 (defcustom org-doi-server-url "http://dx.doi.org/"
1858 "The URL of the DOI server."
1859 :type 'string
1860 ;; :version "24.3"
1861 :group 'org-link-follow)
1863 (defgroup org-refile nil
1864 "Options concerning refiling entries in Org-mode."
1865 :tag "Org Refile"
1866 :group 'org)
1868 (defcustom org-directory "~/org"
1869 "Directory with org files.
1870 This is just a default location to look for Org files. There is no need
1871 at all to put your files into this directory. It is only used in the
1872 following situations:
1874 1. When a remember template specifies a target file that is not an
1875 absolute path. The path will then be interpreted relative to
1876 `org-directory'
1877 2. When a remember note is filed away in an interactive way (when exiting the
1878 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1879 with `org-directory' as the default path."
1880 :group 'org-refile
1881 :group 'org-remember
1882 :type 'directory)
1884 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1885 "Default target for storing notes.
1886 Used as a fall back file for org-remember.el and org-capture.el, for
1887 templates that do not specify a target file."
1888 :group 'org-refile
1889 :group 'org-remember
1890 :type '(choice
1891 (const :tag "Default from remember-data-file" nil)
1892 file))
1894 (defcustom org-goto-interface 'outline
1895 "The default interface to be used for `org-goto'.
1896 Allowed values are:
1897 outline The interface shows an outline of the relevant file
1898 and the correct heading is found by moving through
1899 the outline or by searching with incremental search.
1900 outline-path-completion Headlines in the current buffer are offered via
1901 completion. This is the interface also used by
1902 the refile command."
1903 :group 'org-refile
1904 :type '(choice
1905 (const :tag "Outline" outline)
1906 (const :tag "Outline-path-completion" outline-path-completion)))
1908 (defcustom org-goto-max-level 5
1909 "Maximum target level when running `org-goto' with refile interface."
1910 :group 'org-refile
1911 :type 'integer)
1913 (defcustom org-reverse-note-order nil
1914 "Non-nil means store new notes at the beginning of a file or entry.
1915 When nil, new notes will be filed to the end of a file or entry.
1916 This can also be a list with cons cells of regular expressions that
1917 are matched against file names, and values."
1918 :group 'org-remember
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 If this variable is set, `org-log-state-notes-insert-after-drawers'
2504 will be ignored.
2506 You can set the property LOG_INTO_DRAWER to overrule this setting for
2507 a subtree."
2508 :group 'org-todo
2509 :group 'org-progress
2510 :type '(choice
2511 (const :tag "Not into a drawer" nil)
2512 (const :tag "LOGBOOK" t)
2513 (string :tag "Other")))
2515 (if (fboundp 'defvaralias)
2516 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2518 (defun org-log-into-drawer ()
2519 "Return the value of `org-log-into-drawer', but let properties overrule.
2520 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2521 used instead of the default value."
2522 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2523 (cond
2524 ((or (not p) (equal p "nil")) org-log-into-drawer)
2525 ((equal p "t") "LOGBOOK")
2526 (t p))))
2528 (defcustom org-log-state-notes-insert-after-drawers nil
2529 "Non-nil means insert state change notes after any drawers in entry.
2530 Only the drawers that *immediately* follow the headline and the
2531 deadline/scheduled line are skipped.
2532 When nil, insert notes right after the heading and perhaps the line
2533 with deadline/scheduling if present.
2535 This variable will have no effect if `org-log-into-drawer' is
2536 set."
2537 :group 'org-todo
2538 :group 'org-progress
2539 :type 'boolean)
2541 (defcustom org-log-states-order-reversed t
2542 "Non-nil means the latest state note will be directly after heading.
2543 When nil, the state change notes will be ordered according to time."
2544 :group 'org-todo
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-todo-repeat-to-state nil
2549 "The TODO state to which a repeater should return the repeating task.
2550 By default this is the first task in a TODO sequence, or the previous state
2551 in a TODO_TYP set. But you can specify another task here.
2552 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2553 :group 'org-todo
2554 :version "24.1"
2555 :type '(choice (const :tag "Head of sequence" nil)
2556 (string :tag "Specific state")))
2558 (defcustom org-log-repeat 'time
2559 "Non-nil means record moving through the DONE state when triggering repeat.
2560 An auto-repeating task is immediately switched back to TODO when
2561 marked DONE. If you are not logging state changes (by adding \"@\"
2562 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2563 record a closing note, there will be no record of the task moving
2564 through DONE. This variable forces taking a note anyway.
2566 nil Don't force a record
2567 time Record a time stamp
2568 note Prompt for a note and add it with template `org-log-note-headings'
2570 This option can also be set with on a per-file-basis with
2572 #+STARTUP: nologrepeat
2573 #+STARTUP: logrepeat
2574 #+STARTUP: lognoterepeat
2576 You can have local logging settings for a subtree by setting the LOGGING
2577 property to one or more of these keywords."
2578 :group 'org-todo
2579 :group 'org-progress
2580 :type '(choice
2581 (const :tag "Don't force a record" nil)
2582 (const :tag "Force recording the DONE state" time)
2583 (const :tag "Force recording a note with the DONE state" note)))
2586 (defgroup org-priorities nil
2587 "Priorities in Org-mode."
2588 :tag "Org Priorities"
2589 :group 'org-todo)
2591 (defcustom org-enable-priority-commands t
2592 "Non-nil means priority commands are active.
2593 When nil, these commands will be disabled, so that you never accidentally
2594 set a priority."
2595 :group 'org-priorities
2596 :type 'boolean)
2598 (defcustom org-highest-priority ?A
2599 "The highest priority of TODO items. A character like ?A, ?B etc.
2600 Must have a smaller ASCII number than `org-lowest-priority'."
2601 :group 'org-priorities
2602 :type 'character)
2604 (defcustom org-lowest-priority ?C
2605 "The lowest priority of TODO items. A character like ?A, ?B etc.
2606 Must have a larger ASCII number than `org-highest-priority'."
2607 :group 'org-priorities
2608 :type 'character)
2610 (defcustom org-default-priority ?B
2611 "The default priority of TODO items.
2612 This is the priority an item gets if no explicit priority is given.
2613 When starting to cycle on an empty priority the first step in the cycle
2614 depends on `org-priority-start-cycle-with-default'. The resulting first
2615 step priority must not exceed the range from `org-highest-priority' to
2616 `org-lowest-priority' which means that `org-default-priority' has to be
2617 in this range exclusive or inclusive the range boundaries. Else the
2618 first step refuses to set the default and the second will fall back
2619 to (depending on the command used) the highest or lowest priority."
2620 :group 'org-priorities
2621 :type 'character)
2623 (defcustom org-priority-start-cycle-with-default t
2624 "Non-nil means start with default priority when starting to cycle.
2625 When this is nil, the first step in the cycle will be (depending on the
2626 command used) one higher or lower than the default priority.
2627 See also `org-default-priority'."
2628 :group 'org-priorities
2629 :type 'boolean)
2631 (defcustom org-get-priority-function nil
2632 "Function to extract the priority from a string.
2633 The string is normally the headline. If this is nil Org computes the
2634 priority from the priority cookie like [#A] in the headline. It returns
2635 an integer, increasing by 1000 for each priority level.
2636 The user can set a different function here, which should take a string
2637 as an argument and return the numeric priority."
2638 :group 'org-priorities
2639 :version "24.1"
2640 :type 'function)
2642 (defgroup org-time nil
2643 "Options concerning time stamps and deadlines in Org-mode."
2644 :tag "Org Time"
2645 :group 'org)
2647 (defcustom org-insert-labeled-timestamps-at-point nil
2648 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2649 When nil, these labeled time stamps are forces into the second line of an
2650 entry, just after the headline. When scheduling from the global TODO list,
2651 the time stamp will always be forced into the second line."
2652 :group 'org-time
2653 :type 'boolean)
2655 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2656 "Formats for `format-time-string' which are used for time stamps.
2657 It is not recommended to change this constant.")
2659 (defcustom org-time-stamp-rounding-minutes '(0 5)
2660 "Number of minutes to round time stamps to.
2661 These are two values, the first applies when first creating a time stamp.
2662 The second applies when changing it with the commands `S-up' and `S-down'.
2663 When changing the time stamp, this means that it will change in steps
2664 of N minutes, as given by the second value.
2666 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2667 numbers should be factors of 60, so for example 5, 10, 15.
2669 When this is larger than 1, you can still force an exact time stamp by using
2670 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2671 and by using a prefix arg to `S-up/down' to specify the exact number
2672 of minutes to shift."
2673 :group 'org-time
2674 :get #'(lambda (var) ; Make sure both elements are there
2675 (if (integerp (default-value var))
2676 (list (default-value var) 5)
2677 (default-value var)))
2678 :type '(list
2679 (integer :tag "when inserting times")
2680 (integer :tag "when modifying times")))
2682 ;; Normalize old customizations of this variable.
2683 (when (integerp org-time-stamp-rounding-minutes)
2684 (setq org-time-stamp-rounding-minutes
2685 (list org-time-stamp-rounding-minutes
2686 org-time-stamp-rounding-minutes)))
2688 (defcustom org-display-custom-times nil
2689 "Non-nil means overlay custom formats over all time stamps.
2690 The formats are defined through the variable `org-time-stamp-custom-formats'.
2691 To turn this on on a per-file basis, insert anywhere in the file:
2692 #+STARTUP: customtime"
2693 :group 'org-time
2694 :set 'set-default
2695 :type 'sexp)
2696 (make-variable-buffer-local 'org-display-custom-times)
2698 (defcustom org-time-stamp-custom-formats
2699 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2700 "Custom formats for time stamps. See `format-time-string' for the syntax.
2701 These are overlaid over the default ISO format if the variable
2702 `org-display-custom-times' is set. Time like %H:%M should be at the
2703 end of the second format. The custom formats are also honored by export
2704 commands, if custom time display is turned on at the time of export."
2705 :group 'org-time
2706 :type 'sexp)
2708 (defun org-time-stamp-format (&optional long inactive)
2709 "Get the right format for a time string."
2710 (let ((f (if long (cdr org-time-stamp-formats)
2711 (car org-time-stamp-formats))))
2712 (if inactive
2713 (concat "[" (substring f 1 -1) "]")
2714 f)))
2716 (defcustom org-time-clocksum-format "%d:%02d"
2717 "The format string used when creating CLOCKSUM lines.
2718 This is also used when org-mode generates a time duration."
2719 :group 'org-time
2720 :type 'string)
2722 (defcustom org-time-clocksum-use-fractional nil
2723 "If non-nil, \\[org-clock-display] uses fractional times.
2724 org-mode generates a time duration."
2725 :group 'org-time
2726 :type 'boolean)
2728 (defcustom org-time-clocksum-fractional-format "%.2f"
2729 "The format string used when creating CLOCKSUM lines, or when
2730 org-mode generates a time duration."
2731 :group 'org-time
2732 :type 'string)
2734 (defcustom org-deadline-warning-days 14
2735 "No. of days before expiration during which a deadline becomes active.
2736 This variable governs the display in sparse trees and in the agenda.
2737 When 0 or negative, it means use this number (the absolute value of it)
2738 even if a deadline has a different individual lead time specified.
2740 Custom commands can set this variable in the options section."
2741 :group 'org-time
2742 :group 'org-agenda-daily/weekly
2743 :type 'integer)
2745 (defcustom org-read-date-prefer-future t
2746 "Non-nil means assume future for incomplete date input from user.
2747 This affects the following situations:
2748 1. The user gives a month but not a year.
2749 For example, if it is April and you enter \"feb 2\", this will be read
2750 as Feb 2, *next* year. \"May 5\", however, will be this year.
2751 2. The user gives a day, but no month.
2752 For example, if today is the 15th, and you enter \"3\", Org-mode will
2753 read this as the third of *next* month. However, if you enter \"17\",
2754 it will be considered as *this* month.
2756 If you set this variable to the symbol `time', then also the following
2757 will work:
2759 3. If the user gives a time.
2760 If the time is before now, it will be interpreted as tomorrow.
2762 Currently none of this works for ISO week specifications.
2764 When this option is nil, the current day, month and year will always be
2765 used as defaults.
2767 See also `org-agenda-jump-prefer-future'."
2768 :group 'org-time
2769 :type '(choice
2770 (const :tag "Never" nil)
2771 (const :tag "Check month and day" t)
2772 (const :tag "Check month, day, and time" time)))
2774 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2775 "Should the agenda jump command prefer the future for incomplete dates?
2776 The default is to do the same as configured in `org-read-date-prefer-future'.
2777 But you can also set a deviating value here.
2778 This may t or nil, or the symbol `org-read-date-prefer-future'."
2779 :group 'org-agenda
2780 :group 'org-time
2781 :version "24.1"
2782 :type '(choice
2783 (const :tag "Use org-read-date-prefer-future"
2784 org-read-date-prefer-future)
2785 (const :tag "Never" nil)
2786 (const :tag "Always" t)))
2788 (defcustom org-read-date-force-compatible-dates t
2789 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2791 Depending on the system Emacs is running on, certain dates cannot
2792 be represented with the type used internally to represent time.
2793 Dates between 1970-1-1 and 2038-1-1 can always be represented
2794 correctly. Some systems allow for earlier dates, some for later,
2795 some for both. One way to find out it to insert any date into an
2796 Org buffer, putting the cursor on the year and hitting S-up and
2797 S-down to test the range.
2799 When this variable is set to t, the date/time prompt will not let
2800 you specify dates outside the 1970-2037 range, so it is certain that
2801 these dates will work in whatever version of Emacs you are
2802 running, and also that you can move a file from one Emacs implementation
2803 to another. WHenever Org is forcing the year for you, it will display
2804 a message and beep.
2806 When this variable is nil, Org will check if the date is
2807 representable in the specific Emacs implementation you are using.
2808 If not, it will force a year, usually the current year, and beep
2809 to remind you. Currently this setting is not recommended because
2810 the likelihood that you will open your Org files in an Emacs that
2811 has limited date range is not negligible.
2813 A workaround for this problem is to use diary sexp dates for time
2814 stamps outside of this range."
2815 :group 'org-time
2816 :version "24.1"
2817 :type 'boolean)
2819 (defcustom org-read-date-display-live t
2820 "Non-nil means display current interpretation of date prompt live.
2821 This display will be in an overlay, in the minibuffer."
2822 :group 'org-time
2823 :type 'boolean)
2825 (defcustom org-read-date-popup-calendar t
2826 "Non-nil means pop up a calendar when prompting for a date.
2827 In the calendar, the date can be selected with mouse-1. However, the
2828 minibuffer will also be active, and you can simply enter the date as well.
2829 When nil, only the minibuffer will be available."
2830 :group 'org-time
2831 :type 'boolean)
2832 (if (fboundp 'defvaralias)
2833 (defvaralias 'org-popup-calendar-for-date-prompt
2834 'org-read-date-popup-calendar))
2836 (defcustom org-read-date-minibuffer-setup-hook nil
2837 "Hook to be used to set up keys for the date/time interface.
2838 Add key definitions to `minibuffer-local-map', which will be a temporary
2839 copy."
2840 :group 'org-time
2841 :type 'hook)
2843 (defcustom org-extend-today-until 0
2844 "The hour when your day really ends. Must be an integer.
2845 This has influence for the following applications:
2846 - When switching the agenda to \"today\". It it is still earlier than
2847 the time given here, the day recognized as TODAY is actually yesterday.
2848 - When a date is read from the user and it is still before the time given
2849 here, the current date and time will be assumed to be yesterday, 23:59.
2850 Also, timestamps inserted in remember templates follow this rule.
2852 IMPORTANT: This is a feature whose implementation is and likely will
2853 remain incomplete. Really, it is only here because past midnight seems to
2854 be the favorite working time of John Wiegley :-)"
2855 :group 'org-time
2856 :type 'integer)
2858 (defcustom org-use-effective-time nil
2859 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2860 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2861 \"effective time\" of any timestamps between midnight and 8am will be
2862 23:59 of the previous day."
2863 :group 'org-time
2864 :version "24.1"
2865 :type 'boolean)
2867 (defcustom org-edit-timestamp-down-means-later nil
2868 "Non-nil means S-down will increase the time in a time stamp.
2869 When nil, S-up will increase."
2870 :group 'org-time
2871 :type 'boolean)
2873 (defcustom org-calendar-follow-timestamp-change t
2874 "Non-nil means make the calendar window follow timestamp changes.
2875 When a timestamp is modified and the calendar window is visible, it will be
2876 moved to the new date."
2877 :group 'org-time
2878 :type 'boolean)
2880 (defgroup org-tags nil
2881 "Options concerning tags in Org-mode."
2882 :tag "Org Tags"
2883 :group 'org)
2885 (defcustom org-tag-alist nil
2886 "List of tags allowed in Org-mode files.
2887 When this list is nil, Org-mode will base TAG input on what is already in the
2888 buffer.
2889 The value of this variable is an alist, the car of each entry must be a
2890 keyword as a string, the cdr may be a character that is used to select
2891 that tag through the fast-tag-selection interface.
2892 See the manual for details."
2893 :group 'org-tags
2894 :type '(repeat
2895 (choice
2896 (cons (string :tag "Tag name")
2897 (character :tag "Access char"))
2898 (list :tag "Start radio group"
2899 (const :startgroup)
2900 (option (string :tag "Group description")))
2901 (list :tag "End radio group"
2902 (const :endgroup)
2903 (option (string :tag "Group description")))
2904 (const :tag "New line" (:newline)))))
2906 (defcustom org-tag-persistent-alist nil
2907 "List of tags that will always appear in all Org-mode files.
2908 This is in addition to any in buffer settings or customizations
2909 of `org-tag-alist'.
2910 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2911 The value of this variable is an alist, the car of each entry must be a
2912 keyword as a string, the cdr may be a character that is used to select
2913 that tag through the fast-tag-selection interface.
2914 See the manual for details.
2915 To disable these tags on a per-file basis, insert anywhere in the file:
2916 #+STARTUP: noptag"
2917 :group 'org-tags
2918 :type '(repeat
2919 (choice
2920 (cons (string :tag "Tag name")
2921 (character :tag "Access char"))
2922 (const :tag "Start radio group" (:startgroup))
2923 (const :tag "End radio group" (:endgroup))
2924 (const :tag "New line" (:newline)))))
2926 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2927 "If non-nil, always offer completion for all tags of all agenda files.
2928 Instead of customizing this variable directly, you might want to
2929 set it locally for capture buffers, because there no list of
2930 tags in that file can be created dynamically (there are none).
2932 (add-hook 'org-capture-mode-hook
2933 (lambda ()
2934 (set (make-local-variable
2935 'org-complete-tags-always-offer-all-agenda-tags)
2936 t)))"
2937 :group 'org-tags
2938 :version "24.1"
2939 :type 'boolean)
2941 (defvar org-file-tags nil
2942 "List of tags that can be inherited by all entries in the file.
2943 The tags will be inherited if the variable `org-use-tag-inheritance'
2944 says they should be.
2945 This variable is populated from #+FILETAGS lines.")
2947 (defcustom org-use-fast-tag-selection 'auto
2948 "Non-nil means use fast tag selection scheme.
2949 This is a special interface to select and deselect tags with single keys.
2950 When nil, fast selection is never used.
2951 When the symbol `auto', fast selection is used if and only if selection
2952 characters for tags have been configured, either through the variable
2953 `org-tag-alist' or through a #+TAGS line in the buffer.
2954 When t, fast selection is always used and selection keys are assigned
2955 automatically if necessary."
2956 :group 'org-tags
2957 :type '(choice
2958 (const :tag "Always" t)
2959 (const :tag "Never" nil)
2960 (const :tag "When selection characters are configured" 'auto)))
2962 (defcustom org-fast-tag-selection-single-key nil
2963 "Non-nil means fast tag selection exits after first change.
2964 When nil, you have to press RET to exit it.
2965 During fast tag selection, you can toggle this flag with `C-c'.
2966 This variable can also have the value `expert'. In this case, the window
2967 displaying the tags menu is not even shown, until you press C-c again."
2968 :group 'org-tags
2969 :type '(choice
2970 (const :tag "No" nil)
2971 (const :tag "Yes" t)
2972 (const :tag "Expert" expert)))
2974 (defvar org-fast-tag-selection-include-todo nil
2975 "Non-nil means fast tags selection interface will also offer TODO states.
2976 This is an undocumented feature, you should not rely on it.")
2978 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2979 "The column to which tags should be indented in a headline.
2980 If this number is positive, it specifies the column. If it is negative,
2981 it means that the tags should be flushright to that column. For example,
2982 -80 works well for a normal 80 character screen.
2983 When 0, place tags directly after headline text, with only one space in
2984 between."
2985 :group 'org-tags
2986 :type 'integer)
2988 (defcustom org-auto-align-tags t
2989 "Non-nil keeps tags aligned when modifying headlines.
2990 Some operations (i.e. demoting) change the length of a headline and
2991 therefore shift the tags around. With this option turned on, after
2992 each such operation the tags are again aligned to `org-tags-column'."
2993 :group 'org-tags
2994 :type 'boolean)
2996 (defcustom org-use-tag-inheritance t
2997 "Non-nil means tags in levels apply also for sublevels.
2998 When nil, only the tags directly given in a specific line apply there.
2999 This may also be a list of tags that should be inherited, or a regexp that
3000 matches tags that should be inherited. Additional control is possible
3001 with the variable `org-tags-exclude-from-inheritance' which gives an
3002 explicit list of tags to be excluded from inheritance., even if the value of
3003 `org-use-tag-inheritance' would select it for inheritance.
3005 If this option is t, a match early-on in a tree can lead to a large
3006 number of matches in the subtree when constructing the agenda or creating
3007 a sparse tree. If you only want to see the first match in a tree during
3008 a search, check out the variable `org-tags-match-list-sublevels'."
3009 :group 'org-tags
3010 :type '(choice
3011 (const :tag "Not" nil)
3012 (const :tag "Always" t)
3013 (repeat :tag "Specific tags" (string :tag "Tag"))
3014 (regexp :tag "Tags matched by regexp")))
3016 (defcustom org-tags-exclude-from-inheritance nil
3017 "List of tags that should never be inherited.
3018 This is a way to exclude a few tags from inheritance. For way to do
3019 the opposite, to actively allow inheritance for selected tags,
3020 see the variable `org-use-tag-inheritance'."
3021 :group 'org-tags
3022 :type '(repeat (string :tag "Tag")))
3024 (defun org-tag-inherit-p (tag)
3025 "Check if TAG is one that should be inherited."
3026 (cond
3027 ((member tag org-tags-exclude-from-inheritance) nil)
3028 ((eq org-use-tag-inheritance t) t)
3029 ((not org-use-tag-inheritance) nil)
3030 ((stringp org-use-tag-inheritance)
3031 (string-match org-use-tag-inheritance tag))
3032 ((listp org-use-tag-inheritance)
3033 (member tag org-use-tag-inheritance))
3034 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3036 (defcustom org-tags-match-list-sublevels t
3037 "Non-nil means list also sublevels of headlines matching a search.
3038 This variable applies to tags/property searches, and also to stuck
3039 projects because this search is based on a tags match as well.
3041 When set to the symbol `indented', sublevels are indented with
3042 leading dots.
3044 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3045 the sublevels of a headline matching a tag search often also match
3046 the same search. Listing all of them can create very long lists.
3047 Setting this variable to nil causes subtrees of a match to be skipped.
3049 This variable is semi-obsolete and probably should always be true. It
3050 is better to limit inheritance to certain tags using the variables
3051 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3052 :group 'org-tags
3053 :type '(choice
3054 (const :tag "No, don't list them" nil)
3055 (const :tag "Yes, do list them" t)
3056 (const :tag "List them, indented with leading dots" indented)))
3058 (defcustom org-tags-sort-function nil
3059 "When set, tags are sorted using this function as a comparator."
3060 :group 'org-tags
3061 :type '(choice
3062 (const :tag "No sorting" nil)
3063 (const :tag "Alphabetical" string<)
3064 (const :tag "Reverse alphabetical" string>)
3065 (function :tag "Custom function" nil)))
3067 (defvar org-tags-history nil
3068 "History of minibuffer reads for tags.")
3069 (defvar org-last-tags-completion-table nil
3070 "The last used completion table for tags.")
3071 (defvar org-after-tags-change-hook nil
3072 "Hook that is run after the tags in a line have changed.")
3074 (defgroup org-properties nil
3075 "Options concerning properties in Org-mode."
3076 :tag "Org Properties"
3077 :group 'org)
3079 (defcustom org-property-format "%-10s %s"
3080 "How property key/value pairs should be formatted by `indent-line'.
3081 When `indent-line' hits a property definition, it will format the line
3082 according to this format, mainly to make sure that the values are
3083 lined-up with respect to each other."
3084 :group 'org-properties
3085 :type 'string)
3087 (defcustom org-properties-postprocess-alist nil
3088 "Alist of properties and functions to adjust inserted values.
3089 Elements of this alist must be of the form
3091 ([string] [function])
3093 where [string] must be a property name and [function] must be a
3094 lambda expression: this lambda expression must take one argument,
3095 the value to adjust, and return the new value as a string.
3097 For example, this element will allow the property \"Remaining\"
3098 to be updated wrt the relation between the \"Effort\" property
3099 and the clock summary:
3101 ((\"Remaining\" (lambda(value)
3102 (let ((clocksum (org-clock-sum-current-item))
3103 (effort (org-duration-string-to-minutes
3104 (org-entry-get (point) \"Effort\"))))
3105 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3106 :group 'org-properties
3107 :version "24.1"
3108 :type '(alist :key-type (string :tag "Property")
3109 :value-type (function :tag "Function")))
3111 (defcustom org-use-property-inheritance nil
3112 "Non-nil means properties apply also for sublevels.
3114 This setting is chiefly used during property searches. Turning it on can
3115 cause significant overhead when doing a search, which is why it is not
3116 on by default.
3118 When nil, only the properties directly given in the current entry count.
3119 When t, every property is inherited. The value may also be a list of
3120 properties that should have inheritance, or a regular expression matching
3121 properties that should be inherited.
3123 However, note that some special properties use inheritance under special
3124 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3125 and the properties ending in \"_ALL\" when they are used as descriptor
3126 for valid values of a property.
3128 Note for programmers:
3129 When querying an entry with `org-entry-get', you can control if inheritance
3130 should be used. By default, `org-entry-get' looks only at the local
3131 properties. You can request inheritance by setting the inherit argument
3132 to t (to force inheritance) or to `selective' (to respect the setting
3133 in this variable)."
3134 :group 'org-properties
3135 :type '(choice
3136 (const :tag "Not" nil)
3137 (const :tag "Always" t)
3138 (repeat :tag "Specific properties" (string :tag "Property"))
3139 (regexp :tag "Properties matched by regexp")))
3141 (defun org-property-inherit-p (property)
3142 "Check if PROPERTY is one that should be inherited."
3143 (cond
3144 ((eq org-use-property-inheritance t) t)
3145 ((not org-use-property-inheritance) nil)
3146 ((stringp org-use-property-inheritance)
3147 (string-match org-use-property-inheritance property))
3148 ((listp org-use-property-inheritance)
3149 (member property org-use-property-inheritance))
3150 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3152 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3153 "The default column format, if no other format has been defined.
3154 This variable can be set on the per-file basis by inserting a line
3156 #+COLUMNS: %25ITEM ....."
3157 :group 'org-properties
3158 :type 'string)
3160 (defcustom org-columns-ellipses ".."
3161 "The ellipses to be used when a field in column view is truncated.
3162 When this is the empty string, as many characters as possible are shown,
3163 but then there will be no visual indication that the field has been truncated.
3164 When this is a string of length N, the last N characters of a truncated
3165 field are replaced by this string. If the column is narrower than the
3166 ellipses string, only part of the ellipses string will be shown."
3167 :group 'org-properties
3168 :type 'string)
3170 (defcustom org-columns-modify-value-for-display-function nil
3171 "Function that modifies values for display in column view.
3172 For example, it can be used to cut out a certain part from a time stamp.
3173 The function must take 2 arguments:
3175 column-title The title of the column (*not* the property name)
3176 value The value that should be modified.
3178 The function should return the value that should be displayed,
3179 or nil if the normal value should be used."
3180 :group 'org-properties
3181 :type 'function)
3183 (defcustom org-effort-property "Effort"
3184 "The property that is being used to keep track of effort estimates.
3185 Effort estimates given in this property need to have the format H:MM."
3186 :group 'org-properties
3187 :group 'org-progress
3188 :type '(string :tag "Property"))
3190 (defconst org-global-properties-fixed
3191 '(("VISIBILITY_ALL" . "folded children content all")
3192 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3193 "List of property/value pairs that can be inherited by any entry.
3195 These are fixed values, for the preset properties. The user variable
3196 that can be used to add to this list is `org-global-properties'.
3198 The entries in this list are cons cells where the car is a property
3199 name and cdr is a string with the value. If the value represents
3200 multiple items like an \"_ALL\" property, separate the items by
3201 spaces.")
3203 (defcustom org-global-properties nil
3204 "List of property/value pairs that can be inherited by any entry.
3206 This list will be combined with the constant `org-global-properties-fixed'.
3208 The entries in this list are cons cells where the car is a property
3209 name and cdr is a string with the value.
3211 You can set buffer-local values for the same purpose in the variable
3212 `org-file-properties' this by adding lines like
3214 #+PROPERTY: NAME VALUE"
3215 :group 'org-properties
3216 :type '(repeat
3217 (cons (string :tag "Property")
3218 (string :tag "Value"))))
3220 (defvar org-file-properties nil
3221 "List of property/value pairs that can be inherited by any entry.
3222 Valid for the current buffer.
3223 This variable is populated from #+PROPERTY lines.")
3224 (make-variable-buffer-local 'org-file-properties)
3226 (defgroup org-agenda nil
3227 "Options concerning agenda views in Org-mode."
3228 :tag "Org Agenda"
3229 :group 'org)
3231 (defvar org-category nil
3232 "Variable used by org files to set a category for agenda display.
3233 Such files should use a file variable to set it, for example
3235 # -*- mode: org; org-category: \"ELisp\"
3237 or contain a special line
3239 #+CATEGORY: ELisp
3241 If the file does not specify a category, then file's base name
3242 is used instead.")
3243 (make-variable-buffer-local 'org-category)
3244 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3246 (defcustom org-agenda-files nil
3247 "The files to be used for agenda display.
3248 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3249 \\[org-remove-file]. You can also use customize to edit the list.
3251 If an entry is a directory, all files in that directory that are matched by
3252 `org-agenda-file-regexp' will be part of the file list.
3254 If the value of the variable is not a list but a single file name, then
3255 the list of agenda files is actually stored and maintained in that file, one
3256 agenda file per line. In this file paths can be given relative to
3257 `org-directory'. Tilde expansion and environment variable substitution
3258 are also made."
3259 :group 'org-agenda
3260 :type '(choice
3261 (repeat :tag "List of files and directories" file)
3262 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3264 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3265 "Regular expression to match files for `org-agenda-files'.
3266 If any element in the list in that variable contains a directory instead
3267 of a normal file, all files in that directory that are matched by this
3268 regular expression will be included."
3269 :group 'org-agenda
3270 :type 'regexp)
3272 (defcustom org-agenda-text-search-extra-files nil
3273 "List of extra files to be searched by text search commands.
3274 These files will be search in addition to the agenda files by the
3275 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3276 Note that these files will only be searched for text search commands,
3277 not for the other agenda views like todo lists, tag searches or the weekly
3278 agenda. This variable is intended to list notes and possibly archive files
3279 that should also be searched by these two commands.
3280 In fact, if the first element in the list is the symbol `agenda-archives',
3281 than all archive files of all agenda files will be added to the search
3282 scope."
3283 :group 'org-agenda
3284 :type '(set :greedy t
3285 (const :tag "Agenda Archives" agenda-archives)
3286 (repeat :inline t (file))))
3288 (if (fboundp 'defvaralias)
3289 (defvaralias 'org-agenda-multi-occur-extra-files
3290 'org-agenda-text-search-extra-files))
3292 (defcustom org-agenda-skip-unavailable-files nil
3293 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3294 A nil value means to remove them, after a query, from the list."
3295 :group 'org-agenda
3296 :type 'boolean)
3298 (defcustom org-calendar-to-agenda-key [?c]
3299 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3300 The command `org-calendar-goto-agenda' will be bound to this key. The
3301 default is the character `c' because then `c' can be used to switch back and
3302 forth between agenda and calendar."
3303 :group 'org-agenda
3304 :type 'sexp)
3306 (defcustom org-calendar-agenda-action-key [?k]
3307 "The key to be installed in `calendar-mode-map' for agenda-action.
3308 The command `org-agenda-action' will be bound to this key. The
3309 default is the character `k' because we use the same key in the agenda."
3310 :group 'org-agenda
3311 :type 'sexp)
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
3320 key."
3321 :group 'org-agenda
3322 :type 'sexp)
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."
3329 :group 'org-agenda
3330 :type '(choice
3331 (const :tag "The standard Emacs diary file" diary-file)
3332 (file :tag "Special Org file diary entries")))
3334 (eval-after-load "calendar"
3335 '(progn
3336 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3337 'org-calendar-goto-agenda)
3338 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3339 'org-agenda-action)
3340 (add-hook 'calendar-mode-hook
3341 (lambda ()
3342 (unless (eq org-agenda-diary-file 'diary-file)
3343 (define-key calendar-mode-map
3344 org-calendar-insert-diary-entry-key
3345 'org-agenda-diary-entry))))))
3347 (defgroup org-latex nil
3348 "Options for embedding LaTeX code into Org-mode."
3349 :tag "Org LaTeX"
3350 :group 'org)
3352 (defcustom org-format-latex-options
3353 '(:foreground default :background default :scale 1.0
3354 :html-foreground "Black" :html-background "Transparent"
3355 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3356 "Options for creating images from LaTeX fragments.
3357 This is a property list with the following properties:
3358 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3359 `default' means use the foreground of the default face.
3360 :background the background color, or \"Transparent\".
3361 `default' means use the background of the default 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 \\ [...\\]"
3373 :group 'org-latex
3374 :type 'plist)
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."
3379 :group 'org-latex
3380 :version "24.1"
3381 :type 'boolean)
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."
3389 :group 'org-latex
3390 :version "24.1"
3391 :type '(choice
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\"."
3407 :group 'org-latex
3408 :version "24.1"
3409 :type '(choice
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"
3421 :group 'org-latex
3422 :version "24.1"
3423 :type '(choice
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."
3431 :group 'org-latex
3432 ;; :version "24.3"
3433 :type 'string)
3435 (defun org-format-latex-mathml-available-p ()
3436 "Return t if `org-latex-to-mathml-convert-command' is usable."
3437 (save-match-data
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)
3443 (if (string-match
3444 "%j" org-latex-to-mathml-convert-command)
3445 (file-readable-p org-latex-to-mathml-jar-file)
3446 t))))))
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
3453 \[PACKAGES]
3454 \[DEFAULT-PACKAGES]
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
3473 will be appended."
3474 :group 'org-latex
3475 :type 'string)
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)
3485 val)))
3487 (defun org-get-packages-alist (var)
3489 "Get the packages alist and make sure it has 3 elements per entry."
3490 (mapcar (lambda (x)
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)
3501 ("T1" "fontenc" t)
3502 ("" "fixltx2e" nil)
3503 ("" "graphicx" t)
3504 ("" "longtable" nil)
3505 ("" "float" nil)
3506 ("" "wrapfig" nil)
3507 ("" "soul" t)
3508 ("" "textcomp" t)
3509 ("" "marvosym" t)
3510 ("" "wasysym" t)
3511 ("" "latexsym" t)
3512 ("" "amssymb" t)
3513 ("" "hyperref" nil)
3514 "\\tolerance=1000"
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
3540 :version "24.1"
3541 :type '(repeat
3542 (choice
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
3563 :type '(repeat
3564 (choice
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"
3575 :group 'org)
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
3583 :type 'boolean)
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
3590 make this work.
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
3599 :type 'boolean)
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
3606 :version "24.1"
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
3618 ;; :version "24.3"
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
3627 :type 'boolean)
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
3633 :type 'boolean)
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
3638 org-level-* faces."
3639 :group 'org-appearance
3640 :type 'boolean)
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
3645 :type 'boolean)
3647 (defcustom org-hide-emphasis-markers nil
3648 "Non-nil mean font-lock should hide the emphasis marker characters."
3649 :group 'org-appearance
3650 :type 'boolean)
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
3656 :version "24.1"
3657 :type 'boolean)
3659 (defcustom org-pretty-entities-include-sub-superscripts t
3660 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3661 :group 'org-appearance
3662 :version "24.1"
3663 :type 'boolean)
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."
3681 (set var val)
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)
3686 (pre (car e))
3687 (post (nth 1 e))
3688 (border (nth 2 e))
3689 (body (nth 3 e))
3690 (nl (nth 4 e))
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) "-")))
3705 (if (> nl 0)
3706 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3707 (int-to-string nl) "\\}")))
3708 ;; Make the regexp
3709 (setq org-emph-re
3710 (concat "\\([" pre "]\\|^\\)"
3711 "\\("
3712 "\\([" markers "]\\)"
3713 "\\("
3714 "[^" border "]\\|"
3715 "[^" border "]"
3716 body1
3717 "[^" border "]"
3718 "\\)"
3719 "\\3\\)"
3720 "\\([" post "]\\|$\\)"))
3721 (setq org-verbatim-re
3722 (concat "\\([" pre "]\\|^\\)"
3723 "\\("
3724 "\\([" vmarkers "]\\)"
3725 "\\("
3726 "[^" border "]\\|"
3727 "[^" border "]"
3728 body1
3729 "[^" border "]"
3730 "\\)"
3731 "\\3\\)"
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
3753 :type '(list
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))
3768 "<del>" "</del>")
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
3780 :type '(repeat
3781 (list
3782 (string :tag "Marker character")
3783 (choice
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"
3800 :group 'org)
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
3809 :type 'boolean)
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
3818 :type 'boolean)
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
3824 :type 'function)
3826 ;;; Functions and variables from their packages
3827 ;; Declared here to avoid compiler warnings
3829 ;; XEmacs only
3830 (defvar outline-mode-menu-heading)
3831 (defvar outline-mode-menu-show)
3832 (defvar outline-mode-menu-hide)
3833 (defvar zmacs-regions) ; XEmacs regions
3835 ;; Emacs only
3836 (defvar mark-active)
3838 ;; Various packages
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" ())
3856 (declare-function
3857 org-agenda-format-item "org-agenda"
3858 (extra txt &optional 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"
3865 (beg end))
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.
3909 (eval-and-compile
3910 (org-autoload "org-table"
3911 '(org-table-align org-table-begin org-table-blank-field
3912 org-table-convert org-table-convert-region org-table-copy-down
3913 org-table-copy-region org-table-create
3914 org-table-create-or-convert-from-region
3915 org-table-create-with-table.el org-table-current-dline
3916 org-table-cut-region org-table-delete-column org-table-edit-field
3917 org-table-edit-formulas org-table-end org-table-eval-formula
3918 org-table-export org-table-field-info
3919 org-table-get-stored-formulas org-table-goto-column
3920 org-table-hline-and-move org-table-import org-table-insert-column
3921 org-table-insert-hline org-table-insert-row org-table-iterate
3922 org-table-justify-field-maybe org-table-kill-row
3923 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3924 org-table-move-column org-table-move-column-left
3925 org-table-move-column-right org-table-move-row
3926 org-table-move-row-down org-table-move-row-up
3927 org-table-next-field org-table-next-row org-table-paste-rectangle
3928 org-table-previous-field org-table-recalculate
3929 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3930 org-table-toggle-coordinate-overlays
3931 org-table-toggle-formula-debugger org-table-wrap-region
3932 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3933 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3934 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3936 (defun org-at-table-p (&optional table-type)
3937 "Return t if the cursor is inside an org-type table.
3938 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3939 (if org-enable-table-editor
3940 (save-excursion
3941 (beginning-of-line 1)
3942 (looking-at (if table-type org-table-any-line-regexp
3943 org-table-line-regexp)))
3944 nil))
3945 (defsubst org-table-p () (org-at-table-p))
3947 (defun org-at-table.el-p ()
3948 "Return t if and only if we are at a table.el table."
3949 (and (org-at-table-p 'any)
3950 (save-excursion
3951 (goto-char (org-table-begin 'any))
3952 (looking-at org-table1-hline-regexp))))
3953 (defun org-table-recognize-table.el ()
3954 "If there is a table.el table nearby, recognize it and move into it."
3955 (if org-table-tab-recognizes-table.el
3956 (if (org-at-table.el-p)
3957 (progn
3958 (beginning-of-line 1)
3959 (if (looking-at org-table-dataline-regexp)
3961 (if (looking-at org-table1-hline-regexp)
3962 (progn
3963 (beginning-of-line 2)
3964 (if (looking-at org-table-any-border-regexp)
3965 (beginning-of-line -1)))))
3966 (if (re-search-forward "|" (org-table-end t) t)
3967 (progn
3968 (require 'table)
3969 (if (table--at-cell-p (point))
3971 (message "recognizing table.el table...")
3972 (table-recognize-table)
3973 (message "recognizing table.el table...done")))
3974 (error "This should not happen"))
3976 nil)
3977 nil))
3979 (defun org-at-table-hline-p ()
3980 "Return t if the cursor is inside a hline in a table."
3981 (if org-enable-table-editor
3982 (save-excursion
3983 (beginning-of-line 1)
3984 (looking-at org-table-hline-regexp))
3985 nil))
3987 (defvar org-table-clean-did-remove-column nil)
3989 (defun org-table-map-tables (function &optional quietly)
3990 "Apply FUNCTION to the start of all tables in the buffer."
3991 (save-excursion
3992 (save-restriction
3993 (widen)
3994 (goto-char (point-min))
3995 (while (re-search-forward org-table-any-line-regexp nil t)
3996 (unless quietly
3997 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3998 (beginning-of-line 1)
3999 (when (and (looking-at org-table-line-regexp)
4000 ;; Exclude tables in src/example/verbatim/clocktable blocks
4001 (not (org-in-block-p '("src" "example"))))
4002 (save-excursion (funcall function))
4003 (or (looking-at org-table-line-regexp)
4004 (forward-char 1)))
4005 (re-search-forward org-table-any-border-regexp nil 1))))
4006 (unless quietly (message "Mapping tables: done")))
4008 ;; Declare and autoload functions from org-exp.el & Co
4010 (declare-function org-default-export-plist "org-exp")
4011 (declare-function org-infile-export-plist "org-exp")
4012 (declare-function org-get-current-options "org-exp")
4013 (eval-and-compile
4014 (org-autoload "org-exp"
4015 '(org-export org-export-visible
4016 org-insert-export-options-template
4017 org-table-clean-before-export))
4018 (org-autoload "org-ascii"
4019 '(org-export-as-ascii org-export-ascii-preprocess
4020 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4021 org-export-region-as-ascii))
4022 (org-autoload "org-latex"
4023 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4024 org-replace-region-by-latex org-export-region-as-latex
4025 org-export-as-latex org-export-as-pdf
4026 org-export-as-pdf-and-open))
4027 (org-autoload "org-html"
4028 '(org-export-as-html-and-open
4029 org-export-as-html-batch org-export-as-html-to-buffer
4030 org-replace-region-by-html org-export-region-as-html
4031 org-export-as-html))
4032 (org-autoload "org-docbook"
4033 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4034 org-replace-region-by-docbook org-export-region-as-docbook
4035 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4036 org-export-as-docbook))
4037 (org-autoload "org-icalendar"
4038 '(org-export-icalendar-this-file
4039 org-export-icalendar-all-agenda-files
4040 org-export-icalendar-combine-agenda-files))
4041 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4042 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4044 ;; Declare and autoload functions from org-agenda.el
4046 (eval-and-compile
4047 (org-autoload "org-agenda"
4048 '(org-agenda org-agenda-list org-search-view
4049 org-todo-list org-tags-view org-agenda-list-stuck-projects
4050 org-diary org-agenda-to-appt
4051 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4053 ;; Autoload org-remember
4055 (eval-and-compile
4056 (org-autoload "org-remember"
4057 '(org-remember-insinuate org-remember-annotation
4058 org-remember-apply-template org-remember org-remember-handler)))
4060 (eval-and-compile
4061 (org-autoload "org-capture"
4062 '(org-capture org-capture-insert-template-here
4063 org-capture-import-remember-templates)))
4065 ;; Autoload org-clock.el
4067 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4068 (beg end))
4069 (declare-function org-clock-update-mode-line "org-clock" ())
4070 (declare-function org-resolve-clocks "org-clock"
4071 (&optional also-non-dangling-p prompt last-valid))
4072 (defvar org-clock-start-time)
4073 (defvar org-clock-marker (make-marker)
4074 "Marker recording the last clock-in.")
4075 (defvar org-clock-hd-marker (make-marker)
4076 "Marker recording the last clock-in, but the headline position.")
4077 (defvar org-clock-heading ""
4078 "The heading of the current clock entry.")
4079 (defun org-clock-is-active ()
4080 "Return non-nil if clock is currently running.
4081 The return value is actually the clock marker."
4082 (marker-buffer org-clock-marker))
4084 (eval-and-compile
4085 (org-autoload
4086 "org-clock"
4087 '(org-clock-in org-clock-out org-clock-cancel
4088 org-clock-goto org-clock-sum org-clock-display
4089 org-clock-remove-overlays org-clock-report
4090 org-clocktable-shift org-dblock-write:clocktable
4091 org-get-clocktable org-resolve-clocks)))
4093 (defun org-clock-update-time-maybe ()
4094 "If this is a CLOCK line, update it and return t.
4095 Otherwise, return nil."
4096 (interactive)
4097 (save-excursion
4098 (beginning-of-line 1)
4099 (skip-chars-forward " \t")
4100 (when (looking-at org-clock-string)
4101 (let ((re (concat "[ \t]*" org-clock-string
4102 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4103 "\\([ \t]*=>.*\\)?\\)?"))
4104 ts te h m s neg)
4105 (cond
4106 ((not (looking-at re))
4107 nil)
4108 ((not (match-end 2))
4109 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4110 (> org-clock-marker (point))
4111 (<= org-clock-marker (point-at-eol)))
4112 ;; The clock is running here
4113 (setq org-clock-start-time
4114 (apply 'encode-time
4115 (org-parse-time-string (match-string 1))))
4116 (org-clock-update-mode-line)))
4118 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4119 (end-of-line 1)
4120 (setq ts (match-string 1)
4121 te (match-string 3))
4122 (setq s (- (org-float-time
4123 (apply 'encode-time (org-parse-time-string te)))
4124 (org-float-time
4125 (apply 'encode-time (org-parse-time-string ts))))
4126 neg (< s 0)
4127 s (abs s)
4128 h (floor (/ s 3600))
4129 s (- s (* 3600 h))
4130 m (floor (/ s 60))
4131 s (- s (* 60 s)))
4132 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4133 t))))))
4135 (defun org-check-running-clock ()
4136 "Check if the current buffer contains the running clock.
4137 If yes, offer to stop it and to save the buffer with the changes."
4138 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4139 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4140 (buffer-name))))
4141 (org-clock-out)
4142 (when (y-or-n-p "Save changed buffer?")
4143 (save-buffer))))
4145 (defun org-clocktable-try-shift (dir n)
4146 "Check if this line starts a clock table, if yes, shift the time block."
4147 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4148 (org-clocktable-shift dir n)))
4150 ;; Autoload org-timer.el
4152 (eval-and-compile
4153 (org-autoload
4154 "org-timer"
4155 '(org-timer-start org-timer org-timer-item
4156 org-timer-change-times-in-region
4157 org-timer-set-timer
4158 org-timer-reset-timers
4159 org-timer-show-remaining-time)))
4161 ;; Autoload org-feed.el
4163 (eval-and-compile
4164 (org-autoload
4165 "org-feed"
4166 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4169 ;; Autoload org-indent.el
4171 ;; Define the variable already here, to make sure we have it.
4172 (defvar org-indent-mode nil
4173 "Non-nil if Org-Indent mode is enabled.
4174 Use the command `org-indent-mode' to change this variable.")
4176 (eval-and-compile
4177 (org-autoload
4178 "org-indent"
4179 '(org-indent-mode)))
4181 ;; Autoload org-mobile.el
4183 (eval-and-compile
4184 (org-autoload
4185 "org-mobile"
4186 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4188 ;; Autoload archiving code
4189 ;; The stuff that is needed for cycling and tags has to be defined here.
4191 (defgroup org-archive nil
4192 "Options concerning archiving in Org-mode."
4193 :tag "Org Archive"
4194 :group 'org-structure)
4196 (defcustom org-archive-location "%s_archive::"
4197 "The location where subtrees should be archived.
4199 The value of this variable is a string, consisting of two parts,
4200 separated by a double-colon. The first part is a filename and
4201 the second part is a headline.
4203 When the filename is omitted, archiving happens in the same file.
4204 %s in the filename will be replaced by the current file
4205 name (without the directory part). Archiving to a different file
4206 is useful to keep archived entries from contributing to the
4207 Org-mode Agenda.
4209 The archived entries will be filed as subtrees of the specified
4210 headline. When the headline is omitted, the subtrees are simply
4211 filed away at the end of the file, as top-level entries. Also in
4212 the heading you can use %s to represent the file name, this can be
4213 useful when using the same archive for a number of different files.
4215 Here are a few examples:
4216 \"%s_archive::\"
4217 If the current file is Projects.org, archive in file
4218 Projects.org_archive, as top-level trees. This is the default.
4220 \"::* Archived Tasks\"
4221 Archive in the current file, under the top-level headline
4222 \"* Archived Tasks\".
4224 \"~/org/archive.org::\"
4225 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4227 \"~/org/archive.org::* From %s\"
4228 Archive in file ~/org/archive.org (absolute path), under headlines
4229 \"From FILENAME\" where file name is the current file name.
4231 \"~/org/datetree.org::datetree/* Finished Tasks\"
4232 The \"datetree/\" string is special, signifying to archive
4233 items to the datetree. Items are placed in either the CLOSED
4234 date of the item, or the current date if there is no CLOSED date.
4235 The heading will be a subentry to the current date. There doesn't
4236 need to be a heading, but there always needs to be a slash after
4237 datetree. For example, to store archived items directly in the
4238 datetree, use \"~/org/datetree.org::datetree/\".
4240 \"basement::** Finished Tasks\"
4241 Archive in file ./basement (relative path), as level 3 trees
4242 below the level 2 heading \"** Finished Tasks\".
4244 You may set this option on a per-file basis by adding to the buffer a
4245 line like
4247 #+ARCHIVE: basement::** Finished Tasks
4249 You may also define it locally for a subtree by setting an ARCHIVE property
4250 in the entry. If such a property is found in an entry, or anywhere up
4251 the hierarchy, it will be used."
4252 :group 'org-archive
4253 :type 'string)
4255 (defcustom org-archive-tag "ARCHIVE"
4256 "The tag that marks a subtree as archived.
4257 An archived subtree does not open during visibility cycling, and does
4258 not contribute to the agenda listings.
4259 After changing this, font-lock must be restarted in the relevant buffers to
4260 get the proper fontification."
4261 :group 'org-archive
4262 :group 'org-keywords
4263 :type 'string)
4265 (defcustom org-agenda-skip-archived-trees t
4266 "Non-nil means the agenda will skip any items located in archived trees.
4267 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4268 variable is no longer recommended, you should leave it at the value t.
4269 Instead, use the key `v' to cycle the archives-mode in the agenda."
4270 :group 'org-archive
4271 :group 'org-agenda-skip
4272 :type 'boolean)
4274 (defcustom org-columns-skip-archived-trees t
4275 "Non-nil means ignore archived trees when creating column view."
4276 :group 'org-archive
4277 :group 'org-properties
4278 :type 'boolean)
4280 (defcustom org-cycle-open-archived-trees nil
4281 "Non-nil means `org-cycle' will open archived trees.
4282 An archived tree is a tree marked with the tag ARCHIVE.
4283 When nil, archived trees will stay folded. You can still open them with
4284 normal outline commands like `show-all', but not with the cycling commands."
4285 :group 'org-archive
4286 :group 'org-cycle
4287 :type 'boolean)
4289 (defcustom org-sparse-tree-open-archived-trees nil
4290 "Non-nil means sparse tree construction shows matches in archived trees.
4291 When nil, matches in these trees are highlighted, but the trees are kept in
4292 collapsed state."
4293 :group 'org-archive
4294 :group 'org-sparse-trees
4295 :type 'boolean)
4297 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4298 "The default date type when building a sparse tree.
4299 When this is nil, a date is a scheduled or a deadline timestamp.
4300 Otherwise, these types are allowed:
4302 all: all timestamps
4303 active: only active timestamps (<...>)
4304 inactive: only inactive timestamps (<...)
4305 scheduled: only scheduled timestamps
4306 deadline: only deadline timestamps"
4307 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4308 (const :tag "All timestamps" all)
4309 (const :tag "Only active timestamps" active)
4310 (const :tag "Only inactive timestamps" inactive)
4311 (const :tag "Only scheduled timestamps" scheduled)
4312 (const :tag "Only deadline timestamps" deadline))
4313 ;; :version "24.3"
4314 :group 'org-sparse-trees)
4316 (defun org-cycle-hide-archived-subtrees (state)
4317 "Re-hide all archived subtrees after a visibility state change."
4318 (when (and (not org-cycle-open-archived-trees)
4319 (not (memq state '(overview folded))))
4320 (save-excursion
4321 (let* ((globalp (memq state '(contents all)))
4322 (beg (if globalp (point-min) (point)))
4323 (end (if globalp (point-max) (org-end-of-subtree t))))
4324 (org-hide-archived-subtrees beg end)
4325 (goto-char beg)
4326 (if (looking-at (concat ".*:" org-archive-tag ":"))
4327 (message "%s" (substitute-command-keys
4328 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4330 (defun org-force-cycle-archived ()
4331 "Cycle subtree even if it is archived."
4332 (interactive)
4333 (setq this-command 'org-cycle)
4334 (let ((org-cycle-open-archived-trees t))
4335 (call-interactively 'org-cycle)))
4337 (defun org-hide-archived-subtrees (beg end)
4338 "Re-hide all archived subtrees after a visibility state change."
4339 (save-excursion
4340 (let* ((re (concat ":" org-archive-tag ":")))
4341 (goto-char beg)
4342 (while (re-search-forward re end t)
4343 (when (org-at-heading-p)
4344 (org-flag-subtree t)
4345 (org-end-of-subtree t))))))
4347 (declare-function outline-end-of-heading "outline" ())
4348 (declare-function outline-flag-region "outline" (from to flag))
4349 (defun org-flag-subtree (flag)
4350 (save-excursion
4351 (org-back-to-heading t)
4352 (outline-end-of-heading)
4353 (outline-flag-region (point)
4354 (progn (org-end-of-subtree t) (point))
4355 flag)))
4357 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4359 (eval-and-compile
4360 (org-autoload "org-archive"
4361 '(org-add-archive-files org-archive-subtree
4362 org-archive-to-archive-sibling org-toggle-archive-tag
4363 org-archive-subtree-default
4364 org-archive-subtree-default-with-confirmation)))
4366 ;; Autoload Column View Code
4368 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4369 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4370 (declare-function org-columns-compute "org-colview" (property))
4372 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4373 '(org-columns-number-to-string org-columns-get-format-and-top-level
4374 org-columns-compute org-agenda-columns org-columns-remove-overlays
4375 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4377 ;; Autoload ID code
4379 (declare-function org-id-store-link "org-id")
4380 (declare-function org-id-locations-load "org-id")
4381 (declare-function org-id-locations-save "org-id")
4382 (defvar org-id-track-globally)
4383 (org-autoload "org-id"
4384 '(org-id-get-create org-id-new org-id-copy org-id-get
4385 org-id-get-with-outline-path-completion
4386 org-id-get-with-outline-drilling org-id-store-link
4387 org-id-goto org-id-find org-id-store-link))
4389 ;; Autoload Plotting Code
4391 (org-autoload "org-plot"
4392 '(org-plot/gnuplot))
4394 ;;; Variables for pre-computed regular expressions, all buffer local
4396 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4397 "Matches first line of a hidden block.")
4398 (make-variable-buffer-local 'org-drawer-regexp)
4399 (defvar org-todo-regexp nil
4400 "Matches any of the TODO state keywords.")
4401 (make-variable-buffer-local 'org-todo-regexp)
4402 (defvar org-not-done-regexp nil
4403 "Matches any of the TODO state keywords except the last one.")
4404 (make-variable-buffer-local 'org-not-done-regexp)
4405 (defvar org-not-done-heading-regexp nil
4406 "Matches a TODO headline that is not done.")
4407 (make-variable-buffer-local 'org-not-done-regexp)
4408 (defvar org-todo-line-regexp nil
4409 "Matches a headline and puts TODO state into group 2 if present.")
4410 (make-variable-buffer-local 'org-todo-line-regexp)
4411 (defvar org-complex-heading-regexp nil
4412 "Matches a headline and puts everything into groups:
4413 group 1: the stars
4414 group 2: The todo keyword, maybe
4415 group 3: Priority cookie
4416 group 4: True headline
4417 group 5: Tags")
4418 (make-variable-buffer-local 'org-complex-heading-regexp)
4419 (defvar org-complex-heading-regexp-format nil
4420 "Printf format to make regexp to match an exact headline.
4421 This regexp will match the headline of any node which has the
4422 exact headline text that is put into the format, but may have any
4423 TODO state, priority and tags.")
4424 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4425 (defvar org-todo-line-tags-regexp nil
4426 "Matches a headline and puts TODO state into group 2 if present.
4427 Also put tags into group 4 if tags are present.")
4428 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4429 (defvar org-ds-keyword-length 12
4430 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4431 (make-variable-buffer-local 'org-ds-keyword-length)
4432 (defvar org-deadline-regexp nil
4433 "Matches the DEADLINE keyword.")
4434 (make-variable-buffer-local 'org-deadline-regexp)
4435 (defvar org-deadline-time-regexp nil
4436 "Matches the DEADLINE keyword together with a time stamp.")
4437 (make-variable-buffer-local 'org-deadline-time-regexp)
4438 (defvar org-deadline-line-regexp nil
4439 "Matches the DEADLINE keyword and the rest of the line.")
4440 (make-variable-buffer-local 'org-deadline-line-regexp)
4441 (defvar org-scheduled-regexp nil
4442 "Matches the SCHEDULED keyword.")
4443 (make-variable-buffer-local 'org-scheduled-regexp)
4444 (defvar org-scheduled-time-regexp nil
4445 "Matches the SCHEDULED keyword together with a time stamp.")
4446 (make-variable-buffer-local 'org-scheduled-time-regexp)
4447 (defvar org-closed-time-regexp nil
4448 "Matches the CLOSED keyword together with a time stamp.")
4449 (make-variable-buffer-local 'org-closed-time-regexp)
4451 (defvar org-keyword-time-regexp nil
4452 "Matches any of the 4 keywords, together with the time stamp.")
4453 (make-variable-buffer-local 'org-keyword-time-regexp)
4454 (defvar org-keyword-time-not-clock-regexp nil
4455 "Matches any of the 3 keywords, together with the time stamp.")
4456 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4457 (defvar org-maybe-keyword-time-regexp nil
4458 "Matches a timestamp, possibly preceded by a keyword.")
4459 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4460 (defvar org-all-time-keywords nil
4461 "List of time keywords.")
4462 (make-variable-buffer-local 'org-all-time-keywords)
4464 (defconst org-plain-time-of-day-regexp
4465 (concat
4466 "\\(\\<[012]?[0-9]"
4467 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4468 "\\(--?"
4469 "\\(\\<[012]?[0-9]"
4470 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4471 "\\)?")
4472 "Regular expression to match a plain time or time range.
4473 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4474 groups carry important information:
4475 0 the full match
4476 1 the first time, range or not
4477 8 the second time, if it is a range.")
4479 (defconst org-plain-time-extension-regexp
4480 (concat
4481 "\\(\\<[012]?[0-9]"
4482 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4483 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4484 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4485 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4486 groups carry important information:
4487 0 the full match
4488 7 hours of duration
4489 9 minutes of duration")
4491 (defconst org-stamp-time-of-day-regexp
4492 (concat
4493 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4494 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4495 "\\(--?"
4496 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4497 "Regular expression to match a timestamp time or time range.
4498 After a match, the following groups carry important information:
4499 0 the full match
4500 1 date plus weekday, for back referencing to make sure both times are on the same day
4501 2 the first time, range or not
4502 4 the second time, if it is a range.")
4504 (defconst org-startup-options
4505 '(("fold" org-startup-folded t)
4506 ("overview" org-startup-folded t)
4507 ("nofold" org-startup-folded nil)
4508 ("showall" org-startup-folded nil)
4509 ("showeverything" org-startup-folded showeverything)
4510 ("content" org-startup-folded content)
4511 ("indent" org-startup-indented t)
4512 ("noindent" org-startup-indented nil)
4513 ("hidestars" org-hide-leading-stars t)
4514 ("showstars" org-hide-leading-stars nil)
4515 ("odd" org-odd-levels-only t)
4516 ("oddeven" org-odd-levels-only nil)
4517 ("align" org-startup-align-all-tables t)
4518 ("noalign" org-startup-align-all-tables nil)
4519 ("inlineimages" org-startup-with-inline-images t)
4520 ("noinlineimages" org-startup-with-inline-images nil)
4521 ("customtime" org-display-custom-times t)
4522 ("logdone" org-log-done time)
4523 ("lognotedone" org-log-done note)
4524 ("nologdone" org-log-done nil)
4525 ("lognoteclock-out" org-log-note-clock-out t)
4526 ("nolognoteclock-out" org-log-note-clock-out nil)
4527 ("logrepeat" org-log-repeat state)
4528 ("lognoterepeat" org-log-repeat note)
4529 ("nologrepeat" org-log-repeat nil)
4530 ("logreschedule" org-log-reschedule time)
4531 ("lognotereschedule" org-log-reschedule note)
4532 ("nologreschedule" org-log-reschedule nil)
4533 ("logredeadline" org-log-redeadline time)
4534 ("lognoteredeadline" org-log-redeadline note)
4535 ("nologredeadline" org-log-redeadline nil)
4536 ("logrefile" org-log-refile time)
4537 ("lognoterefile" org-log-refile note)
4538 ("nologrefile" org-log-refile nil)
4539 ("fninline" org-footnote-define-inline t)
4540 ("nofninline" org-footnote-define-inline nil)
4541 ("fnlocal" org-footnote-section nil)
4542 ("fnauto" org-footnote-auto-label t)
4543 ("fnprompt" org-footnote-auto-label nil)
4544 ("fnconfirm" org-footnote-auto-label confirm)
4545 ("fnplain" org-footnote-auto-label plain)
4546 ("fnadjust" org-footnote-auto-adjust t)
4547 ("nofnadjust" org-footnote-auto-adjust nil)
4548 ("constcgs" constants-unit-system cgs)
4549 ("constSI" constants-unit-system SI)
4550 ("noptag" org-tag-persistent-alist nil)
4551 ("hideblocks" org-hide-block-startup t)
4552 ("nohideblocks" org-hide-block-startup nil)
4553 ("beamer" org-startup-with-beamer-mode t)
4554 ("entitiespretty" org-pretty-entities t)
4555 ("entitiesplain" org-pretty-entities nil))
4556 "Variable associated with STARTUP options for org-mode.
4557 Each element is a list of three items: the startup options (as written
4558 in the #+STARTUP line), the corresponding variable, and the value to set
4559 this variable to if the option is found. An optional forth element PUSH
4560 means to push this value onto the list in the variable.")
4562 (defun org-update-property-plist (key val props)
4563 "Update PROPS with KEY and VAL."
4564 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4565 (key (if appending (substring key 0 (- (length key) 1)) key))
4566 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4567 (previous (cdr (assoc key props))))
4568 (if appending
4569 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4570 (cons (cons key val) remainder))))
4572 (defconst org-block-regexp
4573 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4574 "Regular expression for hiding blocks.")
4575 (defconst org-heading-keyword-regexp-format
4576 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4577 "Printf format for a regexp matching an headline with some keyword.
4578 This regexp will match the headline of any node which has the
4579 exact keyword that is put into the format. The keyword isn't in
4580 any group by default, but the stars and the body are.")
4581 (defconst org-heading-keyword-maybe-regexp-format
4582 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4583 "Printf format for a regexp matching an headline, possibly with some keyword.
4584 This regexp can match any headline with the specified keyword, or
4585 without a keyword. The keyword isn't in any group by default,
4586 but the stars and the body are.")
4588 (defun org-set-regexps-and-options ()
4589 "Precompute regular expressions for current buffer."
4590 (when (derived-mode-p 'org-mode)
4591 (org-set-local 'org-todo-kwd-alist nil)
4592 (org-set-local 'org-todo-key-alist nil)
4593 (org-set-local 'org-todo-key-trigger nil)
4594 (org-set-local 'org-todo-keywords-1 nil)
4595 (org-set-local 'org-done-keywords nil)
4596 (org-set-local 'org-todo-heads nil)
4597 (org-set-local 'org-todo-sets nil)
4598 (org-set-local 'org-todo-log-states nil)
4599 (org-set-local 'org-file-properties nil)
4600 (org-set-local 'org-file-tags nil)
4601 (let ((re (org-make-options-regexp
4602 '("CATEGORY" "TODO" "COLUMNS"
4603 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4604 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4605 "OPTIONS")
4606 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4607 (splitre "[ \t]+")
4608 (scripts org-use-sub-superscripts)
4609 kwds kws0 kwsa key log value cat arch tags const links hw dws
4610 tail sep kws1 prio props ftags drawers beamer-p
4611 ext-setup-or-nil setup-contents (start 0))
4612 (save-excursion
4613 (save-restriction
4614 (widen)
4615 (goto-char (point-min))
4616 (while (or (and ext-setup-or-nil
4617 (string-match re ext-setup-or-nil start)
4618 (setq start (match-end 0)))
4619 (and (setq ext-setup-or-nil nil start 0)
4620 (re-search-forward re nil t)))
4621 (setq key (upcase (match-string 1 ext-setup-or-nil))
4622 value (org-match-string-no-properties 2 ext-setup-or-nil))
4623 (if (stringp value) (setq value (org-trim value)))
4624 (cond
4625 ((equal key "CATEGORY")
4626 (setq cat value))
4627 ((member key '("SEQ_TODO" "TODO"))
4628 (push (cons 'sequence (org-split-string value splitre)) kwds))
4629 ((equal key "TYP_TODO")
4630 (push (cons 'type (org-split-string value splitre)) kwds))
4631 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4632 ;; general TODO-like setup
4633 (push (cons (intern (downcase (match-string 1 key)))
4634 (org-split-string value splitre)) kwds))
4635 ((equal key "TAGS")
4636 (setq tags (append tags (if tags '("\\n") nil)
4637 (org-split-string value splitre))))
4638 ((equal key "COLUMNS")
4639 (org-set-local 'org-columns-default-format value))
4640 ((equal key "LINK")
4641 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4642 (push (cons (match-string 1 value)
4643 (org-trim (match-string 2 value)))
4644 links)))
4645 ((equal key "PRIORITIES")
4646 (setq prio (org-split-string value " +")))
4647 ((equal key "PROPERTY")
4648 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4649 (setq props (org-update-property-plist (match-string 1 value)
4650 (match-string 2 value)
4651 props))))
4652 ((equal key "FILETAGS")
4653 (when (string-match "\\S-" value)
4654 (setq ftags
4655 (append
4656 ftags
4657 (apply 'append
4658 (mapcar (lambda (x) (org-split-string x ":"))
4659 (org-split-string value)))))))
4660 ((equal key "DRAWERS")
4661 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4662 ((equal key "CONSTANTS")
4663 (setq const (append const (org-split-string value splitre))))
4664 ((equal key "STARTUP")
4665 (let ((opts (org-split-string value splitre))
4666 l var val)
4667 (while (setq l (pop opts))
4668 (when (setq l (assoc l org-startup-options))
4669 (setq var (nth 1 l) val (nth 2 l))
4670 (if (not (nth 3 l))
4671 (set (make-local-variable var) val)
4672 (if (not (listp (symbol-value var)))
4673 (set (make-local-variable var) nil))
4674 (set (make-local-variable var) (symbol-value var))
4675 (add-to-list var val))))))
4676 ((equal key "ARCHIVE")
4677 (setq arch value)
4678 (remove-text-properties 0 (length arch)
4679 '(face t fontified t) arch))
4680 ((equal key "LATEX_CLASS")
4681 (setq beamer-p (equal value "beamer")))
4682 ((equal key "OPTIONS")
4683 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4684 (setq scripts (read (match-string 2 value)))))
4685 ((equal key "SETUPFILE")
4686 (setq setup-contents (org-file-contents
4687 (expand-file-name
4688 (org-remove-double-quotes value))
4689 'noerror))
4690 (if (not ext-setup-or-nil)
4691 (setq ext-setup-or-nil setup-contents start 0)
4692 (setq ext-setup-or-nil
4693 (concat (substring ext-setup-or-nil 0 start)
4694 "\n" setup-contents "\n"
4695 (substring ext-setup-or-nil start)))))))
4696 ;; search for property blocks
4697 (goto-char (point-min))
4698 (while (re-search-forward org-block-regexp nil t)
4699 (when (equal "PROPERTY" (upcase (match-string 1)))
4700 (setq value (replace-regexp-in-string
4701 "[\n\r]" " " (match-string 4)))
4702 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4703 (setq props (org-update-property-plist (match-string 1 value)
4704 (match-string 2 value)
4705 props)))))))
4706 (org-set-local 'org-use-sub-superscripts scripts)
4707 (when cat
4708 (org-set-local 'org-category (intern cat))
4709 (push (cons "CATEGORY" cat) props))
4710 (when prio
4711 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4712 (setq prio (mapcar 'string-to-char prio))
4713 (org-set-local 'org-highest-priority (nth 0 prio))
4714 (org-set-local 'org-lowest-priority (nth 1 prio))
4715 (org-set-local 'org-default-priority (nth 2 prio)))
4716 (and props (org-set-local 'org-file-properties (nreverse props)))
4717 (and ftags (org-set-local 'org-file-tags
4718 (mapcar 'org-add-prop-inherited ftags)))
4719 (and drawers (org-set-local 'org-drawers drawers))
4720 (and arch (org-set-local 'org-archive-location arch))
4721 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4722 ;; Process the TODO keywords
4723 (unless kwds
4724 ;; Use the global values as if they had been given locally.
4725 (setq kwds (default-value 'org-todo-keywords))
4726 (if (stringp (car kwds))
4727 (setq kwds (list (cons org-todo-interpretation
4728 (default-value 'org-todo-keywords)))))
4729 (setq kwds (reverse kwds)))
4730 (setq kwds (nreverse kwds))
4731 (let (inter kws kw)
4732 (while (setq kws (pop kwds))
4733 (let ((kws (or
4734 (run-hook-with-args-until-success
4735 'org-todo-setup-filter-hook kws)
4736 kws)))
4737 (setq inter (pop kws) sep (member "|" kws)
4738 kws0 (delete "|" (copy-sequence kws))
4739 kwsa nil
4740 kws1 (mapcar
4741 (lambda (x)
4742 ;; 1 2
4743 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4744 (progn
4745 (setq kw (match-string 1 x)
4746 key (and (match-end 2) (match-string 2 x))
4747 log (org-extract-log-state-settings x))
4748 (push (cons kw (and key (string-to-char key))) kwsa)
4749 (and log (push log org-todo-log-states))
4751 (error "Invalid TODO keyword %s" x)))
4752 kws0)
4753 kwsa (if kwsa (append '((:startgroup))
4754 (nreverse kwsa)
4755 '((:endgroup))))
4756 hw (car kws1)
4757 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4758 tail (list inter hw (car dws) (org-last dws))))
4759 (add-to-list 'org-todo-heads hw 'append)
4760 (push kws1 org-todo-sets)
4761 (setq org-done-keywords (append org-done-keywords dws nil))
4762 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4763 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4764 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4765 (setq org-todo-sets (nreverse org-todo-sets)
4766 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4767 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4768 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4769 ;; Process the constants
4770 (when const
4771 (let (e cst)
4772 (while (setq e (pop const))
4773 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4774 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4775 (setq org-table-formula-constants-local cst)))
4777 ;; Process the tags.
4778 (when tags
4779 (let (e tgs)
4780 (while (setq e (pop tags))
4781 (cond
4782 ((equal e "{") (push '(:startgroup) tgs))
4783 ((equal e "}") (push '(:endgroup) tgs))
4784 ((equal e "\\n") (push '(:newline) tgs))
4785 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4786 (push (cons (match-string 1 e)
4787 (string-to-char (match-string 2 e)))
4788 tgs))
4789 (t (push (list e) tgs))))
4790 (org-set-local 'org-tag-alist nil)
4791 (while (setq e (pop tgs))
4792 (or (and (stringp (car e))
4793 (assoc (car e) org-tag-alist))
4794 (push e org-tag-alist)))))
4796 ;; Compute the regular expressions and other local variables.
4797 ;; Using `org-outline-regexp-bol' would complicate them much,
4798 ;; because of the fixed white space at the end of that string.
4799 (if (not org-done-keywords)
4800 (setq org-done-keywords (and org-todo-keywords-1
4801 (list (org-last org-todo-keywords-1)))))
4802 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4803 (length org-scheduled-string)
4804 (length org-clock-string)
4805 (length org-closed-string)))
4806 org-drawer-regexp
4807 (concat "^[ \t]*:\\("
4808 (mapconcat 'regexp-quote org-drawers "\\|")
4809 "\\):[ \t]*$")
4810 org-not-done-keywords
4811 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4812 org-todo-regexp
4813 (concat "\\("
4814 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4815 "\\)")
4816 org-not-done-regexp
4817 (concat "\\("
4818 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4819 "\\)")
4820 org-not-done-heading-regexp
4821 (format org-heading-keyword-regexp-format org-not-done-regexp)
4822 org-todo-line-regexp
4823 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4824 org-complex-heading-regexp
4825 (concat "^\\(\\*+\\)"
4826 "\\(?: +" org-todo-regexp "\\)?"
4827 "\\(?: +\\(\\[#.\\]\\)\\)?"
4828 "\\(?: +\\(.*?\\)\\)??"
4829 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4830 "[ \t]*$")
4831 org-complex-heading-regexp-format
4832 (concat "^\\(\\*+\\)"
4833 "\\(?: +" org-todo-regexp "\\)?"
4834 "\\(?: +\\(\\[#.\\]\\)\\)?"
4835 "\\(?: +"
4836 ;; Stats cookies can be stuck to body.
4837 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4838 "\\(%s\\)"
4839 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4840 "\\)"
4841 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4842 "[ \t]*$")
4843 org-todo-line-tags-regexp
4844 (concat "^\\(\\*+\\)"
4845 "\\(?: +" org-todo-regexp "\\)?"
4846 "\\(?: +\\(.*?\\)\\)??"
4847 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4848 "[ \t]*$")
4849 org-deadline-regexp (concat "\\<" org-deadline-string)
4850 org-deadline-time-regexp
4851 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4852 org-deadline-line-regexp
4853 (concat "\\<\\(" org-deadline-string "\\).*")
4854 org-scheduled-regexp
4855 (concat "\\<" org-scheduled-string)
4856 org-scheduled-time-regexp
4857 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4858 org-closed-time-regexp
4859 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4860 org-keyword-time-regexp
4861 (concat "\\<\\(" org-scheduled-string
4862 "\\|" org-deadline-string
4863 "\\|" org-closed-string
4864 "\\|" org-clock-string "\\)"
4865 " *[[<]\\([^]>]+\\)[]>]")
4866 org-keyword-time-not-clock-regexp
4867 (concat "\\<\\(" org-scheduled-string
4868 "\\|" org-deadline-string
4869 "\\|" org-closed-string
4870 "\\)"
4871 " *[[<]\\([^]>]+\\)[]>]")
4872 org-maybe-keyword-time-regexp
4873 (concat "\\(\\<\\(" org-scheduled-string
4874 "\\|" org-deadline-string
4875 "\\|" org-closed-string
4876 "\\|" org-clock-string "\\)\\)?"
4877 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4878 org-all-time-keywords
4879 (mapcar (lambda (w) (substring w 0 -1))
4880 (list org-scheduled-string org-deadline-string
4881 org-clock-string org-closed-string))
4883 (org-compute-latex-and-specials-regexp)
4884 (org-set-font-lock-defaults))))
4886 (defun org-file-contents (file &optional noerror)
4887 "Return the contents of FILE, as a string."
4888 (if (or (not file)
4889 (not (file-readable-p file)))
4890 (if noerror
4891 (progn
4892 (message "Cannot read file \"%s\"" file)
4893 (ding) (sit-for 2)
4895 (error "Cannot read file \"%s\"" file))
4896 (with-temp-buffer
4897 (insert-file-contents file)
4898 (buffer-string))))
4900 (defun org-extract-log-state-settings (x)
4901 "Extract the log state setting from a TODO keyword string.
4902 This will extract info from a string like \"WAIT(w@/!)\"."
4903 (let (kw key log1 log2)
4904 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4905 (setq kw (match-string 1 x)
4906 key (and (match-end 2) (match-string 2 x))
4907 log1 (and (match-end 3) (match-string 3 x))
4908 log2 (and (match-end 4) (match-string 4 x)))
4909 (and (or log1 log2)
4910 (list kw
4911 (and log1 (if (equal log1 "!") 'time 'note))
4912 (and log2 (if (equal log2 "!") 'time 'note)))))))
4914 (defun org-remove-keyword-keys (list)
4915 "Remove a pair of parenthesis at the end of each string in LIST."
4916 (mapcar (lambda (x)
4917 (if (string-match "(.*)$" x)
4918 (substring x 0 (match-beginning 0))
4920 list))
4922 (defun org-assign-fast-keys (alist)
4923 "Assign fast keys to a keyword-key alist.
4924 Respect keys that are already there."
4925 (let (new e (alt ?0))
4926 (while (setq e (pop alist))
4927 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4928 (cdr e)) ;; Key already assigned.
4929 (push e new)
4930 (let ((clist (string-to-list (downcase (car e))))
4931 (used (append new alist)))
4932 (when (= (car clist) ?@)
4933 (pop clist))
4934 (while (and clist (rassoc (car clist) used))
4935 (pop clist))
4936 (unless clist
4937 (while (rassoc alt used)
4938 (incf alt)))
4939 (push (cons (car e) (or (car clist) alt)) new))))
4940 (nreverse new)))
4942 ;;; Some variables used in various places
4944 (defvar org-window-configuration nil
4945 "Used in various places to store a window configuration.")
4946 (defvar org-selected-window nil
4947 "Used in various places to store a window configuration.")
4948 (defvar org-finish-function nil
4949 "Function to be called when `C-c C-c' is used.
4950 This is for getting out of special buffers like remember.")
4953 ;; FIXME: Occasionally check by commenting these, to make sure
4954 ;; no other functions uses these, forgetting to let-bind them.
4955 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4956 (defvar org-last-state)
4957 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4959 ;; Defined somewhere in this file, but used before definition.
4960 (defvar org-entities) ;; defined in org-entities.el
4961 (defvar org-struct-menu)
4962 (defvar org-org-menu)
4963 (defvar org-tbl-menu)
4965 ;;;; Define the Org-mode
4967 ;; We use a before-change function to check if a table might need
4968 ;; an update.
4969 (defvar org-table-may-need-update t
4970 "Indicates that a table might need an update.
4971 This variable is set by `org-before-change-function'.
4972 `org-table-align' sets it back to nil.")
4973 (defun org-before-change-function (beg end)
4974 "Every change indicates that a table might need an update."
4975 (setq org-table-may-need-update t))
4976 (defvar org-mode-map)
4977 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4978 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4979 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4980 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4981 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4982 (defvar org-table-buffer-is-an nil)
4984 (defvar bidi-paragraph-direction)
4985 (defvar buffer-face-mode-face)
4987 (require 'outline)
4988 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4989 (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"))
4990 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4992 ;; Other stuff we need.
4993 (require 'time-date)
4994 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4995 (require 'easymenu)
4996 (require 'overlay)
4998 (require 'org-macs)
4999 (require 'org-entities)
5000 ;; (require 'org-compat) moved higher up in the file before it is first used
5001 (require 'org-faces)
5002 (require 'org-list)
5003 (require 'org-pcomplete)
5004 (require 'org-src)
5005 (require 'org-footnote)
5007 ;; babel
5008 (require 'ob)
5009 (require 'ob-table)
5010 (require 'ob-lob)
5011 (require 'ob-ref)
5012 (require 'ob-tangle)
5013 (require 'ob-comint)
5014 (require 'ob-keys)
5016 ;;;###autoload
5017 (define-derived-mode org-mode outline-mode "Org"
5018 "Outline-based notes management and organizer, alias
5019 \"Carsten's outline-mode for keeping track of everything.\"
5021 Org-mode develops organizational tasks around a NOTES file which
5022 contains information about projects as plain text. Org-mode is
5023 implemented on top of outline-mode, which is ideal to keep the content
5024 of large files well structured. It supports ToDo items, deadlines and
5025 time stamps, which magically appear in the diary listing of the Emacs
5026 calendar. Tables are easily created with a built-in table editor.
5027 Plain text URL-like links connect to websites, emails (VM), Usenet
5028 messages (Gnus), BBDB entries, and any files related to the project.
5029 For printing and sharing of notes, an Org-mode file (or a part of it)
5030 can be exported as a structured ASCII or HTML file.
5032 The following commands are available:
5034 \\{org-mode-map}"
5036 ;; Get rid of Outline menus, they are not needed
5037 ;; Need to do this here because define-derived-mode sets up
5038 ;; the keymap so late. Still, it is a waste to call this each time
5039 ;; we switch another buffer into org-mode.
5040 (if (featurep 'xemacs)
5041 (when (boundp 'outline-mode-menu-heading)
5042 ;; Assume this is Greg's port, it uses easymenu
5043 (easy-menu-remove outline-mode-menu-heading)
5044 (easy-menu-remove outline-mode-menu-show)
5045 (easy-menu-remove outline-mode-menu-hide))
5046 (define-key org-mode-map [menu-bar headings] 'undefined)
5047 (define-key org-mode-map [menu-bar hide] 'undefined)
5048 (define-key org-mode-map [menu-bar show] 'undefined))
5050 (org-load-modules-maybe)
5051 (easy-menu-add org-org-menu)
5052 (easy-menu-add org-tbl-menu)
5053 (org-install-agenda-files-menu)
5054 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5055 (add-to-invisibility-spec '(org-cwidth))
5056 (add-to-invisibility-spec '(org-hide-block . t))
5057 (when (featurep 'xemacs)
5058 (org-set-local 'line-move-ignore-invisible t))
5059 (org-set-local 'outline-regexp org-outline-regexp)
5060 (org-set-local 'outline-level 'org-outline-level)
5061 (setq bidi-paragraph-direction 'left-to-right)
5062 (when (and org-ellipsis
5063 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5064 (fboundp 'make-glyph-code))
5065 (unless org-display-table
5066 (setq org-display-table (make-display-table)))
5067 (set-display-table-slot
5068 org-display-table 4
5069 (vconcat (mapcar
5070 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5071 org-ellipsis)))
5072 (if (stringp org-ellipsis) org-ellipsis "..."))))
5073 (setq buffer-display-table org-display-table))
5074 (org-set-regexps-and-options)
5075 (when (and org-tag-faces (not org-tags-special-faces-re))
5076 ;; tag faces set outside customize.... force initialization.
5077 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5078 ;; Calc embedded
5079 (org-set-local 'calc-embedded-open-mode "# ")
5080 (modify-syntax-entry ?@ "w")
5081 (if org-startup-truncated (setq truncate-lines t))
5082 (org-set-local 'font-lock-unfontify-region-function
5083 'org-unfontify-region)
5084 ;; Activate before-change-function
5085 (org-set-local 'org-table-may-need-update t)
5086 (org-add-hook 'before-change-functions 'org-before-change-function nil
5087 'local)
5088 ;; Check for running clock before killing a buffer
5089 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5090 ;; Indentation.
5091 (org-set-local 'indent-line-function 'org-indent-line)
5092 (org-set-local 'indent-region-function 'org-indent-region)
5093 ;; Initialize radio targets.
5094 (org-update-radio-target-regexp)
5095 ;; Filling and auto-filling.
5096 (org-setup-filling)
5097 ;; Comments.
5098 (org-setup-comments-handling)
5099 ;; Beginning/end of defun
5100 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5101 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5102 ;; Next error for sparse trees
5103 (org-set-local 'next-error-function 'org-occur-next-match)
5104 ;; Make sure dependence stuff works reliably, even for users who set it
5105 ;; too late :-(
5106 (if org-enforce-todo-dependencies
5107 (add-hook 'org-blocker-hook
5108 'org-block-todo-from-children-or-siblings-or-parent)
5109 (remove-hook 'org-blocker-hook
5110 'org-block-todo-from-children-or-siblings-or-parent))
5111 (if org-enforce-todo-checkbox-dependencies
5112 (add-hook 'org-blocker-hook
5113 'org-block-todo-from-checkboxes)
5114 (remove-hook 'org-blocker-hook
5115 'org-block-todo-from-checkboxes))
5117 ;; Align options lines
5118 (org-set-local
5119 'align-mode-rules-list
5120 '((org-in-buffer-settings
5121 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5122 (modes . '(org-mode)))))
5124 ;; Imenu
5125 (org-set-local 'imenu-create-index-function
5126 'org-imenu-get-tree)
5128 ;; Make isearch reveal context
5129 (if (or (featurep 'xemacs)
5130 (not (boundp 'outline-isearch-open-invisible-function)))
5131 ;; Emacs 21 and XEmacs make use of the hook
5132 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5133 ;; Emacs 22 deals with this through a special variable
5134 (org-set-local 'outline-isearch-open-invisible-function
5135 (lambda (&rest ignore) (org-show-context 'isearch))))
5137 ;; Turn on org-beamer-mode?
5138 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5140 ;; Setup the pcomplete hooks
5141 (set (make-local-variable 'pcomplete-command-completion-function)
5142 'org-pcomplete-initial)
5143 (set (make-local-variable 'pcomplete-command-name-function)
5144 'org-command-at-point)
5145 (set (make-local-variable 'pcomplete-default-completion-function)
5146 'ignore)
5147 (set (make-local-variable 'pcomplete-parse-arguments-function)
5148 'org-parse-arguments)
5149 (set (make-local-variable 'pcomplete-termination-string) "")
5150 (when (>= emacs-major-version 23)
5151 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5153 ;; If empty file that did not turn on org-mode automatically, make it to.
5154 (if (and org-insert-mode-line-in-empty-file
5155 (org-called-interactively-p 'any)
5156 (= (point-min) (point-max)))
5157 (insert "# -*- mode: org -*-\n\n"))
5158 (unless org-inhibit-startup
5159 (when org-startup-align-all-tables
5160 (let ((bmp (buffer-modified-p)))
5161 (org-table-map-tables 'org-table-align 'quietly)
5162 (set-buffer-modified-p bmp)))
5163 (when org-startup-with-inline-images
5164 (org-display-inline-images))
5165 (when org-startup-indented
5166 (require 'org-indent)
5167 (org-indent-mode 1))
5168 (unless org-inhibit-startup-visibility-stuff
5169 (org-set-startup-visibility)))
5170 ;; Try to set org-hide correctly
5171 (set-face-foreground
5172 'org-hide
5173 (or (face-background 'default)
5174 (face-background 'org-default)
5175 (cdr (assoc 'background-color default-frame-alist))
5176 (cdr (assoc 'background-color initial-frame-alist))
5177 (cdr (assoc 'background-color window-system-default-frame-alist))
5178 (face-foreground 'org-hide))))
5180 (when (fboundp 'abbrev-table-put)
5181 (abbrev-table-put org-mode-abbrev-table
5182 :parents (list text-mode-abbrev-table)))
5184 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5186 (defun org-current-time ()
5187 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5188 (if (> (car org-time-stamp-rounding-minutes) 1)
5189 (let ((r (car org-time-stamp-rounding-minutes))
5190 (time (decode-time)))
5191 (apply 'encode-time
5192 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5193 (nthcdr 2 time))))
5194 (current-time)))
5196 (defun org-today ()
5197 "Return today date, considering `org-extend-today-until'."
5198 (time-to-days
5199 (time-subtract (current-time)
5200 (list 0 (* 3600 org-extend-today-until) 0))))
5202 ;;;; Font-Lock stuff, including the activators
5204 (defvar org-mouse-map (make-sparse-keymap))
5205 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5206 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5207 (when org-mouse-1-follows-link
5208 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5209 (when org-tab-follows-link
5210 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5211 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5213 (require 'font-lock)
5215 (defconst org-non-link-chars "]\t\n\r<>")
5216 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5217 "shell" "elisp" "doi" "message"))
5218 (defvar org-link-types-re nil
5219 "Matches a link that has a url-like prefix like \"http:\"")
5220 (defvar org-link-re-with-space nil
5221 "Matches a link with spaces, optional angular brackets around it.")
5222 (defvar org-link-re-with-space2 nil
5223 "Matches a link with spaces, optional angular brackets around it.")
5224 (defvar org-link-re-with-space3 nil
5225 "Matches a link with spaces, only for internal part in bracket links.")
5226 (defvar org-angle-link-re nil
5227 "Matches link with angular brackets, spaces are allowed.")
5228 (defvar org-plain-link-re nil
5229 "Matches plain link, without spaces.")
5230 (defvar org-bracket-link-regexp nil
5231 "Matches a link in double brackets.")
5232 (defvar org-bracket-link-analytic-regexp nil
5233 "Regular expression used to analyze links.
5234 Here is what the match groups contain after a match:
5235 1: http:
5236 2: http
5237 3: path
5238 4: [desc]
5239 5: desc")
5240 (defvar org-bracket-link-analytic-regexp++ nil
5241 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5242 (defvar org-any-link-re nil
5243 "Regular expression matching any link.")
5245 (defcustom org-match-sexp-depth 3
5246 "Number of stacked braces for sub/superscript matching.
5247 This has to be set before loading org.el to be effective."
5248 :group 'org-export-translation ; ??????????????????????????/
5249 :type 'integer)
5251 (defun org-create-multibrace-regexp (left right n)
5252 "Create a regular expression which will match a balanced sexp.
5253 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5254 as single character strings.
5255 The regexp returned will match the entire expression including the
5256 delimiters. It will also define a single group which contains the
5257 match except for the outermost delimiters. The maximum depth of
5258 stacked delimiters is N. Escaping delimiters is not possible."
5259 (let* ((nothing (concat "[^" left right "]*?"))
5260 (or "\\|")
5261 (re nothing)
5262 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5263 (while (> n 1)
5264 (setq n (1- n)
5265 re (concat re or next)
5266 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5267 (concat left "\\(" re "\\)" right)))
5269 (defvar org-match-substring-regexp
5270 (concat
5271 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5272 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5273 "\\|"
5274 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5275 "\\|"
5276 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5277 "The regular expression matching a sub- or superscript.")
5279 (defvar org-match-substring-with-braces-regexp
5280 (concat
5281 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5282 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5283 "\\)")
5284 "The regular expression matching a sub- or superscript, forcing braces.")
5286 (defun org-make-link-regexps ()
5287 "Update the link regular expressions.
5288 This should be called after the variable `org-link-types' has changed."
5289 (setq org-link-types-re
5290 (concat
5291 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5292 org-link-re-with-space
5293 (concat
5294 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5295 "\\([^" org-non-link-chars " ]"
5296 "[^" org-non-link-chars "]*"
5297 "[^" org-non-link-chars " ]\\)>?")
5298 org-link-re-with-space2
5299 (concat
5300 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5301 "\\([^" org-non-link-chars " ]"
5302 "[^\t\n\r]*"
5303 "[^" org-non-link-chars " ]\\)>?")
5304 org-link-re-with-space3
5305 (concat
5306 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5307 "\\([^" org-non-link-chars " ]"
5308 "[^\t\n\r]*\\)")
5309 org-angle-link-re
5310 (concat
5311 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5312 "\\([^" org-non-link-chars " ]"
5313 "[^" org-non-link-chars "]*"
5314 "\\)>")
5315 org-plain-link-re
5316 (concat
5317 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5318 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5319 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5320 org-bracket-link-regexp
5321 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5322 org-bracket-link-analytic-regexp
5323 (concat
5324 "\\[\\["
5325 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5326 "\\([^]]+\\)"
5327 "\\]"
5328 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5329 "\\]")
5330 org-bracket-link-analytic-regexp++
5331 (concat
5332 "\\[\\["
5333 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5334 "\\([^]]+\\)"
5335 "\\]"
5336 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5337 "\\]")
5338 org-any-link-re
5339 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5340 org-angle-link-re "\\)\\|\\("
5341 org-plain-link-re "\\)")))
5343 (org-make-link-regexps)
5345 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5346 "Regular expression for fast time stamp matching.")
5347 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5348 "Regular expression for fast time stamp matching.")
5349 (defconst org-ts-regexp0
5350 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5351 "Regular expression matching time strings for analysis.
5352 This one does not require the space after the date, so it can be used
5353 on a string that terminates immediately after the date.")
5354 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5355 "Regular expression matching time strings for analysis.")
5356 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5357 "Regular expression matching time stamps, with groups.")
5358 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5359 "Regular expression matching time stamps (also [..]), with groups.")
5360 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5361 "Regular expression matching a time stamp range.")
5362 (defconst org-tr-regexp-both
5363 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5364 "Regular expression matching a time stamp range.")
5365 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5366 org-ts-regexp "\\)?")
5367 "Regular expression matching a time stamp or time stamp range.")
5368 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5369 org-ts-regexp-both "\\)?")
5370 "Regular expression matching a time stamp or time stamp range.
5371 The time stamps may be either active or inactive.")
5373 (defvar org-emph-face nil)
5375 (defun org-do-emphasis-faces (limit)
5376 "Run through the buffer and add overlays to emphasized strings."
5377 (let (rtn a)
5378 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5379 (if (not (= (char-after (match-beginning 3))
5380 (char-after (match-beginning 4))))
5381 (progn
5382 (setq rtn t)
5383 (setq a (assoc (match-string 3) org-emphasis-alist))
5384 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5385 'face
5386 (nth 1 a))
5387 (and (nth 4 a)
5388 (org-remove-flyspell-overlays-in
5389 (match-beginning 0) (match-end 0)))
5390 (add-text-properties (match-beginning 2) (match-end 2)
5391 '(font-lock-multiline t org-emphasis t))
5392 (when org-hide-emphasis-markers
5393 (add-text-properties (match-end 4) (match-beginning 5)
5394 '(invisible org-link))
5395 (add-text-properties (match-beginning 3) (match-end 3)
5396 '(invisible org-link)))))
5397 (backward-char 1))
5398 rtn))
5400 (defun org-emphasize (&optional char)
5401 "Insert or change an emphasis, i.e. a font like bold or italic.
5402 If there is an active region, change that region to a new emphasis.
5403 If there is no region, just insert the marker characters and position
5404 the cursor between them.
5405 CHAR should be either the marker character, or the first character of the
5406 HTML tag associated with that emphasis. If CHAR is a space, the means
5407 to remove the emphasis of the selected region.
5408 If char is not given (for example in an interactive call) it
5409 will be prompted for."
5410 (interactive)
5411 (let ((eal org-emphasis-alist) e det
5412 (erc org-emphasis-regexp-components)
5413 (prompt "")
5414 (string "") beg end move tag c s)
5415 (if (org-region-active-p)
5416 (setq beg (region-beginning) end (region-end)
5417 string (buffer-substring beg end))
5418 (setq move t))
5420 (while (setq e (pop eal))
5421 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5422 c (aref tag 0))
5423 (push (cons c (string-to-char (car e))) det)
5424 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5425 (substring tag 1)))))
5426 (setq det (nreverse det))
5427 (unless char
5428 (message "%s" (concat "Emphasis marker or tag:" prompt))
5429 (setq char (read-char-exclusive)))
5430 (setq char (or (cdr (assoc char det)) char))
5431 (if (equal char ?\ )
5432 (setq s "" move nil)
5433 (unless (assoc (char-to-string char) org-emphasis-alist)
5434 (error "No such emphasis marker: \"%c\"" char))
5435 (setq s (char-to-string char)))
5436 (while (and (> (length string) 1)
5437 (equal (substring string 0 1) (substring string -1))
5438 (assoc (substring string 0 1) org-emphasis-alist))
5439 (setq string (substring string 1 -1)))
5440 (setq string (concat s string s))
5441 (if beg (delete-region beg end))
5442 (unless (or (bolp)
5443 (string-match (concat "[" (nth 0 erc) "\n]")
5444 (char-to-string (char-before (point)))))
5445 (insert " "))
5446 (unless (or (eobp)
5447 (string-match (concat "[" (nth 1 erc) "\n]")
5448 (char-to-string (char-after (point)))))
5449 (insert " ") (backward-char 1))
5450 (insert string)
5451 (and move (backward-char 1))))
5453 (defconst org-nonsticky-props
5454 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5456 (defsubst org-rear-nonsticky-at (pos)
5457 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5459 (defun org-activate-plain-links (limit)
5460 "Run through the buffer and add overlays to links."
5461 (catch 'exit
5462 (let (f)
5463 (when (re-search-forward (concat org-plain-link-re) limit t)
5464 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5465 (setq f (get-text-property (match-beginning 0) 'face))
5466 (if (or (eq f 'org-tag)
5467 (and (listp f) (memq 'org-tag f)))
5469 (add-text-properties (match-beginning 0) (match-end 0)
5470 (list 'mouse-face 'highlight
5471 'face 'org-link
5472 'keymap org-mouse-map))
5473 (org-rear-nonsticky-at (match-end 0)))
5474 t))))
5476 (defun org-activate-code (limit)
5477 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5478 (progn
5479 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5480 (remove-text-properties (match-beginning 0) (match-end 0)
5481 '(display t invisible t intangible t))
5482 t)))
5484 (defcustom org-src-fontify-natively nil
5485 "When non-nil, fontify code in code blocks."
5486 :type 'boolean
5487 :version "24.1"
5488 :group 'org-appearance
5489 :group 'org-babel)
5491 (defcustom org-allow-promoting-top-level-subtree nil
5492 "When non-nil, allow promoting a top level subtree.
5493 The leading star of the top level headline will be replaced
5494 by a #."
5495 :type 'boolean
5496 :version "24.1"
5497 :group 'org-appearance)
5499 (defun org-fontify-meta-lines-and-blocks (limit)
5500 (condition-case nil
5501 (org-fontify-meta-lines-and-blocks-1 limit)
5502 (error (message "org-mode fontification error"))))
5504 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5505 "Fontify #+ lines and blocks, in the correct ways."
5506 (let ((case-fold-search t))
5507 (if (re-search-forward
5508 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5509 limit t)
5510 (let ((beg (match-beginning 0))
5511 (block-start (match-end 0))
5512 (block-end nil)
5513 (lang (match-string 7))
5514 (beg1 (line-beginning-position 2))
5515 (dc1 (downcase (match-string 2)))
5516 (dc3 (downcase (match-string 3)))
5517 end end1 quoting block-type ovl)
5518 (cond
5519 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5520 ;; a single line of backend-specific content
5521 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5522 (remove-text-properties (match-beginning 0) (match-end 0)
5523 '(display t invisible t intangible t))
5524 (add-text-properties (match-beginning 1) (match-end 3)
5525 '(font-lock-fontified t face org-meta-line))
5526 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5527 '(font-lock-fontified t face org-block))
5528 ; for backend-specific code
5530 ((and (match-end 4) (equal dc3 "+begin"))
5531 ;; Truly a block
5532 (setq block-type (downcase (match-string 5))
5533 quoting (member block-type org-protecting-blocks))
5534 (when (re-search-forward
5535 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5536 nil t) ;; on purpose, we look further than LIMIT
5537 (setq end (min (point-max) (match-end 0))
5538 end1 (min (point-max) (1- (match-beginning 0))))
5539 (setq block-end (match-beginning 0))
5540 (when quoting
5541 (remove-text-properties beg end
5542 '(display t invisible t intangible t)))
5543 (add-text-properties
5544 beg end
5545 '(font-lock-fontified t font-lock-multiline t))
5546 (add-text-properties beg beg1 '(face org-meta-line))
5547 (add-text-properties end1 (min (point-max) (1+ end))
5548 '(face org-meta-line)) ; for end_src
5549 (cond
5550 ((and lang (not (string= lang "")) org-src-fontify-natively)
5551 (org-src-font-lock-fontify-block lang block-start block-end)
5552 ;; remove old background overlays
5553 (mapc (lambda (ov)
5554 (if (eq (overlay-get ov 'face) 'org-block-background)
5555 (delete-overlay ov)))
5556 (overlays-at (/ (+ beg1 block-end) 2)))
5557 ;; add a background overlay
5558 (setq ovl (make-overlay beg1 block-end))
5559 (overlay-put ovl 'face 'org-block-background)
5560 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5561 (quoting
5562 (add-text-properties beg1 (min (point-max) (1+ end1))
5563 '(face org-block))) ; end of source block
5564 ((not org-fontify-quote-and-verse-blocks))
5565 ((string= block-type "quote")
5566 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5567 ((string= block-type "verse")
5568 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5569 (add-text-properties beg beg1 '(face org-block-begin-line))
5570 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5571 '(face org-block-end-line))
5573 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5574 (add-text-properties
5575 beg (match-end 3)
5576 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5577 '(font-lock-fontified t invisible t)
5578 '(font-lock-fontified t face org-document-info-keyword)))
5579 (add-text-properties
5580 (match-beginning 6) (match-end 6)
5581 (if (string-equal dc1 "+title:")
5582 '(font-lock-fontified t face org-document-title)
5583 '(font-lock-fontified t face org-document-info))))
5584 ((or (equal dc1 "+results")
5585 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5586 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5587 "+call:" "+header:" "+headers:" "+name:"))
5588 (and (match-end 4) (equal dc3 "+attr")))
5589 (add-text-properties
5590 beg (match-end 0)
5591 '(font-lock-fontified t face org-meta-line))
5593 ((member dc3 '(" " ""))
5594 (add-text-properties
5595 beg (match-end 0)
5596 '(font-lock-fontified t face font-lock-comment-face)))
5597 ((not (member (char-after beg) '(?\ ?\t)))
5598 ;; just any other in-buffer setting, but not indented
5599 (add-text-properties
5600 beg (match-end 0)
5601 '(font-lock-fontified t face org-meta-line))
5603 (t nil))))))
5605 (defun org-strip-protective-commas (beg end)
5606 "Strip protective commas between BEG and END in the current buffer."
5607 (interactive "r")
5608 (save-excursion
5609 (save-match-data
5610 (goto-char beg)
5611 (let ((front-line (save-excursion
5612 (re-search-forward
5613 "[^[:space:]]" end t)
5614 (goto-char (match-beginning 0))
5615 (current-column))))
5616 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5617 (goto-char (match-beginning 1))
5618 (when (= (current-column) front-line)
5619 (replace-match "" nil nil nil 1)))))))
5621 (defun org-activate-angle-links (limit)
5622 "Run through the buffer and add overlays to links."
5623 (if (re-search-forward org-angle-link-re limit t)
5624 (progn
5625 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5626 (add-text-properties (match-beginning 0) (match-end 0)
5627 (list 'mouse-face 'highlight
5628 'keymap org-mouse-map))
5629 (org-rear-nonsticky-at (match-end 0))
5630 t)))
5632 (defun org-activate-footnote-links (limit)
5633 "Run through the buffer and add overlays to footnotes."
5634 (let ((fn (org-footnote-next-reference-or-definition limit)))
5635 (when fn
5636 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5637 (org-remove-flyspell-overlays-in beg end)
5638 (add-text-properties beg end
5639 (list 'mouse-face 'highlight
5640 'keymap org-mouse-map
5641 'help-echo
5642 (if (= (point-at-bol) beg)
5643 "Footnote definition"
5644 "Footnote reference")
5645 'font-lock-fontified t
5646 'font-lock-multiline t
5647 'face 'org-footnote))))))
5649 (defun org-activate-bracket-links (limit)
5650 "Run through the buffer and add overlays to bracketed links."
5651 (if (re-search-forward org-bracket-link-regexp limit t)
5652 (let* ((help (concat "LINK: "
5653 (org-match-string-no-properties 1)))
5654 ;; FIXME: above we should remove the escapes.
5655 ;; but that requires another match, protecting match data,
5656 ;; a lot of overhead for font-lock.
5657 (ip (org-maybe-intangible
5658 (list 'invisible 'org-link
5659 'keymap org-mouse-map 'mouse-face 'highlight
5660 'font-lock-multiline t 'help-echo help)))
5661 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5662 'font-lock-multiline t 'help-echo help)))
5663 ;; We need to remove the invisible property here. Table narrowing
5664 ;; may have made some of this invisible.
5665 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5666 (remove-text-properties (match-beginning 0) (match-end 0)
5667 '(invisible nil))
5668 (if (match-end 3)
5669 (progn
5670 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5671 (org-rear-nonsticky-at (match-beginning 3))
5672 (add-text-properties (match-beginning 3) (match-end 3) vp)
5673 (org-rear-nonsticky-at (match-end 3))
5674 (add-text-properties (match-end 3) (match-end 0) ip)
5675 (org-rear-nonsticky-at (match-end 0)))
5676 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5677 (org-rear-nonsticky-at (match-beginning 1))
5678 (add-text-properties (match-beginning 1) (match-end 1) vp)
5679 (org-rear-nonsticky-at (match-end 1))
5680 (add-text-properties (match-end 1) (match-end 0) ip)
5681 (org-rear-nonsticky-at (match-end 0)))
5682 t)))
5684 (defun org-activate-dates (limit)
5685 "Run through the buffer and add overlays to dates."
5686 (if (re-search-forward org-tsr-regexp-both limit t)
5687 (progn
5688 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5689 (add-text-properties (match-beginning 0) (match-end 0)
5690 (list 'mouse-face 'highlight
5691 'keymap org-mouse-map))
5692 (org-rear-nonsticky-at (match-end 0))
5693 (when org-display-custom-times
5694 (if (match-end 3)
5695 (org-display-custom-time (match-beginning 3) (match-end 3)))
5696 (org-display-custom-time (match-beginning 1) (match-end 1)))
5697 t)))
5699 (defvar org-target-link-regexp nil
5700 "Regular expression matching radio targets in plain text.")
5701 (make-variable-buffer-local 'org-target-link-regexp)
5702 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5703 "Regular expression matching a link target.")
5704 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5705 "Regular expression matching a radio target.")
5706 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5707 "Regular expression matching any target.")
5709 (defun org-activate-target-links (limit)
5710 "Run through the buffer and add overlays to target matches."
5711 (when org-target-link-regexp
5712 (let ((case-fold-search t))
5713 (if (re-search-forward org-target-link-regexp limit t)
5714 (progn
5715 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5716 (add-text-properties (match-beginning 0) (match-end 0)
5717 (list 'mouse-face 'highlight
5718 'keymap org-mouse-map
5719 'help-echo "Radio target link"
5720 'org-linked-text t))
5721 (org-rear-nonsticky-at (match-end 0))
5722 t)))))
5724 (defun org-update-radio-target-regexp ()
5725 "Find all radio targets in this file and update the regular expression."
5726 (interactive)
5727 (when (memq 'radio org-activate-links)
5728 (setq org-target-link-regexp
5729 (org-make-target-link-regexp (org-all-targets 'radio)))
5730 (org-restart-font-lock)))
5732 (defun org-hide-wide-columns (limit)
5733 (let (s e)
5734 (setq s (text-property-any (point) (or limit (point-max))
5735 'org-cwidth t))
5736 (when s
5737 (setq e (next-single-property-change s 'org-cwidth))
5738 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5739 (goto-char e)
5740 t)))
5742 (defvar org-latex-and-specials-regexp nil
5743 "Regular expression for highlighting export special stuff.")
5744 (defvar org-match-substring-regexp)
5745 (defvar org-match-substring-with-braces-regexp)
5747 ;; This should be with the exporter code, but we also use if for font-locking
5748 (defconst org-export-html-special-string-regexps
5749 '(("\\\\-" . "&shy;")
5750 ("---\\([^-]\\)" . "&mdash;\\1")
5751 ("--\\([^-]\\)" . "&ndash;\\1")
5752 ("\\.\\.\\." . "&hellip;"))
5753 "Regular expressions for special string conversion.")
5756 (defun org-compute-latex-and-specials-regexp ()
5757 "Compute regular expression for stuff treated specially by exporters."
5758 (if (not org-highlight-latex-fragments-and-specials)
5759 (org-set-local 'org-latex-and-specials-regexp nil)
5760 (require 'org-exp)
5761 (let*
5762 ((matchers (plist-get org-format-latex-options :matchers))
5763 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5764 org-latex-regexps)))
5765 (org-export-allow-BIND nil)
5766 (options (org-combine-plists (org-default-export-plist)
5767 (org-infile-export-plist)))
5768 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5769 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5770 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5771 (org-export-html-expand (plist-get options :expand-quoted-html))
5772 (org-export-with-special-strings (plist-get options :special-strings))
5773 (re-sub
5774 (cond
5775 ((equal org-export-with-sub-superscripts '{})
5776 (list org-match-substring-with-braces-regexp))
5777 (org-export-with-sub-superscripts
5778 (list org-match-substring-regexp))))
5779 (re-latex
5780 (if org-export-with-LaTeX-fragments
5781 (mapcar (lambda (x) (nth 1 x)) latexs)))
5782 (re-macros
5783 (if org-export-with-TeX-macros
5784 (list (concat "\\\\"
5785 (regexp-opt
5786 (append
5788 (delq nil
5789 (mapcar 'car-safe
5790 (append org-entities-user
5791 org-entities)))
5792 (if (boundp 'org-latex-entities)
5793 (mapcar (lambda (x)
5794 (or (car-safe x) x))
5795 org-latex-entities)
5796 nil))
5797 'words))) ; FIXME
5799 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5800 (re-special (if org-export-with-special-strings
5801 (mapcar (lambda (x) (car x))
5802 org-export-html-special-string-regexps)))
5803 (re-rest
5804 (delq nil
5805 (list
5806 (if org-export-html-expand "@<[^>\n]+>")
5807 ))))
5808 (org-set-local
5809 'org-latex-and-specials-regexp
5810 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5811 re-rest) "\\|")))))
5813 (defun org-do-latex-and-special-faces (limit)
5814 "Run through the buffer and add overlays to links."
5815 (when org-latex-and-specials-regexp
5816 (let (rtn d)
5817 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5818 limit t))
5819 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5820 'face))
5821 '(org-code org-verbatim underline)))
5822 (progn
5823 (setq rtn t
5824 d (cond ((member (char-after (1+ (match-beginning 0)))
5825 '(?_ ?^)) 1)
5826 (t 0)))
5827 (font-lock-prepend-text-property
5828 (+ d (match-beginning 0)) (match-end 0)
5829 'face 'org-latex-and-export-specials)
5830 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5831 '(font-lock-multiline t)))))
5832 rtn)))
5834 (defun org-restart-font-lock ()
5835 "Restart `font-lock-mode', to force refontification."
5836 (when (and (boundp 'font-lock-mode) font-lock-mode)
5837 (font-lock-mode -1)
5838 (font-lock-mode 1)))
5840 (defun org-all-targets (&optional radio)
5841 "Return a list of all targets in this file.
5842 With optional argument RADIO, only find radio targets."
5843 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5844 rtn)
5845 (save-excursion
5846 (goto-char (point-min))
5847 (while (re-search-forward re nil t)
5848 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5849 rtn)))
5851 (defun org-make-target-link-regexp (targets)
5852 "Make regular expression matching all strings in TARGETS.
5853 The regular expression finds the targets also if there is a line break
5854 between words."
5855 (and targets
5856 (concat
5857 "\\<\\("
5858 (mapconcat
5859 (lambda (x)
5860 (setq x (regexp-quote x))
5861 (while (string-match " +" x)
5862 (setq x (replace-match "\\s-+" t t x)))
5864 targets
5865 "\\|")
5866 "\\)\\>")))
5868 (defun org-activate-tags (limit)
5869 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5870 (progn
5871 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5872 (add-text-properties (match-beginning 1) (match-end 1)
5873 (list 'mouse-face 'highlight
5874 'keymap org-mouse-map))
5875 (org-rear-nonsticky-at (match-end 1))
5876 t)))
5878 (defun org-outline-level ()
5879 "Compute the outline level of the heading at point.
5880 This function assumes that the cursor is at the beginning of a line matched
5881 by `outline-regexp'. Otherwise it returns garbage.
5882 If this is called at a normal headline, the level is the number of stars.
5883 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5884 (save-excursion
5885 (looking-at org-outline-regexp)
5886 (1- (- (match-end 0) (match-beginning 0)))))
5888 (defvar org-font-lock-keywords nil)
5890 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5891 "Regular expression matching a property line.")
5893 (defvar org-font-lock-hook nil
5894 "Functions to be called for special font lock stuff.")
5896 (defvar org-font-lock-set-keywords-hook nil
5897 "Functions that can manipulate `org-font-lock-extra-keywords'.
5898 This is called after `org-font-lock-extra-keywords' is defined, but before
5899 it is installed to be used by font lock. This can be useful if something
5900 needs to be inserted at a specific position in the font-lock sequence.")
5902 (defun org-font-lock-hook (limit)
5903 (run-hook-with-args 'org-font-lock-hook limit))
5905 (defun org-set-font-lock-defaults ()
5906 (let* ((em org-fontify-emphasized-text)
5907 (lk org-activate-links)
5908 (org-font-lock-extra-keywords
5909 (list
5910 ;; Call the hook
5911 '(org-font-lock-hook)
5912 ;; Headlines
5913 `(,(if org-fontify-whole-heading-line
5914 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5915 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5916 (1 (org-get-level-face 1))
5917 (2 (org-get-level-face 2))
5918 (3 (org-get-level-face 3)))
5919 ;; Table lines
5920 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5921 (1 'org-table t))
5922 ;; Table internals
5923 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5924 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5925 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5926 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5927 ;; Drawers
5928 (list org-drawer-regexp '(0 'org-special-keyword t))
5929 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5930 ;; Properties
5931 (list org-property-re
5932 '(1 'org-special-keyword t)
5933 '(3 'org-property-value t))
5934 ;; Links
5935 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5936 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5937 (if (memq 'plain lk) '(org-activate-plain-links))
5938 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5939 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5940 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5941 (if (memq 'footnote lk) '(org-activate-footnote-links))
5942 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5943 '(org-hide-wide-columns (0 nil append))
5944 ;; TODO keyword
5945 (list (format org-heading-keyword-regexp-format
5946 org-todo-regexp)
5947 '(2 (org-get-todo-face 2) t))
5948 ;; DONE
5949 (if org-fontify-done-headline
5950 (list (format org-heading-keyword-regexp-format
5951 (concat
5952 "\\(?:"
5953 (mapconcat 'regexp-quote org-done-keywords "\\|")
5954 "\\)"))
5955 '(2 'org-headline-done t))
5956 nil)
5957 ;; Priorities
5958 '(org-font-lock-add-priority-faces)
5959 ;; Tags
5960 '(org-font-lock-add-tag-faces)
5961 ;; Special keywords
5962 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5963 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5964 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5965 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5966 ;; Emphasis
5967 (if em
5968 (if (featurep 'xemacs)
5969 '(org-do-emphasis-faces (0 nil append))
5970 '(org-do-emphasis-faces)))
5971 ;; Checkboxes
5972 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5973 1 'org-checkbox prepend)
5974 (if (cdr (assq 'checkbox org-list-automatic-rules))
5975 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5976 (0 (org-get-checkbox-statistics-face) t)))
5977 ;; Description list items
5978 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5979 1 'org-list-dt prepend)
5980 ;; ARCHIVEd headings
5981 (list (concat
5982 org-outline-regexp-bol
5983 "\\(.*:" org-archive-tag ":.*\\)")
5984 '(1 'org-archived prepend))
5985 ;; Specials
5986 '(org-do-latex-and-special-faces)
5987 '(org-fontify-entities)
5988 '(org-raise-scripts)
5989 ;; Code
5990 '(org-activate-code (1 'org-code t))
5991 ;; COMMENT
5992 (list (format org-heading-keyword-regexp-format
5993 (concat "\\("
5994 org-comment-string "\\|" org-quote-string
5995 "\\)"))
5996 '(2 'org-special-keyword t))
5997 ;; Blocks and meta lines
5998 '(org-fontify-meta-lines-and-blocks)
6000 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6001 (run-hooks 'org-font-lock-set-keywords-hook)
6002 ;; Now set the full font-lock-keywords
6003 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6004 (org-set-local 'font-lock-defaults
6005 '(org-font-lock-keywords t nil nil backward-paragraph))
6006 (kill-local-variable 'font-lock-keywords) nil))
6008 (defun org-toggle-pretty-entities ()
6009 "Toggle the composition display of entities as UTF8 characters."
6010 (interactive)
6011 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6012 (org-restart-font-lock)
6013 (if org-pretty-entities
6014 (message "Entities are displayed as UTF8 characters")
6015 (save-restriction
6016 (widen)
6017 (org-decompose-region (point-min) (point-max))
6018 (message "Entities are displayed plain"))))
6020 (defvar org-custom-properties-overlays nil
6021 "List of overlays used for custom properties.")
6022 (make-variable-buffer-local 'org-custom-properties-overlays)
6024 (defun org-toggle-custom-properties-visibility ()
6025 "Display or hide properties in `org-custom-properties'."
6026 (interactive)
6027 (if org-custom-properties-overlays
6028 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6029 (setq org-custom-properties-overlays nil))
6030 (unless (not org-custom-properties)
6031 (save-excursion
6032 (save-restriction
6033 (widen)
6034 (goto-char (point-min))
6035 (while (re-search-forward org-property-re nil t)
6036 (mapc (lambda(p)
6037 (when (equal p (substring (match-string 1) 1 -1))
6038 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6039 (overlay-put o 'invisible t)
6040 (overlay-put o 'org-custom-property t)
6041 (push o org-custom-properties-overlays))))
6042 org-custom-properties)))))))
6044 (defun org-fontify-entities (limit)
6045 "Find an entity to fontify."
6046 (let (ee)
6047 (when org-pretty-entities
6048 (catch 'match
6049 (while (re-search-forward
6050 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6051 limit t)
6052 (if (and (not (org-in-indented-comment-line))
6053 (setq ee (org-entity-get (match-string 1)))
6054 (= (length (nth 6 ee)) 1))
6055 (let*
6056 ((end (if (equal (match-string 2) "{}")
6057 (match-end 2)
6058 (match-end 1))))
6059 (add-text-properties
6060 (match-beginning 0) end
6061 (list 'font-lock-fontified t))
6062 (compose-region (match-beginning 0) end
6063 (nth 6 ee) nil)
6064 (backward-char 1)
6065 (throw 'match t))))
6066 nil))))
6068 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6069 "Fontify string S like in Org-mode."
6070 (with-temp-buffer
6071 (insert s)
6072 (let ((org-odd-levels-only odd-levels))
6073 (org-mode)
6074 (font-lock-fontify-buffer)
6075 (buffer-string))))
6077 (defvar org-m nil)
6078 (defvar org-l nil)
6079 (defvar org-f nil)
6080 (defun org-get-level-face (n)
6081 "Get the right face for match N in font-lock matching of headlines."
6082 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6083 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6084 (if org-cycle-level-faces
6085 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6086 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6087 (cond
6088 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6089 ((eq n 2) org-f)
6090 (t (if org-level-color-stars-only nil org-f))))
6093 (defun org-get-todo-face (kwd)
6094 "Get the right face for a TODO keyword KWD.
6095 If KWD is a number, get the corresponding match group."
6096 (if (numberp kwd) (setq kwd (match-string kwd)))
6097 (or (org-face-from-face-or-color
6098 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6099 (and (member kwd org-done-keywords) 'org-done)
6100 'org-todo))
6102 (defun org-face-from-face-or-color (context inherit face-or-color)
6103 "Create a face list that inherits INHERIT, but sets the foreground color.
6104 When FACE-OR-COLOR is not a string, just return it."
6105 (if (stringp face-or-color)
6106 (list :inherit inherit
6107 (cdr (assoc context org-faces-easy-properties))
6108 face-or-color)
6109 face-or-color))
6111 (defun org-font-lock-add-tag-faces (limit)
6112 "Add the special tag faces."
6113 (when (and org-tag-faces org-tags-special-faces-re)
6114 (while (re-search-forward org-tags-special-faces-re limit t)
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'face (org-get-tag-face 1)
6117 'font-lock-fontified t))
6118 (backward-char 1))))
6120 (defun org-font-lock-add-priority-faces (limit)
6121 "Add the special priority faces."
6122 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6123 (when (save-match-data (org-at-heading-p))
6124 (add-text-properties
6125 (match-beginning 0) (match-end 0)
6126 (list 'face (or (org-face-from-face-or-color
6127 'priority 'org-special-keyword
6128 (cdr (assoc (char-after (match-beginning 1))
6129 org-priority-faces)))
6130 'org-special-keyword)
6131 'font-lock-fontified t)))))
6133 (defun org-get-tag-face (kwd)
6134 "Get the right face for a TODO keyword KWD.
6135 If KWD is a number, get the corresponding match group."
6136 (if (numberp kwd) (setq kwd (match-string kwd)))
6137 (or (org-face-from-face-or-color
6138 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6139 'org-tag))
6141 (defun org-unfontify-region (beg end &optional maybe_loudly)
6142 "Remove fontification and activation overlays from links."
6143 (font-lock-default-unfontify-region beg end)
6144 (let* ((buffer-undo-list t)
6145 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6146 (inhibit-modification-hooks t)
6147 deactivate-mark buffer-file-name buffer-file-truename)
6148 (org-decompose-region beg end)
6149 (remove-text-properties beg end
6150 '(mouse-face t keymap t org-linked-text t
6151 invisible t intangible t
6152 org-no-flyspell t org-emphasis t))
6153 (org-remove-font-lock-display-properties beg end)))
6155 (defconst org-script-display '(((raise -0.3) (height 0.7))
6156 ((raise 0.3) (height 0.7))
6157 ((raise -0.5))
6158 ((raise 0.5)))
6159 "Display properties for showing superscripts and subscripts.")
6161 (defun org-remove-font-lock-display-properties (beg end)
6162 "Remove specific display properties that have been added by font lock.
6163 The will remove the raise properties that are used to show superscripts
6164 and subscripts."
6165 (let (next prop)
6166 (while (< beg end)
6167 (setq next (next-single-property-change beg 'display nil end)
6168 prop (get-text-property beg 'display))
6169 (if (member prop org-script-display)
6170 (put-text-property beg next 'display nil))
6171 (setq beg next))))
6173 (defun org-raise-scripts (limit)
6174 "Add raise properties to sub/superscripts."
6175 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6176 (if (re-search-forward
6177 (if (eq org-use-sub-superscripts t)
6178 org-match-substring-regexp
6179 org-match-substring-with-braces-regexp)
6180 limit t)
6181 (let* ((pos (point)) table-p comment-p
6182 (mpos (match-beginning 3))
6183 (emph-p (get-text-property mpos 'org-emphasis))
6184 (link-p (get-text-property mpos 'mouse-face))
6185 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6186 (goto-char (point-at-bol))
6187 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6188 comment-p (org-looking-at-p "[ \t]*#"))
6189 (goto-char pos)
6190 ;; FIXME: Should we go back one character here, for a_b^c
6191 ;; (goto-char (1- pos)) ;????????????????????
6192 (if (or comment-p emph-p link-p keyw-p)
6194 (put-text-property (match-beginning 3) (match-end 0)
6195 'display
6196 (if (equal (char-after (match-beginning 2)) ?^)
6197 (nth (if table-p 3 1) org-script-display)
6198 (nth (if table-p 2 0) org-script-display)))
6199 (add-text-properties (match-beginning 2) (match-end 2)
6200 (list 'invisible t
6201 'org-dwidth t 'org-dwidth-n 1))
6202 (if (and (eq (char-after (match-beginning 3)) ?{)
6203 (eq (char-before (match-end 3)) ?}))
6204 (progn
6205 (add-text-properties
6206 (match-beginning 3) (1+ (match-beginning 3))
6207 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6208 (add-text-properties
6209 (1- (match-end 3)) (match-end 3)
6210 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6211 t)))))
6213 ;;;; Visibility cycling, including org-goto and indirect buffer
6215 ;;; Cycling
6217 (defvar org-cycle-global-status nil)
6218 (make-variable-buffer-local 'org-cycle-global-status)
6219 (defvar org-cycle-subtree-status nil)
6220 (make-variable-buffer-local 'org-cycle-subtree-status)
6222 ;;;###autoload
6224 (defvar org-inlinetask-min-level)
6226 (defun org-cycle (&optional arg)
6227 "TAB-action and visibility cycling for Org-mode.
6229 This is the command invoked in Org-mode by the TAB key. Its main purpose
6230 is outline visibility cycling, but it also invokes other actions
6231 in special contexts.
6233 - When this function is called with a prefix argument, rotate the entire
6234 buffer through 3 states (global cycling)
6235 1. OVERVIEW: Show only top-level headlines.
6236 2. CONTENTS: Show all headlines of all levels, but no body text.
6237 3. SHOW ALL: Show everything.
6238 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6239 determined by the variable `org-startup-folded', and by any VISIBILITY
6240 properties in the buffer.
6241 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6242 including any drawers.
6244 - When inside a table, re-align the table and move to the next field.
6246 - When point is at the beginning of a headline, rotate the subtree started
6247 by this line through 3 different states (local cycling)
6248 1. FOLDED: Only the main headline is shown.
6249 2. CHILDREN: The main headline and the direct children are shown.
6250 From this state, you can move to one of the children
6251 and zoom in further.
6252 3. SUBTREE: Show the entire subtree, including body text.
6253 If there is no subtree, switch directly from CHILDREN to FOLDED.
6255 - When point is at the beginning of an empty headline and the variable
6256 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6257 of the headline by demoting and promoting it to likely levels. This
6258 speeds up creation document structure by pressing TAB once or several
6259 times right after creating a new headline.
6261 - When there is a numeric prefix, go up to a heading with level ARG, do
6262 a `show-subtree' and return to the previous cursor position. If ARG
6263 is negative, go up that many levels.
6265 - When point is not at the beginning of a headline, execute the global
6266 binding for TAB, which is re-indenting the line. See the option
6267 `org-cycle-emulate-tab' for details.
6269 - Special case: if point is at the beginning of the buffer and there is
6270 no headline in line 1, this function will act as if called with prefix arg
6271 (C-u TAB, same as S-TAB) also when called without prefix arg.
6272 But only if also the variable `org-cycle-global-at-bob' is t."
6273 (interactive "P")
6274 (org-load-modules-maybe)
6275 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6276 (and org-cycle-level-after-item/entry-creation
6277 (or (org-cycle-level)
6278 (org-cycle-item-indentation))))
6279 (let* ((limit-level
6280 (or org-cycle-max-level
6281 (and (boundp 'org-inlinetask-min-level)
6282 org-inlinetask-min-level
6283 (1- org-inlinetask-min-level))))
6284 (nstars (and limit-level
6285 (if org-odd-levels-only
6286 (and limit-level (1- (* limit-level 2)))
6287 limit-level)))
6288 (org-outline-regexp
6289 (if (not (derived-mode-p 'org-mode))
6290 outline-regexp
6291 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6292 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6293 (not (looking-at org-outline-regexp))))
6294 (org-cycle-hook
6295 (if bob-special
6296 (delq 'org-optimize-window-after-visibility-change
6297 (copy-sequence org-cycle-hook))
6298 org-cycle-hook))
6299 (pos (point)))
6301 (if (or bob-special (equal arg '(4)))
6302 ;; special case: use global cycling
6303 (setq arg t))
6305 (cond
6307 ((equal arg '(16))
6308 (setq last-command 'dummy)
6309 (org-set-startup-visibility)
6310 (message "Startup visibility, plus VISIBILITY properties"))
6312 ((equal arg '(64))
6313 (show-all)
6314 (message "Entire buffer visible, including drawers"))
6316 ;; Table: enter it or move to the next field.
6317 ((org-at-table-p 'any)
6318 (if (org-at-table.el-p)
6319 (message "Use C-c ' to edit table.el tables")
6320 (if arg (org-table-edit-field t)
6321 (org-table-justify-field-maybe)
6322 (call-interactively 'org-table-next-field))))
6324 ((run-hook-with-args-until-success
6325 'org-tab-after-check-for-table-hook))
6327 ;; Global cycling: delegate to `org-cycle-internal-global'.
6328 ((eq arg t) (org-cycle-internal-global))
6330 ;; Drawers: delegate to `org-flag-drawer'.
6331 ((and org-drawers org-drawer-regexp
6332 (save-excursion
6333 (beginning-of-line 1)
6334 (looking-at org-drawer-regexp)))
6335 (org-flag-drawer ; toggle block visibility
6336 (not (get-char-property (match-end 0) 'invisible))))
6338 ;; Show-subtree, ARG levels up from here.
6339 ((integerp arg)
6340 (save-excursion
6341 (org-back-to-heading)
6342 (outline-up-heading (if (< arg 0) (- arg)
6343 (- (funcall outline-level) arg)))
6344 (org-show-subtree)))
6346 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6347 ((and (featurep 'org-inlinetask)
6348 (org-inlinetask-at-task-p)
6349 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6350 (org-inlinetask-toggle-visibility))
6352 ((org-try-cdlatex-tab))
6354 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6355 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6356 (save-excursion (beginning-of-line 1)
6357 (looking-at org-outline-regexp)))
6358 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6359 (org-cycle-internal-local))
6361 ;; From there: TAB emulation and template completion.
6362 (buffer-read-only (org-back-to-heading))
6364 ((run-hook-with-args-until-success
6365 'org-tab-after-check-for-cycling-hook))
6367 ((org-try-structure-completion))
6369 ((run-hook-with-args-until-success
6370 'org-tab-before-tab-emulation-hook))
6372 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6373 (or (not (bolp))
6374 (not (looking-at org-outline-regexp))))
6375 (call-interactively (global-key-binding "\t")))
6377 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6378 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6379 (or (and (eq org-cycle-emulate-tab 'white)
6380 (= (match-end 0) (point-at-eol)))
6381 (and (eq org-cycle-emulate-tab 'whitestart)
6382 (>= (match-end 0) pos))))
6384 (eq org-cycle-emulate-tab t))
6385 (call-interactively (global-key-binding "\t")))
6387 (t (save-excursion
6388 (org-back-to-heading)
6389 (org-cycle)))))))
6391 (defun org-cycle-internal-global ()
6392 "Do the global cycling action."
6393 ;; Hack to avoid display of messages for .org attachments in Gnus
6394 (let ((ga (string-match "\\*fontification" (buffer-name))))
6395 (cond
6396 ((and (eq last-command this-command)
6397 (eq org-cycle-global-status 'overview))
6398 ;; We just created the overview - now do table of contents
6399 ;; This can be slow in very large buffers, so indicate action
6400 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6401 (unless ga (message "CONTENTS..."))
6402 (org-content)
6403 (unless ga (message "CONTENTS...done"))
6404 (setq org-cycle-global-status 'contents)
6405 (run-hook-with-args 'org-cycle-hook 'contents))
6407 ((and (eq last-command this-command)
6408 (eq org-cycle-global-status 'contents))
6409 ;; We just showed the table of contents - now show everything
6410 (run-hook-with-args 'org-pre-cycle-hook 'all)
6411 (show-all)
6412 (unless ga (message "SHOW ALL"))
6413 (setq org-cycle-global-status 'all)
6414 (run-hook-with-args 'org-cycle-hook 'all))
6417 ;; Default action: go to overview
6418 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6419 (org-overview)
6420 (unless ga (message "OVERVIEW"))
6421 (setq org-cycle-global-status 'overview)
6422 (run-hook-with-args 'org-cycle-hook 'overview)))))
6424 (defun org-cycle-internal-local ()
6425 "Do the local cycling action."
6426 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6427 ;; First, determine end of headline (EOH), end of subtree or item
6428 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6429 (save-excursion
6430 (if (org-at-item-p)
6431 (progn
6432 (beginning-of-line)
6433 (setq struct (org-list-struct))
6434 (setq eoh (point-at-eol))
6435 (setq eos (org-list-get-item-end-before-blank (point) struct))
6436 (setq has-children (org-list-has-child-p (point) struct)))
6437 (org-back-to-heading)
6438 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6439 (setq eos (save-excursion
6440 (org-end-of-subtree t)
6441 (unless (eobp)
6442 (skip-chars-forward " \t\n"))
6443 (if (eobp) (point) (1- (point)))))
6444 (setq has-children
6445 (or (save-excursion
6446 (let ((level (funcall outline-level)))
6447 (outline-next-heading)
6448 (and (org-at-heading-p t)
6449 (> (funcall outline-level) level))))
6450 (save-excursion
6451 (org-list-search-forward (org-item-beginning-re) eos t)))))
6452 ;; Determine end invisible part of buffer (EOL)
6453 (beginning-of-line 2)
6454 ;; XEmacs doesn't have `next-single-char-property-change'
6455 (if (featurep 'xemacs)
6456 (while (and (not (eobp)) ;; this is like `next-line'
6457 (get-char-property (1- (point)) 'invisible))
6458 (beginning-of-line 2))
6459 (while (and (not (eobp)) ;; this is like `next-line'
6460 (get-char-property (1- (point)) 'invisible))
6461 (goto-char (next-single-char-property-change (point) 'invisible))
6462 (and (eolp) (beginning-of-line 2))))
6463 (setq eol (point)))
6464 ;; Find out what to do next and set `this-command'
6465 (cond
6466 ((= eos eoh)
6467 ;; Nothing is hidden behind this heading
6468 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6469 (message "EMPTY ENTRY")
6470 (setq org-cycle-subtree-status nil)
6471 (save-excursion
6472 (goto-char eos)
6473 (outline-next-heading)
6474 (if (outline-invisible-p) (org-flag-heading nil))))
6475 ((and (or (>= eol eos)
6476 (not (string-match "\\S-" (buffer-substring eol eos))))
6477 (or has-children
6478 (not (setq children-skipped
6479 org-cycle-skip-children-state-if-no-children))))
6480 ;; Entire subtree is hidden in one line: children view
6481 (run-hook-with-args 'org-pre-cycle-hook 'children)
6482 (if (org-at-item-p)
6483 (org-list-set-item-visibility (point-at-bol) struct 'children)
6484 (org-show-entry)
6485 (org-with-limited-levels (show-children))
6486 ;; FIXME: This slows down the func way too much.
6487 ;; How keep drawers hidden in subtree anyway?
6488 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6489 ;; (org-cycle-hide-drawers 'subtree))
6491 ;; Fold every list in subtree to top-level items.
6492 (when (eq org-cycle-include-plain-lists 'integrate)
6493 (save-excursion
6494 (org-back-to-heading)
6495 (while (org-list-search-forward (org-item-beginning-re) eos t)
6496 (beginning-of-line 1)
6497 (let* ((struct (org-list-struct))
6498 (prevs (org-list-prevs-alist struct))
6499 (end (org-list-get-bottom-point struct)))
6500 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6501 (org-list-get-all-items (point) struct prevs))
6502 (goto-char end))))))
6503 (message "CHILDREN")
6504 (save-excursion
6505 (goto-char eos)
6506 (outline-next-heading)
6507 (if (outline-invisible-p) (org-flag-heading nil)))
6508 (setq org-cycle-subtree-status 'children)
6509 (run-hook-with-args 'org-cycle-hook 'children))
6510 ((or children-skipped
6511 (and (eq last-command this-command)
6512 (eq org-cycle-subtree-status 'children)))
6513 ;; We just showed the children, or no children are there,
6514 ;; now show everything.
6515 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6516 (outline-flag-region eoh eos nil)
6517 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6518 (setq org-cycle-subtree-status 'subtree)
6519 (run-hook-with-args 'org-cycle-hook 'subtree))
6521 ;; Default action: hide the subtree.
6522 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6523 (outline-flag-region eoh eos t)
6524 (message "FOLDED")
6525 (setq org-cycle-subtree-status 'folded)
6526 (run-hook-with-args 'org-cycle-hook 'folded)))))
6528 ;;;###autoload
6529 (defun org-global-cycle (&optional arg)
6530 "Cycle the global visibility. For details see `org-cycle'.
6531 With \\[universal-argument] prefix arg, switch to startup visibility.
6532 With a numeric prefix, show all headlines up to that level."
6533 (interactive "P")
6534 (let ((org-cycle-include-plain-lists
6535 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6536 (cond
6537 ((integerp arg)
6538 (show-all)
6539 (hide-sublevels arg)
6540 (setq org-cycle-global-status 'contents))
6541 ((equal arg '(4))
6542 (org-set-startup-visibility)
6543 (message "Startup visibility, plus VISIBILITY properties."))
6545 (org-cycle '(4))))))
6547 (defun org-set-startup-visibility ()
6548 "Set the visibility required by startup options and properties."
6549 (cond
6550 ((eq org-startup-folded t)
6551 (org-cycle '(4)))
6552 ((eq org-startup-folded 'content)
6553 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6554 (org-cycle '(4)) (org-cycle '(4)))))
6555 (unless (eq org-startup-folded 'showeverything)
6556 (if org-hide-block-startup (org-hide-block-all))
6557 (org-set-visibility-according-to-property 'no-cleanup)
6558 (org-cycle-hide-archived-subtrees 'all)
6559 (org-cycle-hide-drawers 'all)
6560 (org-cycle-show-empty-lines t)))
6562 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6563 "Switch subtree visibilities according to :VISIBILITY: property."
6564 (interactive)
6565 (let (org-show-entry-below state)
6566 (save-excursion
6567 (goto-char (point-min))
6568 (while (re-search-forward
6569 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6570 nil t)
6571 (setq state (match-string 1))
6572 (save-excursion
6573 (org-back-to-heading t)
6574 (hide-subtree)
6575 (org-reveal)
6576 (cond
6577 ((equal state '("fold" "folded"))
6578 (hide-subtree))
6579 ((equal state "children")
6580 (org-show-hidden-entry)
6581 (show-children))
6582 ((equal state "content")
6583 (save-excursion
6584 (save-restriction
6585 (org-narrow-to-subtree)
6586 (org-content))))
6587 ((member state '("all" "showall"))
6588 (show-subtree)))))
6589 (unless no-cleanup
6590 (org-cycle-hide-archived-subtrees 'all)
6591 (org-cycle-hide-drawers 'all)
6592 (org-cycle-show-empty-lines 'all)))))
6594 ;; This function uses outline-regexp instead of the more fundamental
6595 ;; org-outline-regexp so that org-cycle-global works outside of Org
6596 ;; buffers, where outline-regexp is needed.
6597 (defun org-overview ()
6598 "Switch to overview mode, showing only top-level headlines.
6599 Really, this shows all headlines with level equal or greater than the level
6600 of the first headline in the buffer. This is important, because if the
6601 first headline is not level one, then (hide-sublevels 1) gives confusing
6602 results."
6603 (interactive)
6604 (let ((level (save-excursion
6605 (goto-char (point-min))
6606 (if (re-search-forward (concat "^" outline-regexp) nil t)
6607 (progn
6608 (goto-char (match-beginning 0))
6609 (funcall outline-level))))))
6610 (and level (hide-sublevels level))))
6612 (defun org-content (&optional arg)
6613 "Show all headlines in the buffer, like a table of contents.
6614 With numerical argument N, show content up to level N."
6615 (interactive "P")
6616 (save-excursion
6617 ;; Visit all headings and show their offspring
6618 (and (integerp arg) (org-overview))
6619 (goto-char (point-max))
6620 (catch 'exit
6621 (while (and (progn (condition-case nil
6622 (outline-previous-visible-heading 1)
6623 (error (goto-char (point-min))))
6625 (looking-at org-outline-regexp))
6626 (if (integerp arg)
6627 (show-children (1- arg))
6628 (show-branches))
6629 (if (bobp) (throw 'exit nil))))))
6632 (defun org-optimize-window-after-visibility-change (state)
6633 "Adjust the window after a change in outline visibility.
6634 This function is the default value of the hook `org-cycle-hook'."
6635 (when (get-buffer-window (current-buffer))
6636 (cond
6637 ((eq state 'content) nil)
6638 ((eq state 'all) nil)
6639 ((eq state 'folded) nil)
6640 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6641 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6643 (defun org-remove-empty-overlays-at (pos)
6644 "Remove outline overlays that do not contain non-white stuff."
6645 (mapc
6646 (lambda (o)
6647 (and (eq 'outline (overlay-get o 'invisible))
6648 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6649 (overlay-end o))))
6650 (delete-overlay o)))
6651 (overlays-at pos)))
6653 (defun org-clean-visibility-after-subtree-move ()
6654 "Fix visibility issues after moving a subtree."
6655 ;; First, find a reasonable region to look at:
6656 ;; Start two siblings above, end three below
6657 (let* ((beg (save-excursion
6658 (and (org-get-last-sibling)
6659 (org-get-last-sibling))
6660 (point)))
6661 (end (save-excursion
6662 (and (org-get-next-sibling)
6663 (org-get-next-sibling)
6664 (org-get-next-sibling))
6665 (if (org-at-heading-p)
6666 (point-at-eol)
6667 (point))))
6668 (level (looking-at "\\*+"))
6669 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6670 (save-excursion
6671 (save-restriction
6672 (narrow-to-region beg end)
6673 (when re
6674 ;; Properly fold already folded siblings
6675 (goto-char (point-min))
6676 (while (re-search-forward re nil t)
6677 (if (and (not (outline-invisible-p))
6678 (save-excursion
6679 (goto-char (point-at-eol)) (outline-invisible-p)))
6680 (hide-entry))))
6681 (org-cycle-show-empty-lines 'overview)
6682 (org-cycle-hide-drawers 'overview)))))
6684 (defun org-cycle-show-empty-lines (state)
6685 "Show empty lines above all visible headlines.
6686 The region to be covered depends on STATE when called through
6687 `org-cycle-hook'. Lisp program can use t for STATE to get the
6688 entire buffer covered. Note that an empty line is only shown if there
6689 are at least `org-cycle-separator-lines' empty lines before the headline."
6690 (when (not (= org-cycle-separator-lines 0))
6691 (save-excursion
6692 (let* ((n (abs org-cycle-separator-lines))
6693 (re (cond
6694 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6695 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6696 (t (let ((ns (number-to-string (- n 2))))
6697 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6698 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6699 beg end b e)
6700 (cond
6701 ((memq state '(overview contents t))
6702 (setq beg (point-min) end (point-max)))
6703 ((memq state '(children folded))
6704 (setq beg (point) end (progn (org-end-of-subtree t t)
6705 (beginning-of-line 2)
6706 (point)))))
6707 (when beg
6708 (goto-char beg)
6709 (while (re-search-forward re end t)
6710 (unless (get-char-property (match-end 1) 'invisible)
6711 (setq e (match-end 1))
6712 (if (< org-cycle-separator-lines 0)
6713 (setq b (save-excursion
6714 (goto-char (match-beginning 0))
6715 (org-back-over-empty-lines)
6716 (if (save-excursion
6717 (goto-char (max (point-min) (1- (point))))
6718 (org-at-heading-p))
6719 (1- (point))
6720 (point))))
6721 (setq b (match-beginning 1)))
6722 (outline-flag-region b e nil)))))))
6723 ;; Never hide empty lines at the end of the file.
6724 (save-excursion
6725 (goto-char (point-max))
6726 (outline-previous-heading)
6727 (outline-end-of-heading)
6728 (if (and (looking-at "[ \t\n]+")
6729 (= (match-end 0) (point-max)))
6730 (outline-flag-region (point) (match-end 0) nil))))
6732 (defun org-show-empty-lines-in-parent ()
6733 "Move to the parent and re-show empty lines before visible headlines."
6734 (save-excursion
6735 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6736 (org-cycle-show-empty-lines context))))
6738 (defun org-files-list ()
6739 "Return `org-agenda-files' list, plus all open org-mode files.
6740 This is useful for operations that need to scan all of a user's
6741 open and agenda-wise Org files."
6742 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6743 (dolist (buf (buffer-list))
6744 (with-current-buffer buf
6745 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6746 (let ((file (expand-file-name (buffer-file-name))))
6747 (unless (member file files)
6748 (push file files))))))
6749 files))
6751 (defsubst org-entry-beginning-position ()
6752 "Return the beginning position of the current entry."
6753 (save-excursion (outline-back-to-heading t) (point)))
6755 (defsubst org-entry-end-position ()
6756 "Return the end position of the current entry."
6757 (save-excursion (outline-next-heading) (point)))
6759 (defun org-cycle-hide-drawers (state)
6760 "Re-hide all drawers after a visibility state change."
6761 (when (and (derived-mode-p 'org-mode)
6762 (not (memq state '(overview folded contents))))
6763 (save-excursion
6764 (let* ((globalp (memq state '(contents all)))
6765 (beg (if globalp (point-min) (point)))
6766 (end (if globalp (point-max)
6767 (if (eq state 'children)
6768 (save-excursion (outline-next-heading) (point))
6769 (org-end-of-subtree t)))))
6770 (goto-char beg)
6771 (while (re-search-forward org-drawer-regexp end t)
6772 (org-flag-drawer t))))))
6774 (defun org-flag-drawer (flag)
6775 "When FLAG is non-nil, hide the drawer we are within.
6776 Otherwise make it visible."
6777 (save-excursion
6778 (beginning-of-line 1)
6779 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6780 (let ((b (match-end 0)))
6781 (if (re-search-forward
6782 "^[ \t]*:END:"
6783 (save-excursion (outline-next-heading) (point)) t)
6784 (outline-flag-region b (point-at-eol) flag)
6785 (error ":END: line missing at position %s" b))))))
6787 (defun org-subtree-end-visible-p ()
6788 "Is the end of the current subtree visible?"
6789 (pos-visible-in-window-p
6790 (save-excursion (org-end-of-subtree t) (point))))
6792 (defun org-first-headline-recenter (&optional N)
6793 "Move cursor to the first headline and recenter the headline.
6794 Optional argument N means put the headline into the Nth line of the window."
6795 (goto-char (point-min))
6796 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6797 (beginning-of-line)
6798 (recenter (prefix-numeric-value N))))
6800 ;;; Saving and restoring visibility
6802 (defun org-outline-overlay-data (&optional use-markers)
6803 "Return a list of the locations of all outline overlays.
6804 These are overlays with the `invisible' property value `outline'.
6805 The return value is a list of cons cells, with start and stop
6806 positions for each overlay.
6807 If USE-MARKERS is set, return the positions as markers."
6808 (let (beg end)
6809 (save-excursion
6810 (save-restriction
6811 (widen)
6812 (delq nil
6813 (mapcar (lambda (o)
6814 (when (eq (overlay-get o 'invisible) 'outline)
6815 (setq beg (overlay-start o)
6816 end (overlay-end o))
6817 (and beg end (> end beg)
6818 (if use-markers
6819 (cons (move-marker (make-marker) beg)
6820 (move-marker (make-marker) end))
6821 (cons beg end)))))
6822 (overlays-in (point-min) (point-max))))))))
6824 (defun org-set-outline-overlay-data (data)
6825 "Create visibility overlays for all positions in DATA.
6826 DATA should have been made by `org-outline-overlay-data'."
6827 (let (o)
6828 (save-excursion
6829 (save-restriction
6830 (widen)
6831 (show-all)
6832 (mapc (lambda (c)
6833 (outline-flag-region (car c) (cdr c) t))
6834 data)))))
6836 ;;; Folding of blocks
6838 (defvar org-hide-block-overlays nil
6839 "Overlays hiding blocks.")
6840 (make-variable-buffer-local 'org-hide-block-overlays)
6842 (defun org-block-map (function &optional start end)
6843 "Call FUNCTION at the head of all source blocks in the current buffer.
6844 Optional arguments START and END can be used to limit the range."
6845 (let ((start (or start (point-min)))
6846 (end (or end (point-max))))
6847 (save-excursion
6848 (goto-char start)
6849 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6850 (save-excursion
6851 (save-match-data
6852 (goto-char (match-beginning 0))
6853 (funcall function)))))))
6855 (defun org-hide-block-toggle-all ()
6856 "Toggle the visibility of all blocks in the current buffer."
6857 (org-block-map #'org-hide-block-toggle))
6859 (defun org-hide-block-all ()
6860 "Fold all blocks in the current buffer."
6861 (interactive)
6862 (org-show-block-all)
6863 (org-block-map #'org-hide-block-toggle-maybe))
6865 (defun org-show-block-all ()
6866 "Unfold all blocks in the current buffer."
6867 (interactive)
6868 (mapc 'delete-overlay org-hide-block-overlays)
6869 (setq org-hide-block-overlays nil))
6871 (defun org-hide-block-toggle-maybe ()
6872 "Toggle visibility of block at point."
6873 (interactive)
6874 (let ((case-fold-search t))
6875 (if (save-excursion
6876 (beginning-of-line 1)
6877 (looking-at org-block-regexp))
6878 (progn (org-hide-block-toggle)
6879 t) ;; to signal that we took action
6880 nil))) ;; to signal that we did not
6882 (defun org-hide-block-toggle (&optional force)
6883 "Toggle the visibility of the current block."
6884 (interactive)
6885 (save-excursion
6886 (beginning-of-line)
6887 (if (re-search-forward org-block-regexp nil t)
6888 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6889 (end (match-end 0)) ;; end of entire body
6891 (if (memq t (mapcar (lambda (overlay)
6892 (eq (overlay-get overlay 'invisible)
6893 'org-hide-block))
6894 (overlays-at start)))
6895 (if (or (not force) (eq force 'off))
6896 (mapc (lambda (ov)
6897 (when (member ov org-hide-block-overlays)
6898 (setq org-hide-block-overlays
6899 (delq ov org-hide-block-overlays)))
6900 (when (eq (overlay-get ov 'invisible)
6901 'org-hide-block)
6902 (delete-overlay ov)))
6903 (overlays-at start)))
6904 (setq ov (make-overlay start end))
6905 (overlay-put ov 'invisible 'org-hide-block)
6906 ;; make the block accessible to isearch
6907 (overlay-put
6908 ov 'isearch-open-invisible
6909 (lambda (ov)
6910 (when (member ov org-hide-block-overlays)
6911 (setq org-hide-block-overlays
6912 (delq ov org-hide-block-overlays)))
6913 (when (eq (overlay-get ov 'invisible)
6914 'org-hide-block)
6915 (delete-overlay ov))))
6916 (push ov org-hide-block-overlays)))
6917 (error "Not looking at a source block"))))
6919 ;; org-tab-after-check-for-cycling-hook
6920 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6921 ;; Remove overlays when changing major mode
6922 (add-hook 'org-mode-hook
6923 (lambda () (org-add-hook 'change-major-mode-hook
6924 'org-show-block-all 'append 'local)))
6926 ;;; Org-goto
6928 (defvar org-goto-window-configuration nil)
6929 (defvar org-goto-marker nil)
6930 (defvar org-goto-map
6931 (let ((map (make-sparse-keymap)))
6932 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6933 (while (setq cmd (pop cmds))
6934 (substitute-key-definition cmd cmd map global-map)))
6935 (suppress-keymap map)
6936 (org-defkey map "\C-m" 'org-goto-ret)
6937 (org-defkey map [(return)] 'org-goto-ret)
6938 (org-defkey map [(left)] 'org-goto-left)
6939 (org-defkey map [(right)] 'org-goto-right)
6940 (org-defkey map [(control ?g)] 'org-goto-quit)
6941 (org-defkey map "\C-i" 'org-cycle)
6942 (org-defkey map [(tab)] 'org-cycle)
6943 (org-defkey map [(down)] 'outline-next-visible-heading)
6944 (org-defkey map [(up)] 'outline-previous-visible-heading)
6945 (if org-goto-auto-isearch
6946 (if (fboundp 'define-key-after)
6947 (define-key-after map [t] 'org-goto-local-auto-isearch)
6948 nil)
6949 (org-defkey map "q" 'org-goto-quit)
6950 (org-defkey map "n" 'outline-next-visible-heading)
6951 (org-defkey map "p" 'outline-previous-visible-heading)
6952 (org-defkey map "f" 'outline-forward-same-level)
6953 (org-defkey map "b" 'outline-backward-same-level)
6954 (org-defkey map "u" 'outline-up-heading))
6955 (org-defkey map "/" 'org-occur)
6956 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6957 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6958 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6959 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6960 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6961 map))
6963 (defconst org-goto-help
6964 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6965 RET=jump to location [Q]uit and return to previous location
6966 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6968 (defvar org-goto-start-pos) ; dynamically scoped parameter
6970 ;; FIXME: Docstring does not mention both interfaces
6971 (defun org-goto (&optional alternative-interface)
6972 "Look up a different location in the current file, keeping current visibility.
6974 When you want look-up or go to a different location in a
6975 document, the fastest way is often to fold the entire buffer and
6976 then dive into the tree. This method has the disadvantage, that
6977 the previous location will be folded, which may not be what you
6978 want.
6980 This command works around this by showing a copy of the current
6981 buffer in an indirect buffer, in overview mode. You can dive
6982 into the tree in that copy, use org-occur and incremental search
6983 to find a location. When pressing RET or `Q', the command
6984 returns to the original buffer in which the visibility is still
6985 unchanged. After RET it will also jump to the location selected
6986 in the indirect buffer and expose the headline hierarchy above.
6988 With a prefix argument, use the alternative interface: e.g. if
6989 `org-goto-interface' is 'outline use 'outline-path-completion."
6990 (interactive "P")
6991 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6992 (org-refile-use-outline-path t)
6993 (org-refile-target-verify-function nil)
6994 (interface
6995 (if (not alternative-interface)
6996 org-goto-interface
6997 (if (eq org-goto-interface 'outline)
6998 'outline-path-completion
6999 'outline)))
7000 (org-goto-start-pos (point))
7001 (selected-point
7002 (if (eq interface 'outline)
7003 (car (org-get-location (current-buffer) org-goto-help))
7004 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7005 (org-refile-check-position pa)
7006 (nth 3 pa)))))
7007 (if selected-point
7008 (progn
7009 (org-mark-ring-push org-goto-start-pos)
7010 (goto-char selected-point)
7011 (if (or (outline-invisible-p) (org-invisible-p2))
7012 (org-show-context 'org-goto)))
7013 (message "Quit"))))
7015 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7016 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7017 (defvar org-goto-local-auto-isearch-map) ; defined below
7019 (defun org-get-location (buf help)
7020 "Let the user select a location in the Org-mode buffer BUF.
7021 This function uses a recursive edit. It returns the selected position
7022 or nil."
7023 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7024 (isearch-hide-immediately nil)
7025 (isearch-search-fun-function
7026 (lambda () 'org-goto-local-search-headings))
7027 (org-goto-selected-point org-goto-exit-command)
7028 (pop-up-frames nil)
7029 (special-display-buffer-names nil)
7030 (special-display-regexps nil)
7031 (special-display-function nil))
7032 (save-excursion
7033 (save-window-excursion
7034 (delete-other-windows)
7035 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7036 (org-pop-to-buffer-same-window
7037 (condition-case nil
7038 (make-indirect-buffer (current-buffer) "*org-goto*")
7039 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7040 (with-output-to-temp-buffer "*Help*"
7041 (princ help))
7042 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7043 (setq buffer-read-only nil)
7044 (let ((org-startup-truncated t)
7045 (org-startup-folded nil)
7046 (org-startup-align-all-tables nil))
7047 (org-mode)
7048 (org-overview))
7049 (setq buffer-read-only t)
7050 (if (and (boundp 'org-goto-start-pos)
7051 (integer-or-marker-p org-goto-start-pos))
7052 (let ((org-show-hierarchy-above t)
7053 (org-show-siblings t)
7054 (org-show-following-heading t))
7055 (goto-char org-goto-start-pos)
7056 (and (outline-invisible-p) (org-show-context)))
7057 (goto-char (point-min)))
7058 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7059 (message "Select location and press RET")
7060 (use-local-map org-goto-map)
7061 (recursive-edit)
7063 (kill-buffer "*org-goto*")
7064 (cons org-goto-selected-point org-goto-exit-command)))
7066 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7067 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7068 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7069 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7071 (defun org-goto-local-search-headings (string bound noerror)
7072 "Search and make sure that any matches are in headlines."
7073 (catch 'return
7074 (while (if isearch-forward
7075 (search-forward string bound noerror)
7076 (search-backward string bound noerror))
7077 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7078 (and (member :headline context)
7079 (not (member :tags context))))
7080 (throw 'return (point))))))
7082 (defun org-goto-local-auto-isearch ()
7083 "Start isearch."
7084 (interactive)
7085 (goto-char (point-min))
7086 (let ((keys (this-command-keys)))
7087 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7088 (isearch-mode t)
7089 (isearch-process-search-char (string-to-char keys)))))
7091 (defun org-goto-ret (&optional arg)
7092 "Finish `org-goto' by going to the new location."
7093 (interactive "P")
7094 (setq org-goto-selected-point (point)
7095 org-goto-exit-command 'return)
7096 (throw 'exit nil))
7098 (defun org-goto-left ()
7099 "Finish `org-goto' by going to the new location."
7100 (interactive)
7101 (if (org-at-heading-p)
7102 (progn
7103 (beginning-of-line 1)
7104 (setq org-goto-selected-point (point)
7105 org-goto-exit-command 'left)
7106 (throw 'exit nil))
7107 (error "Not on a heading")))
7109 (defun org-goto-right ()
7110 "Finish `org-goto' by going to the new location."
7111 (interactive)
7112 (if (org-at-heading-p)
7113 (progn
7114 (setq org-goto-selected-point (point)
7115 org-goto-exit-command 'right)
7116 (throw 'exit nil))
7117 (error "Not on a heading")))
7119 (defun org-goto-quit ()
7120 "Finish `org-goto' without cursor motion."
7121 (interactive)
7122 (setq org-goto-selected-point nil)
7123 (setq org-goto-exit-command 'quit)
7124 (throw 'exit nil))
7126 ;;; Indirect buffer display of subtrees
7128 (defvar org-indirect-dedicated-frame nil
7129 "This is the frame being used for indirect tree display.")
7130 (defvar org-last-indirect-buffer nil)
7132 (defun org-tree-to-indirect-buffer (&optional arg)
7133 "Create indirect buffer and narrow it to current subtree.
7134 With numerical prefix ARG, go up to this level and then take that tree.
7135 If ARG is negative, go up that many levels.
7136 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7137 indirect buffer previously made with this command, to avoid proliferation of
7138 indirect buffers. However, when you call the command with a \
7139 \\[universal-argument] prefix, or
7140 when `org-indirect-buffer-display' is `new-frame', the last buffer
7141 is kept so that you can work with several indirect buffers at the same time.
7142 If `org-indirect-buffer-display' is `dedicated-frame', the \
7143 \\[universal-argument] prefix also
7144 requests that a new frame be made for the new buffer, so that the dedicated
7145 frame is not changed."
7146 (interactive "P")
7147 (let ((cbuf (current-buffer))
7148 (cwin (selected-window))
7149 (pos (point))
7150 beg end level heading ibuf)
7151 (save-excursion
7152 (org-back-to-heading t)
7153 (when (numberp arg)
7154 (setq level (org-outline-level))
7155 (if (< arg 0) (setq arg (+ level arg)))
7156 (while (> (setq level (org-outline-level)) arg)
7157 (outline-up-heading 1 t)))
7158 (setq beg (point)
7159 heading (org-get-heading))
7160 (org-end-of-subtree t t)
7161 (if (org-at-heading-p) (backward-char 1))
7162 (setq end (point)))
7163 (if (and (buffer-live-p org-last-indirect-buffer)
7164 (not (eq org-indirect-buffer-display 'new-frame))
7165 (not arg))
7166 (kill-buffer org-last-indirect-buffer))
7167 (setq ibuf (org-get-indirect-buffer cbuf)
7168 org-last-indirect-buffer ibuf)
7169 (cond
7170 ((or (eq org-indirect-buffer-display 'new-frame)
7171 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7172 (select-frame (make-frame))
7173 (delete-other-windows)
7174 (org-pop-to-buffer-same-window ibuf)
7175 (org-set-frame-title heading))
7176 ((eq org-indirect-buffer-display 'dedicated-frame)
7177 (raise-frame
7178 (select-frame (or (and org-indirect-dedicated-frame
7179 (frame-live-p org-indirect-dedicated-frame)
7180 org-indirect-dedicated-frame)
7181 (setq org-indirect-dedicated-frame (make-frame)))))
7182 (delete-other-windows)
7183 (org-pop-to-buffer-same-window ibuf)
7184 (org-set-frame-title (concat "Indirect: " heading)))
7185 ((eq org-indirect-buffer-display 'current-window)
7186 (org-pop-to-buffer-same-window ibuf))
7187 ((eq org-indirect-buffer-display 'other-window)
7188 (pop-to-buffer ibuf))
7189 (t (error "Invalid value")))
7190 (if (featurep 'xemacs)
7191 (save-excursion (org-mode) (turn-on-font-lock)))
7192 (narrow-to-region beg end)
7193 (show-all)
7194 (goto-char pos)
7195 (run-hook-with-args 'org-cycle-hook 'all)
7196 (and (window-live-p cwin) (select-window cwin))))
7198 (defun org-get-indirect-buffer (&optional buffer)
7199 (setq buffer (or buffer (current-buffer)))
7200 (let ((n 1) (base (buffer-name buffer)) bname)
7201 (while (buffer-live-p
7202 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7203 (setq n (1+ n)))
7204 (condition-case nil
7205 (make-indirect-buffer buffer bname 'clone)
7206 (error (make-indirect-buffer buffer bname)))))
7208 (defun org-set-frame-title (title)
7209 "Set the title of the current frame to the string TITLE."
7210 ;; FIXME: how to name a single frame in XEmacs???
7211 (unless (featurep 'xemacs)
7212 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7214 ;;;; Structure editing
7216 ;;; Inserting headlines
7218 (defun org-previous-line-empty-p ()
7219 (save-excursion
7220 (and (not (bobp))
7221 (or (beginning-of-line 0) t)
7222 (save-match-data
7223 (looking-at "[ \t]*$")))))
7225 (defun org-insert-heading (&optional force-heading invisible-ok)
7226 "Insert a new heading or item with same depth at point.
7227 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7228 If point is at the beginning of a headline, insert a sibling before the
7229 current headline. If point is not at the beginning, split the line,
7230 create the new headline with the text in the current line after point
7231 \(but see also the variable `org-M-RET-may-split-line').
7233 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7234 This is important for non-interactive uses of the command."
7235 (interactive "P")
7236 (if (or (= (buffer-size) 0)
7237 (and (not (save-excursion
7238 (and (ignore-errors (org-back-to-heading invisible-ok))
7239 (org-at-heading-p))))
7240 (or force-heading (not (org-in-item-p)))))
7241 (progn
7242 (insert "\n* ")
7243 (run-hooks 'org-insert-heading-hook))
7244 (when (or force-heading (not (org-insert-item)))
7245 (let* ((empty-line-p nil)
7246 (level nil)
7247 (on-heading (org-at-heading-p))
7248 (head (save-excursion
7249 (condition-case nil
7250 (progn
7251 (org-back-to-heading invisible-ok)
7252 (when (and (not on-heading)
7253 (featurep 'org-inlinetask)
7254 (integerp org-inlinetask-min-level)
7255 (>= (length (match-string 0))
7256 org-inlinetask-min-level))
7257 ;; Find a heading level before the inline task
7258 (while (and (setq level (org-up-heading-safe))
7259 (>= level org-inlinetask-min-level)))
7260 (if (org-at-heading-p)
7261 (org-back-to-heading invisible-ok)
7262 (error "This should not happen")))
7263 (setq empty-line-p (org-previous-line-empty-p))
7264 (match-string 0))
7265 (error "*"))))
7266 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7267 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7268 pos hide-previous previous-pos)
7269 (cond
7270 ((and (org-at-heading-p) (bolp)
7271 (or (bobp)
7272 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7273 ;; insert before the current line
7274 (open-line (if blank 2 1)))
7275 ((and (bolp)
7276 (not org-insert-heading-respect-content)
7277 (or (bobp)
7278 (save-excursion
7279 (backward-char 1) (not (outline-invisible-p)))))
7280 ;; insert right here
7281 nil)
7283 ;; somewhere in the line
7284 (save-excursion
7285 (setq previous-pos (point-at-bol))
7286 (end-of-line)
7287 (setq hide-previous (outline-invisible-p)))
7288 (and org-insert-heading-respect-content (org-show-subtree))
7289 (let ((split
7290 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7291 (save-excursion
7292 (let ((p (point)))
7293 (goto-char (point-at-bol))
7294 (and (looking-at org-complex-heading-regexp)
7295 (match-beginning 4)
7296 (> p (match-beginning 4)))))))
7297 tags pos)
7298 (cond
7299 (org-insert-heading-respect-content
7300 (org-end-of-subtree nil t)
7301 (when (featurep 'org-inlinetask)
7302 (while (and (not (eobp))
7303 (looking-at "\\(\\*+\\)[ \t]+")
7304 (>= (length (match-string 1))
7305 org-inlinetask-min-level))
7306 (org-end-of-subtree nil t)))
7307 (or (bolp) (newline))
7308 (or (org-previous-line-empty-p)
7309 (and blank (newline)))
7310 (open-line 1))
7311 ((org-at-heading-p)
7312 (when hide-previous
7313 (show-children)
7314 (org-show-entry))
7315 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7316 (setq tags (and (match-end 2) (match-string 2)))
7317 (and (match-end 1)
7318 (delete-region (match-beginning 1) (match-end 1)))
7319 (setq pos (point-at-bol))
7320 (or split (end-of-line 1))
7321 (delete-horizontal-space)
7322 (if (string-match "\\`\\*+\\'"
7323 (buffer-substring (point-at-bol) (point)))
7324 (insert " "))
7325 (newline (if blank 2 1))
7326 (when tags
7327 (save-excursion
7328 (goto-char pos)
7329 (end-of-line 1)
7330 (insert " " tags)
7331 (org-set-tags nil 'align))))
7333 (or split (end-of-line 1))
7334 (newline (if blank 2 1)))))))
7335 (insert head) (just-one-space)
7336 (setq pos (point))
7337 (end-of-line 1)
7338 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7339 (when (and org-insert-heading-respect-content hide-previous)
7340 (save-excursion
7341 (goto-char previous-pos)
7342 (hide-subtree)))
7343 (run-hooks 'org-insert-heading-hook)))))
7345 (defun org-get-heading (&optional no-tags no-todo)
7346 "Return the heading of the current entry, without the stars.
7347 When NO-TAGS is non-nil, don't include tags.
7348 When NO-TODO is non-nil, don't include TODO keywords."
7349 (save-excursion
7350 (org-back-to-heading t)
7351 (cond
7352 ((and no-tags no-todo)
7353 (looking-at org-complex-heading-regexp)
7354 (match-string 4))
7355 (no-tags
7356 (looking-at (concat org-outline-regexp
7357 "\\(.*?\\)"
7358 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7359 (match-string 1))
7360 (no-todo
7361 (looking-at org-todo-line-regexp)
7362 (match-string 3))
7363 (t (looking-at org-heading-regexp)
7364 (match-string 2)))))
7366 (defun org-heading-components ()
7367 "Return the components of the current heading.
7368 This is a list with the following elements:
7369 - the level as an integer
7370 - the reduced level, different if `org-odd-levels-only' is set.
7371 - the TODO keyword, or nil
7372 - the priority character, like ?A, or nil if no priority is given
7373 - the headline text itself, or the tags string if no headline text
7374 - the tags string, or nil."
7375 (save-excursion
7376 (org-back-to-heading t)
7377 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7378 (list (length (match-string 1))
7379 (org-reduced-level (length (match-string 1)))
7380 (org-match-string-no-properties 2)
7381 (and (match-end 3) (aref (match-string 3) 2))
7382 (org-match-string-no-properties 4)
7383 (org-match-string-no-properties 5)))))
7385 (defun org-get-entry ()
7386 "Get the entry text, after heading, entire subtree."
7387 (save-excursion
7388 (org-back-to-heading t)
7389 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7391 (defun org-insert-heading-after-current ()
7392 "Insert a new heading with same level as current, after current subtree."
7393 (interactive)
7394 (org-back-to-heading)
7395 (org-insert-heading)
7396 (org-move-subtree-down)
7397 (end-of-line 1))
7399 (defun org-insert-heading-respect-content ()
7400 (interactive)
7401 (let ((org-insert-heading-respect-content t))
7402 (org-insert-heading t)))
7404 (defun org-insert-todo-heading-respect-content (&optional force-state)
7405 (interactive "P")
7406 (let ((org-insert-heading-respect-content t))
7407 (org-insert-todo-heading force-state t)))
7409 (defun org-insert-todo-heading (arg &optional force-heading)
7410 "Insert a new heading with the same level and TODO state as current heading.
7411 If the heading has no TODO state, or if the state is DONE, use the first
7412 state (TODO by default). Also with prefix arg, force first state."
7413 (interactive "P")
7414 (when (or force-heading (not (org-insert-item 'checkbox)))
7415 (org-insert-heading force-heading)
7416 (save-excursion
7417 (org-back-to-heading)
7418 (outline-previous-heading)
7419 (looking-at org-todo-line-regexp))
7420 (let*
7421 ((new-mark-x
7422 (if (or arg
7423 (not (match-beginning 2))
7424 (member (match-string 2) org-done-keywords))
7425 (car org-todo-keywords-1)
7426 (match-string 2)))
7427 (new-mark
7429 (run-hook-with-args-until-success
7430 'org-todo-get-default-hook new-mark-x nil)
7431 new-mark-x)))
7432 (beginning-of-line 1)
7433 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7434 (if org-treat-insert-todo-heading-as-state-change
7435 (org-todo new-mark)
7436 (insert new-mark " "))))
7437 (when org-provide-todo-statistics
7438 (org-update-parent-todo-statistics))))
7440 (defun org-insert-subheading (arg)
7441 "Insert a new subheading and demote it.
7442 Works for outline headings and for plain lists alike."
7443 (interactive "P")
7444 (org-insert-heading arg)
7445 (cond
7446 ((org-at-heading-p) (org-do-demote))
7447 ((org-at-item-p) (org-indent-item))))
7449 (defun org-insert-todo-subheading (arg)
7450 "Insert a new subheading with TODO keyword or checkbox and demote it.
7451 Works for outline headings and for plain lists alike."
7452 (interactive "P")
7453 (org-insert-todo-heading arg)
7454 (cond
7455 ((org-at-heading-p) (org-do-demote))
7456 ((org-at-item-p) (org-indent-item))))
7458 ;;; Promotion and Demotion
7460 (defvar org-after-demote-entry-hook nil
7461 "Hook run after an entry has been demoted.
7462 The cursor will be at the beginning of the entry.
7463 When a subtree is being demoted, the hook will be called for each node.")
7465 (defvar org-after-promote-entry-hook nil
7466 "Hook run after an entry has been promoted.
7467 The cursor will be at the beginning of the entry.
7468 When a subtree is being promoted, the hook will be called for each node.")
7470 (defun org-promote-subtree ()
7471 "Promote the entire subtree.
7472 See also `org-promote'."
7473 (interactive)
7474 (save-excursion
7475 (org-with-limited-levels (org-map-tree 'org-promote)))
7476 (org-fix-position-after-promote))
7478 (defun org-demote-subtree ()
7479 "Demote the entire subtree. See `org-demote'.
7480 See also `org-promote'."
7481 (interactive)
7482 (save-excursion
7483 (org-with-limited-levels (org-map-tree 'org-demote)))
7484 (org-fix-position-after-promote))
7487 (defun org-do-promote ()
7488 "Promote the current heading higher up the tree.
7489 If the region is active in `transient-mark-mode', promote all headings
7490 in the region."
7491 (interactive)
7492 (save-excursion
7493 (if (org-region-active-p)
7494 (org-map-region 'org-promote (region-beginning) (region-end))
7495 (org-promote)))
7496 (org-fix-position-after-promote))
7498 (defun org-do-demote ()
7499 "Demote the current heading lower down the tree.
7500 If the region is active in `transient-mark-mode', demote all headings
7501 in the region."
7502 (interactive)
7503 (save-excursion
7504 (if (org-region-active-p)
7505 (org-map-region 'org-demote (region-beginning) (region-end))
7506 (org-demote)))
7507 (org-fix-position-after-promote))
7509 (defun org-fix-position-after-promote ()
7510 "Make sure that after pro/demotion cursor position is right."
7511 (let ((pos (point)))
7512 (when (save-excursion
7513 (beginning-of-line 1)
7514 (looking-at org-todo-line-regexp)
7515 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7516 (cond ((eobp) (insert " "))
7517 ((eolp) (insert " "))
7518 ((equal (char-after) ?\ ) (forward-char 1))))))
7520 (defun org-current-level ()
7521 "Return the level of the current entry, or nil if before the first headline.
7522 The level is the number of stars at the beginning of the headline."
7523 (save-excursion
7524 (org-with-limited-levels
7525 (if (ignore-errors (org-back-to-heading t))
7526 (funcall outline-level)))))
7528 (defun org-get-previous-line-level ()
7529 "Return the outline depth of the last headline before the current line.
7530 Returns 0 for the first headline in the buffer, and nil if before the
7531 first headline."
7532 (let ((current-level (org-current-level))
7533 (prev-level (when (> (line-number-at-pos) 1)
7534 (save-excursion
7535 (beginning-of-line 0)
7536 (org-current-level)))))
7537 (cond ((null current-level) nil) ; Before first headline
7538 ((null prev-level) 0) ; At first headline
7539 (prev-level))))
7541 (defun org-reduced-level (l)
7542 "Compute the effective level of a heading.
7543 This takes into account the setting of `org-odd-levels-only'."
7544 (cond
7545 ((zerop l) 0)
7546 (org-odd-levels-only (1+ (floor (/ l 2))))
7547 (t l)))
7549 (defun org-level-increment ()
7550 "Return the number of stars that will be added or removed at a
7551 time to headlines when structure editing, based on the value of
7552 `org-odd-levels-only'."
7553 (if org-odd-levels-only 2 1))
7555 (defun org-get-valid-level (level &optional change)
7556 "Rectify a level change under the influence of `org-odd-levels-only'
7557 LEVEL is a current level, CHANGE is by how much the level should be
7558 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7559 even level numbers will become the next higher odd number."
7560 (if org-odd-levels-only
7561 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7562 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7563 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7564 (max 1 (+ level (or change 0)))))
7566 (if (boundp 'define-obsolete-function-alias)
7567 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7568 (define-obsolete-function-alias 'org-get-legal-level
7569 'org-get-valid-level)
7570 (define-obsolete-function-alias 'org-get-legal-level
7571 'org-get-valid-level "23.1")))
7573 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7574 ;; ̀org-with-limited-levels'
7575 (defun org-promote ()
7576 "Promote the current heading higher up the tree.
7577 If the region is active in `transient-mark-mode', promote all headings
7578 in the region."
7579 (org-back-to-heading t)
7580 (let* ((level (save-match-data (funcall outline-level)))
7581 (after-change-functions (remove 'flyspell-after-change-function
7582 after-change-functions))
7583 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7584 (diff (abs (- level (length up-head) -1))))
7585 (cond ((and (= level 1) org-called-with-limited-levels
7586 org-allow-promoting-top-level-subtree)
7587 (replace-match "# " nil t))
7588 ((= level 1)
7589 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7590 (t (replace-match up-head nil t)))
7591 ;; Fixup tag positioning
7592 (unless (= level 1)
7593 (and org-auto-align-tags (org-set-tags nil t))
7594 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7595 (run-hooks 'org-after-promote-entry-hook)))
7597 (defun org-demote ()
7598 "Demote the current heading lower down the tree.
7599 If the region is active in `transient-mark-mode', demote all headings
7600 in the region."
7601 (org-back-to-heading t)
7602 (let* ((level (save-match-data (funcall outline-level)))
7603 (after-change-functions (remove 'flyspell-after-change-function
7604 after-change-functions))
7605 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7606 (diff (abs (- level (length down-head) -1))))
7607 (replace-match down-head nil t)
7608 ;; Fixup tag positioning
7609 (and org-auto-align-tags (org-set-tags nil t))
7610 (if org-adapt-indentation (org-fixup-indentation diff))
7611 (run-hooks 'org-after-demote-entry-hook)))
7613 (defun org-cycle-level ()
7614 "Cycle the level of an empty headline through possible states.
7615 This goes first to child, then to parent, level, then up the hierarchy.
7616 After top level, it switches back to sibling level."
7617 (interactive)
7618 (let ((org-adapt-indentation nil))
7619 (when (org-point-at-end-of-empty-headline)
7620 (setq this-command 'org-cycle-level) ; Only needed for caching
7621 (let ((cur-level (org-current-level))
7622 (prev-level (org-get-previous-line-level)))
7623 (cond
7624 ;; If first headline in file, promote to top-level.
7625 ((= prev-level 0)
7626 (loop repeat (/ (- cur-level 1) (org-level-increment))
7627 do (org-do-promote)))
7628 ;; If same level as prev, demote one.
7629 ((= prev-level cur-level)
7630 (org-do-demote))
7631 ;; If parent is top-level, promote to top level if not already.
7632 ((= prev-level 1)
7633 (loop repeat (/ (- cur-level 1) (org-level-increment))
7634 do (org-do-promote)))
7635 ;; If top-level, return to prev-level.
7636 ((= cur-level 1)
7637 (loop repeat (/ (- prev-level 1) (org-level-increment))
7638 do (org-do-demote)))
7639 ;; If less than prev-level, promote one.
7640 ((< cur-level prev-level)
7641 (org-do-promote))
7642 ;; If deeper than prev-level, promote until higher than
7643 ;; prev-level.
7644 ((> cur-level prev-level)
7645 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7646 do (org-do-promote))))
7647 t))))
7649 (defun org-map-tree (fun)
7650 "Call FUN for every heading underneath the current one."
7651 (org-back-to-heading)
7652 (let ((level (funcall outline-level)))
7653 (save-excursion
7654 (funcall fun)
7655 (while (and (progn
7656 (outline-next-heading)
7657 (> (funcall outline-level) level))
7658 (not (eobp)))
7659 (funcall fun)))))
7661 (defun org-map-region (fun beg end)
7662 "Call FUN for every heading between BEG and END."
7663 (let ((org-ignore-region t))
7664 (save-excursion
7665 (setq end (copy-marker end))
7666 (goto-char beg)
7667 (if (and (re-search-forward org-outline-regexp-bol nil t)
7668 (< (point) end))
7669 (funcall fun))
7670 (while (and (progn
7671 (outline-next-heading)
7672 (< (point) end))
7673 (not (eobp)))
7674 (funcall fun)))))
7676 (defvar org-property-end-re) ; silence byte-compiler
7677 (defun org-fixup-indentation (diff)
7678 "Change the indentation in the current entry by DIFF.
7679 However, if any line in the current entry has no indentation, or if it
7680 would end up with no indentation after the change, nothing at all is done."
7681 (save-excursion
7682 (let ((end (save-excursion (outline-next-heading)
7683 (point-marker)))
7684 (prohibit (if (> diff 0)
7685 "^\\S-"
7686 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7687 col)
7688 (unless (save-excursion (end-of-line 1)
7689 (re-search-forward prohibit end t))
7690 (while (and (< (point) end)
7691 (re-search-forward "^[ \t]+" end t))
7692 (goto-char (match-end 0))
7693 (setq col (current-column))
7694 (if (< diff 0) (replace-match ""))
7695 (org-indent-to-column (+ diff col))))
7696 (move-marker end nil))))
7698 (defun org-convert-to-odd-levels ()
7699 "Convert an org-mode file with all levels allowed to one with odd levels.
7700 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7701 level 5 etc."
7702 (interactive)
7703 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7704 (let ((outline-level 'org-outline-level)
7705 (org-odd-levels-only nil) n)
7706 (save-excursion
7707 (goto-char (point-min))
7708 (while (re-search-forward "^\\*\\*+ " nil t)
7709 (setq n (- (length (match-string 0)) 2))
7710 (while (>= (setq n (1- n)) 0)
7711 (org-demote))
7712 (end-of-line 1))))))
7714 (defun org-convert-to-oddeven-levels ()
7715 "Convert an org-mode file with only odd levels to one with odd/even levels.
7716 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7717 file contains a section with an even level, conversion would
7718 destroy the structure of the file. An error is signaled in this
7719 case."
7720 (interactive)
7721 (goto-char (point-min))
7722 ;; First check if there are no even levels
7723 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7724 (org-show-context t)
7725 (error "Not all levels are odd in this file. Conversion not possible"))
7726 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7727 (let ((outline-regexp org-outline-regexp)
7728 (outline-level 'org-outline-level)
7729 (org-odd-levels-only nil) n)
7730 (save-excursion
7731 (goto-char (point-min))
7732 (while (re-search-forward "^\\*\\*+ " nil t)
7733 (setq n (/ (1- (length (match-string 0))) 2))
7734 (while (>= (setq n (1- n)) 0)
7735 (org-promote))
7736 (end-of-line 1))))))
7738 (defun org-tr-level (n)
7739 "Make N odd if required."
7740 (if org-odd-levels-only (1+ (/ n 2)) n))
7742 ;;; Vertical tree motion, cutting and pasting of subtrees
7744 (defun org-move-subtree-up (&optional arg)
7745 "Move the current subtree up past ARG headlines of the same level."
7746 (interactive "p")
7747 (org-move-subtree-down (- (prefix-numeric-value arg))))
7749 (defun org-move-subtree-down (&optional arg)
7750 "Move the current subtree down past ARG headlines of the same level."
7751 (interactive "p")
7752 (setq arg (prefix-numeric-value arg))
7753 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7754 'org-get-last-sibling))
7755 (ins-point (make-marker))
7756 (cnt (abs arg))
7757 (col (current-column))
7758 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7759 ;; Select the tree
7760 (org-back-to-heading)
7761 (setq beg0 (point))
7762 (save-excursion
7763 (setq ne-beg (org-back-over-empty-lines))
7764 (setq beg (point)))
7765 (save-match-data
7766 (save-excursion (outline-end-of-heading)
7767 (setq folded (outline-invisible-p)))
7768 (outline-end-of-subtree))
7769 (outline-next-heading)
7770 (setq ne-end (org-back-over-empty-lines))
7771 (setq end (point))
7772 (goto-char beg0)
7773 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7774 ;; include less whitespace
7775 (save-excursion
7776 (goto-char beg)
7777 (forward-line (- ne-beg ne-end))
7778 (setq beg (point))))
7779 ;; Find insertion point, with error handling
7780 (while (> cnt 0)
7781 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7782 (progn (goto-char beg0)
7783 (error "Cannot move past superior level or buffer limit")))
7784 (setq cnt (1- cnt)))
7785 (if (> arg 0)
7786 ;; Moving forward - still need to move over subtree
7787 (progn (org-end-of-subtree t t)
7788 (save-excursion
7789 (org-back-over-empty-lines)
7790 (or (bolp) (newline)))))
7791 (setq ne-ins (org-back-over-empty-lines))
7792 (move-marker ins-point (point))
7793 (setq txt (buffer-substring beg end))
7794 (org-save-markers-in-region beg end)
7795 (delete-region beg end)
7796 (org-remove-empty-overlays-at beg)
7797 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7798 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7799 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7800 (let ((bbb (point)))
7801 (insert-before-markers txt)
7802 (org-reinstall-markers-in-region bbb)
7803 (move-marker ins-point bbb))
7804 (or (bolp) (insert "\n"))
7805 (setq ins-end (point))
7806 (goto-char ins-point)
7807 (org-skip-whitespace)
7808 (when (and (< arg 0)
7809 (org-first-sibling-p)
7810 (> ne-ins ne-beg))
7811 ;; Move whitespace back to beginning
7812 (save-excursion
7813 (goto-char ins-end)
7814 (let ((kill-whole-line t))
7815 (kill-line (- ne-ins ne-beg)) (point)))
7816 (insert (make-string (- ne-ins ne-beg) ?\n)))
7817 (move-marker ins-point nil)
7818 (if folded
7819 (hide-subtree)
7820 (org-show-entry)
7821 (show-children)
7822 (org-cycle-hide-drawers 'children))
7823 (org-clean-visibility-after-subtree-move)
7824 ;; move back to the initial column we were at
7825 (move-to-column col)))
7827 (defvar org-subtree-clip ""
7828 "Clipboard for cut and paste of subtrees.
7829 This is actually only a copy of the kill, because we use the normal kill
7830 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7832 (defvar org-subtree-clip-folded nil
7833 "Was the last copied subtree folded?
7834 This is used to fold the tree back after pasting.")
7836 (defun org-cut-subtree (&optional n)
7837 "Cut the current subtree into the clipboard.
7838 With prefix arg N, cut this many sequential subtrees.
7839 This is a short-hand for marking the subtree and then cutting it."
7840 (interactive "p")
7841 (org-copy-subtree n 'cut))
7843 (defun org-copy-subtree (&optional n cut force-store-markers)
7844 "Cut the current subtree into the clipboard.
7845 With prefix arg N, cut this many sequential subtrees.
7846 This is a short-hand for marking the subtree and then copying it.
7847 If CUT is non-nil, actually cut the subtree.
7848 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7849 of some markers in the region, even if CUT is non-nil. This is
7850 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7851 (interactive "p")
7852 (let (beg end folded (beg0 (point)))
7853 (if (org-called-interactively-p 'any)
7854 (org-back-to-heading nil) ; take what looks like a subtree
7855 (org-back-to-heading t)) ; take what is really there
7856 (org-back-over-empty-lines)
7857 (setq beg (point))
7858 (skip-chars-forward " \t\r\n")
7859 (save-match-data
7860 (save-excursion (outline-end-of-heading)
7861 (setq folded (outline-invisible-p)))
7862 (condition-case nil
7863 (org-forward-heading-same-level (1- n) t)
7864 (error nil))
7865 (org-end-of-subtree t t))
7866 (org-back-over-empty-lines)
7867 (setq end (point))
7868 (goto-char beg0)
7869 (when (> end beg)
7870 (setq org-subtree-clip-folded folded)
7871 (when (or cut force-store-markers)
7872 (org-save-markers-in-region beg end))
7873 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7874 (setq org-subtree-clip (current-kill 0))
7875 (message "%s: Subtree(s) with %d characters"
7876 (if cut "Cut" "Copied")
7877 (length org-subtree-clip)))))
7879 (defun org-paste-subtree (&optional level tree for-yank)
7880 "Paste the clipboard as a subtree, with modification of headline level.
7881 The entire subtree is promoted or demoted in order to match a new headline
7882 level.
7884 If the cursor is at the beginning of a headline, the same level as
7885 that headline is used to paste the tree
7887 If not, the new level is derived from the *visible* headings
7888 before and after the insertion point, and taken to be the inferior headline
7889 level of the two. So if the previous visible heading is level 3 and the
7890 next is level 4 (or vice versa), level 4 will be used for insertion.
7891 This makes sure that the subtree remains an independent subtree and does
7892 not swallow low level entries.
7894 You can also force a different level, either by using a numeric prefix
7895 argument, or by inserting the heading marker by hand. For example, if the
7896 cursor is after \"*****\", then the tree will be shifted to level 5.
7898 If optional TREE is given, use this text instead of the kill ring.
7900 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7901 move back over whitespace before inserting, and move point to the end of
7902 the inserted text when done."
7903 (interactive "P")
7904 (setq tree (or tree (and kill-ring (current-kill 0))))
7905 (unless (org-kill-is-subtree-p tree)
7906 (error "%s"
7907 (substitute-command-keys
7908 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7909 (org-with-limited-levels
7910 (let* ((visp (not (outline-invisible-p)))
7911 (txt tree)
7912 (^re_ "\\(\\*+\\)[ \t]*")
7913 (old-level (if (string-match org-outline-regexp-bol txt)
7914 (- (match-end 0) (match-beginning 0) 1)
7915 -1))
7916 (force-level (cond (level (prefix-numeric-value level))
7917 ((and (looking-at "[ \t]*$")
7918 (string-match
7919 "^\\*+$" (buffer-substring
7920 (point-at-bol) (point))))
7921 (- (match-end 1) (match-beginning 1)))
7922 ((and (bolp)
7923 (looking-at org-outline-regexp))
7924 (- (match-end 0) (point) 1))))
7925 (previous-level (save-excursion
7926 (condition-case nil
7927 (progn
7928 (outline-previous-visible-heading 1)
7929 (if (looking-at ^re_)
7930 (- (match-end 0) (match-beginning 0) 1)
7932 (error 1))))
7933 (next-level (save-excursion
7934 (condition-case nil
7935 (progn
7936 (or (looking-at org-outline-regexp)
7937 (outline-next-visible-heading 1))
7938 (if (looking-at ^re_)
7939 (- (match-end 0) (match-beginning 0) 1)
7941 (error 1))))
7942 (new-level (or force-level (max previous-level next-level)))
7943 (shift (if (or (= old-level -1)
7944 (= new-level -1)
7945 (= old-level new-level))
7947 (- new-level old-level)))
7948 (delta (if (> shift 0) -1 1))
7949 (func (if (> shift 0) 'org-demote 'org-promote))
7950 (org-odd-levels-only nil)
7951 beg end newend)
7952 ;; Remove the forced level indicator
7953 (if force-level
7954 (delete-region (point-at-bol) (point)))
7955 ;; Paste
7956 (beginning-of-line (if (bolp) 1 2))
7957 (unless for-yank (org-back-over-empty-lines))
7958 (setq beg (point))
7959 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7960 (insert-before-markers txt)
7961 (unless (string-match "\n\\'" txt) (insert "\n"))
7962 (setq newend (point))
7963 (org-reinstall-markers-in-region beg)
7964 (setq end (point))
7965 (goto-char beg)
7966 (skip-chars-forward " \t\n\r")
7967 (setq beg (point))
7968 (if (and (outline-invisible-p) visp)
7969 (save-excursion (outline-show-heading)))
7970 ;; Shift if necessary
7971 (unless (= shift 0)
7972 (save-restriction
7973 (narrow-to-region beg end)
7974 (while (not (= shift 0))
7975 (org-map-region func (point-min) (point-max))
7976 (setq shift (+ delta shift)))
7977 (goto-char (point-min))
7978 (setq newend (point-max))))
7979 (when (or (org-called-interactively-p 'interactive) for-yank)
7980 (message "Clipboard pasted as level %d subtree" new-level))
7981 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7982 kill-ring
7983 (eq org-subtree-clip (current-kill 0))
7984 org-subtree-clip-folded)
7985 ;; The tree was folded before it was killed/copied
7986 (hide-subtree))
7987 (and for-yank (goto-char newend)))))
7989 (defun org-kill-is-subtree-p (&optional txt)
7990 "Check if the current kill is an outline subtree, or a set of trees.
7991 Returns nil if kill does not start with a headline, or if the first
7992 headline level is not the largest headline level in the tree.
7993 So this will actually accept several entries of equal levels as well,
7994 which is OK for `org-paste-subtree'.
7995 If optional TXT is given, check this string instead of the current kill."
7996 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7997 (re (org-get-limited-outline-regexp))
7998 (^re (concat "^" re))
7999 (start-level (and kill
8000 (string-match
8001 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8002 kill)
8003 (- (match-end 2) (match-beginning 2) 1)))
8004 (start (1+ (or (match-beginning 2) -1))))
8005 (if (not start-level)
8006 (progn
8007 nil) ;; does not even start with a heading
8008 (catch 'exit
8009 (while (setq start (string-match ^re kill (1+ start)))
8010 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8011 (throw 'exit nil)))
8012 t))))
8014 (defvar org-markers-to-move nil
8015 "Markers that should be moved with a cut-and-paste operation.
8016 Those markers are stored together with their positions relative to
8017 the start of the region.")
8019 (defun org-save-markers-in-region (beg end)
8020 "Check markers in region.
8021 If these markers are between BEG and END, record their position relative
8022 to BEG, so that after moving the block of text, we can put the markers back
8023 into place.
8024 This function gets called just before an entry or tree gets cut from the
8025 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8026 called immediately, to move the markers with the entries."
8027 (setq org-markers-to-move nil)
8028 (when (featurep 'org-clock)
8029 (org-clock-save-markers-for-cut-and-paste beg end))
8030 (when (featurep 'org-agenda)
8031 (org-agenda-save-markers-for-cut-and-paste beg end)))
8033 (defun org-check-and-save-marker (marker beg end)
8034 "Check if MARKER is between BEG and END.
8035 If yes, remember the marker and the distance to BEG."
8036 (when (and (marker-buffer marker)
8037 (equal (marker-buffer marker) (current-buffer)))
8038 (if (and (>= marker beg) (< marker end))
8039 (push (cons marker (- marker beg)) org-markers-to-move))))
8041 (defun org-reinstall-markers-in-region (beg)
8042 "Move all remembered markers to their position relative to BEG."
8043 (mapc (lambda (x)
8044 (move-marker (car x) (+ beg (cdr x))))
8045 org-markers-to-move)
8046 (setq org-markers-to-move nil))
8048 (defun org-narrow-to-subtree ()
8049 "Narrow buffer to the current subtree."
8050 (interactive)
8051 (save-excursion
8052 (save-match-data
8053 (org-with-limited-levels
8054 (narrow-to-region
8055 (progn (org-back-to-heading t) (point))
8056 (progn (org-end-of-subtree t t)
8057 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8058 (point)))))))
8060 (defun org-narrow-to-block ()
8061 "Narrow buffer to the current block."
8062 (interactive)
8063 (let* ((case-fold-search t)
8064 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8065 "^[ \t]*#\\+end_.*")))
8066 (if blockp
8067 (narrow-to-region (car blockp) (cdr blockp))
8068 (error "Not in a block"))))
8070 (eval-when-compile
8071 (defvar org-property-drawer-re))
8073 (defvar org-property-start-re) ;; defined below
8074 (defun org-clone-subtree-with-time-shift (n &optional shift)
8075 "Clone the task (subtree) at point N times.
8076 The clones will be inserted as siblings.
8078 In interactive use, the user will be prompted for the number of
8079 clones to be produced, and for a time SHIFT, which may be a
8080 repeater as used in time stamps, for example `+3d'.
8082 When a valid repeater is given and the entry contains any time
8083 stamps, the clones will become a sequence in time, with time
8084 stamps in the subtree shifted for each clone produced. If SHIFT
8085 is nil or the empty string, time stamps will be left alone. The
8086 ID property of the original subtree is removed.
8088 If the original subtree did contain time stamps with a repeater,
8089 the following will happen:
8090 - the repeater will be removed in each clone
8091 - an additional clone will be produced, with the current, unshifted
8092 date(s) in the entry.
8093 - the original entry will be placed *after* all the clones, with
8094 repeater intact.
8095 - the start days in the repeater in the original entry will be shifted
8096 to past the last clone.
8097 In this way you can spell out a number of instances of a repeating task,
8098 and still retain the repeater to cover future instances of the task."
8099 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8100 (let (beg end template task idprop
8101 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8102 (drawer-re org-drawer-regexp))
8103 (if (not (and (integerp n) (> n 0)))
8104 (error "Invalid number of replications %s" n))
8105 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8106 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8107 shift)))
8108 (error "Invalid shift specification %s" shift))
8109 (when doshift
8110 (setq shift-n (string-to-number (match-string 1 shift))
8111 shift-what (cdr (assoc (match-string 2 shift)
8112 '(("d" . day) ("w" . week)
8113 ("m" . month) ("y" . year))))))
8114 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8115 (setq nmin 1 nmax n)
8116 (org-back-to-heading t)
8117 (setq beg (point))
8118 (setq idprop (org-entry-get nil "ID"))
8119 (org-end-of-subtree t t)
8120 (or (bolp) (insert "\n"))
8121 (setq end (point))
8122 (setq template (buffer-substring beg end))
8123 (when (and doshift
8124 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8125 (delete-region beg end)
8126 (setq end beg)
8127 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8128 (goto-char end)
8129 (loop for n from nmin to nmax do
8130 ;; prepare clone
8131 (with-temp-buffer
8132 (insert template)
8133 (org-mode)
8134 (goto-char (point-min))
8135 (org-show-subtree)
8136 (and idprop (if org-clone-delete-id
8137 (org-entry-delete nil "ID")
8138 (org-id-get-create t)))
8139 (unless (= n 0)
8140 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8141 (kill-whole-line))
8142 (goto-char (point-min))
8143 (while (re-search-forward drawer-re nil t)
8144 (mapc (lambda (d)
8145 (org-remove-empty-drawer-at d (point))) org-drawers)))
8146 (goto-char (point-min))
8147 (when doshift
8148 (while (re-search-forward org-ts-regexp-both nil t)
8149 (org-timestamp-change (* n shift-n) shift-what))
8150 (unless (= n n-no-remove)
8151 (goto-char (point-min))
8152 (while (re-search-forward org-ts-regexp nil t)
8153 (save-excursion
8154 (goto-char (match-beginning 0))
8155 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8156 (delete-region (match-beginning 1) (match-end 1)))))))
8157 (setq task (buffer-string)))
8158 (insert task))
8159 (goto-char beg)))
8161 ;;; Outline Sorting
8163 (defun org-sort (with-case)
8164 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8165 Optional argument WITH-CASE means sort case-sensitively."
8166 (interactive "P")
8167 (cond
8168 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8169 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8171 (org-call-with-arg 'org-sort-entries with-case))))
8173 (defun org-sort-remove-invisible (s)
8174 (remove-text-properties 0 (length s) org-rm-props s)
8175 (while (string-match org-bracket-link-regexp s)
8176 (setq s (replace-match (if (match-end 2)
8177 (match-string 3 s)
8178 (match-string 1 s)) t t s)))
8181 (defvar org-priority-regexp) ; defined later in the file
8183 (defvar org-after-sorting-entries-or-items-hook nil
8184 "Hook that is run after a bunch of entries or items have been sorted.
8185 When children are sorted, the cursor is in the parent line when this
8186 hook gets called. When a region or a plain list is sorted, the cursor
8187 will be in the first entry of the sorted region/list.")
8189 (defun org-sort-entries
8190 (&optional with-case sorting-type getkey-func compare-func property)
8191 "Sort entries on a certain level of an outline tree.
8192 If there is an active region, the entries in the region are sorted.
8193 Else, if the cursor is before the first entry, sort the top-level items.
8194 Else, the children of the entry at point are sorted.
8196 Sorting can be alphabetically, numerically, by date/time as given by
8197 a time stamp, by a property or by priority.
8199 The command prompts for the sorting type unless it has been given to the
8200 function through the SORTING-TYPE argument, which needs to be a character,
8201 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8202 precise meaning of each character:
8204 n Numerically, by converting the beginning of the entry/item to a number.
8205 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8206 t By date/time, either the first active time stamp in the entry, or, if
8207 none exist, by the first inactive one.
8208 s By the scheduled date/time.
8209 d By deadline date/time.
8210 c By creation time, which is assumed to be the first inactive time stamp
8211 at the beginning of a line.
8212 p By priority according to the cookie.
8213 r By the value of a property.
8215 Capital letters will reverse the sort order.
8217 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8218 called with point at the beginning of the record. It must return either
8219 a string or a number that should serve as the sorting key for that record.
8221 Comparing entries ignores case by default. However, with an optional argument
8222 WITH-CASE, the sorting considers case as well."
8223 (interactive "P")
8224 (let ((case-func (if with-case 'identity 'downcase))
8225 start beg end stars re re2
8226 txt what tmp)
8227 ;; Find beginning and end of region to sort
8228 (cond
8229 ((org-region-active-p)
8230 ;; we will sort the region
8231 (setq end (region-end)
8232 what "region")
8233 (goto-char (region-beginning))
8234 (if (not (org-at-heading-p)) (outline-next-heading))
8235 (setq start (point)))
8236 ((or (org-at-heading-p)
8237 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8238 ;; we will sort the children of the current headline
8239 (org-back-to-heading)
8240 (setq start (point)
8241 end (progn (org-end-of-subtree t t)
8242 (or (bolp) (insert "\n"))
8243 (org-back-over-empty-lines)
8244 (point))
8245 what "children")
8246 (goto-char start)
8247 (show-subtree)
8248 (outline-next-heading))
8250 ;; we will sort the top-level entries in this file
8251 (goto-char (point-min))
8252 (or (org-at-heading-p) (outline-next-heading))
8253 (setq start (point))
8254 (goto-char (point-max))
8255 (beginning-of-line 1)
8256 (when (looking-at ".*?\\S-")
8257 ;; File ends in a non-white line
8258 (end-of-line 1)
8259 (insert "\n"))
8260 (setq end (point-max))
8261 (setq what "top-level")
8262 (goto-char start)
8263 (show-all)))
8265 (setq beg (point))
8266 (if (>= beg end) (error "Nothing to sort"))
8268 (looking-at "\\(\\*+\\)")
8269 (setq stars (match-string 1)
8270 re (concat "^" (regexp-quote stars) " +")
8271 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8272 txt (buffer-substring beg end))
8273 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8274 (if (and (not (equal stars "*")) (string-match re2 txt))
8275 (error "Region to sort contains a level above the first entry"))
8277 (unless sorting-type
8278 (message
8279 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8280 [t]ime [s]cheduled [d]eadline [c]reated
8281 A/N/T/S/D/C/P/O/F means reversed:"
8282 what)
8283 (setq sorting-type (read-char-exclusive))
8285 (and (= (downcase sorting-type) ?f)
8286 (setq getkey-func
8287 (org-icompleting-read "Sort using function: "
8288 obarray 'fboundp t nil nil))
8289 (setq getkey-func (intern getkey-func)))
8291 (and (= (downcase sorting-type) ?r)
8292 (setq property
8293 (org-icompleting-read "Property: "
8294 (mapcar 'list (org-buffer-property-keys t))
8295 nil t))))
8297 (message "Sorting entries...")
8299 (save-restriction
8300 (narrow-to-region start end)
8301 (let ((dcst (downcase sorting-type))
8302 (case-fold-search nil)
8303 (now (current-time)))
8304 (sort-subr
8305 (/= dcst sorting-type)
8306 ;; This function moves to the beginning character of the "record" to
8307 ;; be sorted.
8308 (lambda nil
8309 (if (re-search-forward re nil t)
8310 (goto-char (match-beginning 0))
8311 (goto-char (point-max))))
8312 ;; This function moves to the last character of the "record" being
8313 ;; sorted.
8314 (lambda nil
8315 (save-match-data
8316 (condition-case nil
8317 (outline-forward-same-level 1)
8318 (error
8319 (goto-char (point-max))))))
8320 ;; This function returns the value that gets sorted against.
8321 (lambda nil
8322 (cond
8323 ((= dcst ?n)
8324 (if (looking-at org-complex-heading-regexp)
8325 (string-to-number (match-string 4))
8326 nil))
8327 ((= dcst ?a)
8328 (if (looking-at org-complex-heading-regexp)
8329 (funcall case-func (match-string 4))
8330 nil))
8331 ((= dcst ?t)
8332 (let ((end (save-excursion (outline-next-heading) (point))))
8333 (if (or (re-search-forward org-ts-regexp end t)
8334 (re-search-forward org-ts-regexp-both end t))
8335 (org-time-string-to-seconds (match-string 0))
8336 (org-float-time now))))
8337 ((= dcst ?c)
8338 (let ((end (save-excursion (outline-next-heading) (point))))
8339 (if (re-search-forward
8340 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8341 end t)
8342 (org-time-string-to-seconds (match-string 0))
8343 (org-float-time now))))
8344 ((= dcst ?s)
8345 (let ((end (save-excursion (outline-next-heading) (point))))
8346 (if (re-search-forward org-scheduled-time-regexp end t)
8347 (org-time-string-to-seconds (match-string 1))
8348 (org-float-time now))))
8349 ((= dcst ?d)
8350 (let ((end (save-excursion (outline-next-heading) (point))))
8351 (if (re-search-forward org-deadline-time-regexp end t)
8352 (org-time-string-to-seconds (match-string 1))
8353 (org-float-time now))))
8354 ((= dcst ?p)
8355 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8356 (string-to-char (match-string 2))
8357 org-default-priority))
8358 ((= dcst ?r)
8359 (or (org-entry-get nil property) ""))
8360 ((= dcst ?o)
8361 (if (looking-at org-complex-heading-regexp)
8362 (- 9999 (length (member (match-string 2)
8363 org-todo-keywords-1)))))
8364 ((= dcst ?f)
8365 (if getkey-func
8366 (progn
8367 (setq tmp (funcall getkey-func))
8368 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8369 tmp)
8370 (error "Invalid key function `%s'" getkey-func)))
8371 (t (error "Invalid sorting type `%c'" sorting-type))))
8373 (cond
8374 ((= dcst ?a) 'string<)
8375 ((= dcst ?f) compare-func)
8376 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8377 (run-hooks 'org-after-sorting-entries-or-items-hook)
8378 (message "Sorting entries...done")))
8380 (defun org-do-sort (table what &optional with-case sorting-type)
8381 "Sort TABLE of WHAT according to SORTING-TYPE.
8382 The user will be prompted for the SORTING-TYPE if the call to this
8383 function does not specify it. WHAT is only for the prompt, to indicate
8384 what is being sorted. The sorting key will be extracted from
8385 the car of the elements of the table.
8386 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8387 (unless sorting-type
8388 (message
8389 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8390 what)
8391 (setq sorting-type (read-char-exclusive)))
8392 (let ((dcst (downcase sorting-type))
8393 extractfun comparefun)
8394 ;; Define the appropriate functions
8395 (cond
8396 ((= dcst ?n)
8397 (setq extractfun 'string-to-number
8398 comparefun (if (= dcst sorting-type) '< '>)))
8399 ((= dcst ?a)
8400 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8401 (lambda(x) (downcase (org-sort-remove-invisible x))))
8402 comparefun (if (= dcst sorting-type)
8403 'string<
8404 (lambda (a b) (and (not (string< a b))
8405 (not (string= a b)))))))
8406 ((= dcst ?t)
8407 (setq extractfun
8408 (lambda (x)
8409 (if (or (string-match org-ts-regexp x)
8410 (string-match org-ts-regexp-both x))
8411 (org-float-time
8412 (org-time-string-to-time (match-string 0 x)))
8414 comparefun (if (= dcst sorting-type) '< '>)))
8415 (t (error "Invalid sorting type `%c'" sorting-type)))
8417 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8418 table)
8419 (lambda (a b) (funcall comparefun (car a) (car b))))))
8422 ;;; The orgstruct minor mode
8424 ;; Define a minor mode which can be used in other modes in order to
8425 ;; integrate the org-mode structure editing commands.
8427 ;; This is really a hack, because the org-mode structure commands use
8428 ;; keys which normally belong to the major mode. Here is how it
8429 ;; works: The minor mode defines all the keys necessary to operate the
8430 ;; structure commands, but wraps the commands into a function which
8431 ;; tests if the cursor is currently at a headline or a plain list
8432 ;; item. If that is the case, the structure command is used,
8433 ;; temporarily setting many Org-mode variables like regular
8434 ;; expressions for filling etc. However, when any of those keys is
8435 ;; used at a different location, function uses `key-binding' to look
8436 ;; up if the key has an associated command in another currently active
8437 ;; keymap (minor modes, major mode, global), and executes that
8438 ;; command. There might be problems if any of the keys is otherwise
8439 ;; used as a prefix key.
8441 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8442 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8443 ;; addresses this by checking explicitly for both bindings.
8445 (defvar orgstruct-mode-map (make-sparse-keymap)
8446 "Keymap for the minor `orgstruct-mode'.")
8448 (defvar org-local-vars nil
8449 "List of local variables, for use by `orgstruct-mode'.")
8451 ;;;###autoload
8452 (define-minor-mode orgstruct-mode
8453 "Toggle the minor mode `orgstruct-mode'.
8454 This mode is for using Org-mode structure commands in other
8455 modes. The following keys behave as if Org-mode were active, if
8456 the cursor is on a headline, or on a plain list item (both as
8457 defined by Org-mode).
8459 M-up Move entry/item up
8460 M-down Move entry/item down
8461 M-left Promote
8462 M-right Demote
8463 M-S-up Move entry/item up
8464 M-S-down Move entry/item down
8465 M-S-left Promote subtree
8466 M-S-right Demote subtree
8467 M-q Fill paragraph and items like in Org-mode
8468 C-c ^ Sort entries
8469 C-c - Cycle list bullet
8470 TAB Cycle item visibility
8471 M-RET Insert new heading/item
8472 S-M-RET Insert new TODO heading / Checkbox item
8473 C-c C-c Set tags / toggle checkbox"
8474 nil " OrgStruct" nil
8475 (org-load-modules-maybe)
8476 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8478 ;;;###autoload
8479 (defun turn-on-orgstruct ()
8480 "Unconditionally turn on `orgstruct-mode'."
8481 (orgstruct-mode 1))
8483 (defvar org-fb-vars nil)
8484 (make-variable-buffer-local 'org-fb-vars)
8485 (defun orgstruct++-mode (&optional arg)
8486 "Toggle `orgstruct-mode', the enhanced version of it.
8487 In addition to setting orgstruct-mode, this also exports all
8488 indentation and autofilling variables from org-mode into the
8489 buffer. It will also recognize item context in multiline items."
8490 (interactive "P")
8491 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8492 (if (< arg 1)
8493 (progn (orgstruct-mode -1)
8494 (mapc (lambda(v)
8495 (org-set-local (car v)
8496 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8497 org-fb-vars))
8498 (orgstruct-mode 1)
8499 (setq org-fb-vars nil)
8500 (let (var val)
8501 (mapc
8502 (lambda (x)
8503 (when (string-match
8504 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8505 (symbol-name (car x)))
8506 (setq var (car x) val (nth 1 x))
8507 (push (list var `(quote ,(eval var))) org-fb-vars)
8508 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8509 org-local-vars)
8510 (org-set-local 'orgstruct-is-++ t))))
8512 (defvar orgstruct-is-++ nil
8513 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8514 (make-variable-buffer-local 'orgstruct-is-++)
8516 ;;;###autoload
8517 (defun turn-on-orgstruct++ ()
8518 "Unconditionally turn on `orgstruct++-mode'."
8519 (orgstruct++-mode 1))
8521 (defun orgstruct-error ()
8522 "Error when there is no default binding for a structure key."
8523 (interactive)
8524 (error "This key has no function outside structure elements"))
8526 (defun orgstruct-setup ()
8527 "Setup orgstruct keymaps."
8528 (let ((nfunc 0)
8529 (bindings
8530 (list
8531 '([(meta up)] org-metaup)
8532 '([(meta down)] org-metadown)
8533 '([(meta left)] org-metaleft)
8534 '([(meta right)] org-metaright)
8535 '([(meta shift up)] org-shiftmetaup)
8536 '([(meta shift down)] org-shiftmetadown)
8537 '([(meta shift left)] org-shiftmetaleft)
8538 '([(meta shift right)] org-shiftmetaright)
8539 '([?\e (up)] org-metaup)
8540 '([?\e (down)] org-metadown)
8541 '([?\e (left)] org-metaleft)
8542 '([?\e (right)] org-metaright)
8543 '([?\e (shift up)] org-shiftmetaup)
8544 '([?\e (shift down)] org-shiftmetadown)
8545 '([?\e (shift left)] org-shiftmetaleft)
8546 '([?\e (shift right)] org-shiftmetaright)
8547 '([(shift up)] org-shiftup)
8548 '([(shift down)] org-shiftdown)
8549 '([(shift left)] org-shiftleft)
8550 '([(shift right)] org-shiftright)
8551 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8552 '("\M-q" fill-paragraph)
8553 '("\C-c^" org-sort)
8554 '("\C-c-" org-cycle-list-bullet)))
8555 elt key fun cmd)
8556 (while (setq elt (pop bindings))
8557 (setq nfunc (1+ nfunc))
8558 (setq key (org-key (car elt))
8559 fun (nth 1 elt)
8560 cmd (orgstruct-make-binding fun nfunc key))
8561 (org-defkey orgstruct-mode-map key cmd))
8563 ;; Prevent an error for users who forgot to make autoloads
8564 (require 'org-element)
8566 ;; Special treatment needed for TAB and RET
8567 (org-defkey orgstruct-mode-map [(tab)]
8568 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8569 (org-defkey orgstruct-mode-map "\C-i"
8570 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8572 (org-defkey orgstruct-mode-map "\M-\C-m"
8573 (orgstruct-make-binding 'org-insert-heading 105
8574 "\M-\C-m" [(meta return)]))
8575 (org-defkey orgstruct-mode-map [(meta return)]
8576 (orgstruct-make-binding 'org-insert-heading 106
8577 [(meta return)] "\M-\C-m"))
8579 (org-defkey orgstruct-mode-map [(shift meta return)]
8580 (orgstruct-make-binding 'org-insert-todo-heading 107
8581 [(meta return)] "\M-\C-m"))
8583 (org-defkey orgstruct-mode-map "\e\C-m"
8584 (orgstruct-make-binding 'org-insert-heading 108
8585 "\e\C-m" [?\e (return)]))
8586 (org-defkey orgstruct-mode-map [?\e (return)]
8587 (orgstruct-make-binding 'org-insert-heading 109
8588 [?\e (return)] "\e\C-m"))
8589 (org-defkey orgstruct-mode-map [?\e (shift return)]
8590 (orgstruct-make-binding 'org-insert-todo-heading 110
8591 [?\e (return)] "\e\C-m"))
8593 (unless org-local-vars
8594 (setq org-local-vars (org-get-local-variables)))
8598 (defun orgstruct-make-binding (fun n &rest keys)
8599 "Create a function for binding in the structure minor mode.
8600 FUN is the command to call inside a table. N is used to create a unique
8601 command name. KEYS are keys that should be checked in for a command
8602 to execute outside of tables."
8603 (eval
8604 (list 'defun
8605 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8606 '(arg)
8607 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8608 "Outside of structure, run the binding of `"
8609 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8610 "'.")
8611 '(interactive "p")
8612 (list 'if
8613 `(org-context-p 'headline 'item
8614 (and orgstruct-is-++
8615 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8616 'item-body))
8617 (list 'org-run-like-in-org-mode (list 'quote fun))
8618 (list 'let '(orgstruct-mode)
8619 (list 'call-interactively
8620 (append '(or)
8621 (mapcar (lambda (k)
8622 (list 'key-binding k))
8623 keys)
8624 '('orgstruct-error))))))))
8626 (defun org-contextualize-keys (alist contexts)
8627 "Return valid elements in ALIST depending on CONTEXTS.
8629 `org-agenda-custom-commands' or `org-capture-templates' are the
8630 values used for ALIST, and `org-agenda-custom-commands-contexts'
8631 or `org-capture-templates-contexts' are the associated contexts
8632 definitions."
8633 (let ((contexts
8634 ;; normalize contexts
8635 (mapcar
8636 (lambda(c) (cond ((listp (cadr c))
8637 (list (car c) (car c) (cadr c)))
8638 ((string= "" (cadr c))
8639 (list (car c) (car c) (caddr c)))
8640 (t c))) contexts))
8641 (a alist) c r s)
8642 ;; loop over all commands or templates
8643 (while (setq c (pop a))
8644 (let (vrules repl)
8645 (cond
8646 ((not (assoc (car c) contexts))
8647 (push c r))
8648 ((and (assoc (car c) contexts)
8649 (setq vrules (org-contextualize-validate-key
8650 (car c) contexts)))
8651 (mapc (lambda (vr)
8652 (when (not (equal (car vr) (cadr vr)))
8653 (setq repl vr))) vrules)
8654 (if (not repl) (push c r)
8655 (push (cadr repl) s)
8656 (push
8657 (cons (car c)
8658 (cdr (or (assoc (cadr repl) alist)
8659 (error "Undefined key `%s' as contextual replacement for `%s'"
8660 (cadr repl) (car c)))))
8661 r))))))
8662 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8663 (delq
8665 (delete-dups
8666 (mapcar (lambda (x)
8667 (let ((tpl (car x)))
8668 (when (not (delq
8670 (mapcar (lambda(y)
8671 (equal y tpl)) s))) x)))
8672 (reverse r))))))
8674 (defun org-contextualize-validate-key (key contexts)
8675 "Check CONTEXTS for agenda or capture KEY."
8676 (let (r rr res)
8677 (while (setq r (pop contexts))
8678 (mapc
8679 (lambda (rr)
8680 (when
8681 (and (equal key (car r))
8682 (if (functionp rr) (funcall rr)
8683 (or (and (eq (car rr) 'in-file)
8684 (buffer-file-name)
8685 (string-match (cdr rr) (buffer-file-name)))
8686 (and (eq (car rr) 'in-mode)
8687 (string-match (cdr rr) (symbol-name major-mode)))
8688 (when (and (eq (car rr) 'not-in-file)
8689 (buffer-file-name))
8690 (not (string-match (cdr rr) (buffer-file-name))))
8691 (when (eq (car rr) 'not-in-mode)
8692 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8693 (push r res)))
8694 (car (last r))))
8695 (delete-dups (delq nil res))))
8697 (defun org-context-p (&rest contexts)
8698 "Check if local context is any of CONTEXTS.
8699 Possible values in the list of contexts are `table', `headline', and `item'."
8700 (let ((pos (point)))
8701 (goto-char (point-at-bol))
8702 (prog1 (or (and (memq 'table contexts)
8703 (looking-at "[ \t]*|"))
8704 (and (memq 'headline contexts)
8705 (looking-at org-outline-regexp))
8706 (and (memq 'item contexts)
8707 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8708 (and (memq 'item-body contexts)
8709 (org-in-item-p)))
8710 (goto-char pos))))
8712 (defun org-get-local-variables ()
8713 "Return a list of all local variables in an Org mode buffer."
8714 (let (varlist)
8715 (with-current-buffer (get-buffer-create "*Org tmp*")
8716 (erase-buffer)
8717 (org-mode)
8718 (setq varlist (buffer-local-variables)))
8719 (kill-buffer "*Org tmp*")
8720 (delq nil
8721 (mapcar
8722 (lambda (x)
8723 (setq x
8724 (if (symbolp x)
8725 (list x)
8726 (list (car x) (list 'quote (cdr x)))))
8727 (if (string-match
8728 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8729 (symbol-name (car x)))
8730 x nil))
8731 varlist))))
8733 (defun org-clone-local-variables (from-buffer &optional regexp)
8734 "Clone local variables from FROM-BUFFER.
8735 Optional argument REGEXP selects variables to clone."
8736 (mapc
8737 (lambda (pair)
8738 (and (symbolp (car pair))
8739 (or (null regexp)
8740 (string-match regexp (symbol-name (car pair))))
8741 (set (make-local-variable (car pair))
8742 (cdr pair))))
8743 (buffer-local-variables from-buffer)))
8745 ;;;###autoload
8746 (defun org-run-like-in-org-mode (cmd)
8747 "Run a command, pretending that the current buffer is in Org-mode.
8748 This will temporarily bind local variables that are typically bound in
8749 Org-mode to the values they have in Org-mode, and then interactively
8750 call CMD."
8751 (org-load-modules-maybe)
8752 (unless org-local-vars
8753 (setq org-local-vars (org-get-local-variables)))
8754 (eval (list 'let org-local-vars
8755 (list 'call-interactively (list 'quote cmd)))))
8757 ;;;; Archiving
8759 (defun org-get-category (&optional pos force-refresh)
8760 "Get the category applying to position POS."
8761 (save-match-data
8762 (if force-refresh (org-refresh-category-properties))
8763 (let ((pos (or pos (point))))
8764 (or (get-text-property pos 'org-category)
8765 (progn (org-refresh-category-properties)
8766 (get-text-property pos 'org-category))))))
8768 (defun org-refresh-category-properties ()
8769 "Refresh category text properties in the buffer."
8770 (let ((case-fold-search t)
8771 (inhibit-read-only t)
8772 (def-cat (cond
8773 ((null org-category)
8774 (if buffer-file-name
8775 (file-name-sans-extension
8776 (file-name-nondirectory buffer-file-name))
8777 "???"))
8778 ((symbolp org-category) (symbol-name org-category))
8779 (t org-category)))
8780 beg end cat pos optionp)
8781 (org-unmodified
8782 (save-excursion
8783 (save-restriction
8784 (widen)
8785 (goto-char (point-min))
8786 (put-text-property (point) (point-max) 'org-category def-cat)
8787 (while (re-search-forward
8788 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8789 (setq pos (match-end 0)
8790 optionp (equal (char-after (match-beginning 0)) ?#)
8791 cat (org-trim (match-string 2)))
8792 (if optionp
8793 (setq beg (point-at-bol) end (point-max))
8794 (org-back-to-heading t)
8795 (setq beg (point) end (org-end-of-subtree t t)))
8796 (put-text-property beg end 'org-category cat)
8797 (put-text-property beg end 'org-category-position beg)
8798 (goto-char pos)))))))
8801 ;;;; Link Stuff
8803 ;;; Link abbreviations
8805 (defun org-link-expand-abbrev (link)
8806 "Apply replacements as defined in `org-link-abbrev-alist'."
8807 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8808 (let* ((key (match-string 1 link))
8809 (as (or (assoc key org-link-abbrev-alist-local)
8810 (assoc key org-link-abbrev-alist)))
8811 (tag (and (match-end 2) (match-string 3 link)))
8812 rpl)
8813 (if (not as)
8814 link
8815 (setq rpl (cdr as))
8816 (cond
8817 ((symbolp rpl) (funcall rpl tag))
8818 ((string-match "%(\\([^)]+\\))" rpl)
8819 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8820 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8821 ((string-match "%h" rpl)
8822 (replace-match (url-hexify-string (or tag "")) t t rpl))
8823 (t (concat rpl tag)))))
8824 link))
8826 ;;; Storing and inserting links
8828 (defvar org-insert-link-history nil
8829 "Minibuffer history for links inserted with `org-insert-link'.")
8831 (defvar org-stored-links nil
8832 "Contains the links stored with `org-store-link'.")
8834 (defvar org-store-link-plist nil
8835 "Plist with info about the most recently link created with `org-store-link'.")
8837 (defvar org-link-protocols nil
8838 "Link protocols added to Org-mode using `org-add-link-type'.")
8840 (defvar org-store-link-functions nil
8841 "List of functions that are called to create and store a link.
8842 Each function will be called in turn until one returns a non-nil
8843 value. Each function should check if it is responsible for creating
8844 this link (for example by looking at the major mode).
8845 If not, it must exit and return nil.
8846 If yes, it should return a non-nil value after a calling
8847 `org-store-link-props' with a list of properties and values.
8848 Special properties are:
8850 :type The link prefix, like \"http\". This must be given.
8851 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8852 This is obligatory as well.
8853 :description Optional default description for the second pair
8854 of brackets in an Org-mode link. The user can still change
8855 this when inserting this link into an Org-mode buffer.
8857 In addition to these, any additional properties can be specified
8858 and then used in remember templates.")
8860 (defun org-add-link-type (type &optional follow export)
8861 "Add TYPE to the list of `org-link-types'.
8862 Re-compute all regular expressions depending on `org-link-types'
8864 FOLLOW and EXPORT are two functions.
8866 FOLLOW should take the link path as the single argument and do whatever
8867 is necessary to follow the link, for example find a file or display
8868 a mail message.
8870 EXPORT should format the link path for export to one of the export formats.
8871 It should be a function accepting three arguments:
8873 path the path of the link, the text after the prefix (like \"http:\")
8874 desc the description of the link, if any, or a description added by
8875 org-export-normalize-links if there is none
8876 format the export format, a symbol like `html' or `latex' or `ascii'..
8878 The function may use the FORMAT information to return different values
8879 depending on the format. The return value will be put literally into
8880 the exported file. If the return value is nil, this means Org should
8881 do what it normally does with links which do not have EXPORT defined.
8883 Org-mode has a built-in default for exporting links. If you are happy with
8884 this default, there is no need to define an export function for the link
8885 type. For a simple example of an export function, see `org-bbdb.el'."
8886 (add-to-list 'org-link-types type t)
8887 (org-make-link-regexps)
8888 (if (assoc type org-link-protocols)
8889 (setcdr (assoc type org-link-protocols) (list follow export))
8890 (push (list type follow export) org-link-protocols)))
8892 (defvar org-agenda-buffer-name)
8894 ;;;###autoload
8895 (defun org-store-link (arg)
8896 "\\<org-mode-map>Store an org-link to the current location.
8897 This link is added to `org-stored-links' and can later be inserted
8898 into an org-buffer with \\[org-insert-link].
8900 For some link types, a prefix arg is interpreted:
8901 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8902 For file links, arg negates `org-context-in-file-links'."
8903 (interactive "P")
8904 (org-load-modules-maybe)
8905 (setq org-store-link-plist nil) ; reset
8906 (org-with-limited-levels
8907 (let (link cpltxt desc description search txt custom-id agenda-link)
8908 (cond
8910 ((run-hook-with-args-until-success 'org-store-link-functions)
8911 (setq link (plist-get org-store-link-plist :link)
8912 desc (or (plist-get org-store-link-plist :description) link)))
8914 ((org-src-edit-buffer-p)
8915 (let (label gc)
8916 (while (or (not label)
8917 (save-excursion
8918 (save-restriction
8919 (widen)
8920 (goto-char (point-min))
8921 (re-search-forward
8922 (regexp-quote (format org-coderef-label-format label))
8923 nil t))))
8924 (when label (message "Label exists already") (sit-for 2))
8925 (setq label (read-string "Code line label: " label)))
8926 (end-of-line 1)
8927 (setq link (format org-coderef-label-format label))
8928 (setq gc (- 79 (length link)))
8929 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8930 (insert link)
8931 (setq link (concat "(" label ")") desc nil)))
8933 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8934 ;; We are in the agenda, link to referenced location
8935 (let ((m (or (get-text-property (point) 'org-hd-marker)
8936 (get-text-property (point) 'org-marker))))
8937 (when m
8938 (org-with-point-at m
8939 (setq agenda-link
8940 (if (org-called-interactively-p 'any)
8941 (call-interactively 'org-store-link)
8942 (org-store-link nil)))))))
8944 ((eq major-mode 'calendar-mode)
8945 (let ((cd (calendar-cursor-to-date)))
8946 (setq link
8947 (format-time-string
8948 (car org-time-stamp-formats)
8949 (apply 'encode-time
8950 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8951 nil nil nil))))
8952 (org-store-link-props :type "calendar" :date cd)))
8954 ((eq major-mode 'help-mode)
8955 (setq link (concat "help:" (save-excursion
8956 (goto-char (point-min))
8957 (looking-at "^[^ ]+")
8958 (match-string 0))))
8959 (org-store-link-props :type "help"))
8961 ((eq major-mode 'w3-mode)
8962 (setq cpltxt (if (and (buffer-name)
8963 (not (string-match "Untitled" (buffer-name))))
8964 (buffer-name)
8965 (url-view-url t))
8966 link (url-view-url t))
8967 (org-store-link-props :type "w3" :url (url-view-url t)))
8969 ((eq major-mode 'w3m-mode)
8970 (setq cpltxt (or w3m-current-title w3m-current-url)
8971 link w3m-current-url)
8972 (org-store-link-props :type "w3m" :url (url-view-url t)))
8974 ((setq search (run-hook-with-args-until-success
8975 'org-create-file-search-functions))
8976 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8977 "::" search))
8978 (setq cpltxt (or description link)))
8980 ((eq major-mode 'image-mode)
8981 (setq cpltxt (concat "file:"
8982 (abbreviate-file-name buffer-file-name))
8983 link cpltxt)
8984 (org-store-link-props :type "image" :file buffer-file-name))
8986 ((eq major-mode 'dired-mode)
8987 ;; link to the file in the current line
8988 (let ((file (dired-get-filename nil t)))
8989 (setq file (if file
8990 (abbreviate-file-name
8991 (expand-file-name (dired-get-filename nil t)))
8992 ;; otherwise, no file so use current directory.
8993 default-directory))
8994 (setq cpltxt (concat "file:" file)
8995 link cpltxt)))
8997 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8998 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8999 (cond
9000 ((org-in-regexp "<<\\(.*?\\)>>")
9001 (setq cpltxt
9002 (concat "file:"
9003 (abbreviate-file-name
9004 (buffer-file-name (buffer-base-buffer)))
9005 "::" (match-string 1))
9006 link cpltxt))
9007 ((and (featurep 'org-id)
9008 (or (eq org-link-to-org-use-id t)
9009 (and (org-called-interactively-p 'any)
9010 (or (eq org-link-to-org-use-id 'create-if-interactive)
9011 (and (eq org-link-to-org-use-id
9012 'create-if-interactive-and-no-custom-id)
9013 (not custom-id))))
9014 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9015 ;; We can make a link using the ID.
9016 (setq link (condition-case nil
9017 (prog1 (org-id-store-link)
9018 (setq desc (plist-get org-store-link-plist :description)))
9019 (error
9020 ;; probably before first headline, link to file only
9021 (concat "file:"
9022 (abbreviate-file-name
9023 (buffer-file-name (buffer-base-buffer))))))))
9025 ;; Just link to current headline
9026 (setq cpltxt (concat "file:"
9027 (abbreviate-file-name
9028 (buffer-file-name (buffer-base-buffer)))))
9029 ;; Add a context search string
9030 (when (org-xor org-context-in-file-links arg)
9031 (setq txt (cond
9032 ((org-at-heading-p) nil)
9033 ((org-region-active-p)
9034 (buffer-substring (region-beginning) (region-end)))))
9035 (when (or (null txt) (string-match "\\S-" txt))
9036 (setq cpltxt
9037 (concat cpltxt "::"
9038 (condition-case nil
9039 (org-make-org-heading-search-string txt)
9040 (error "")))
9041 desc (or (nth 4 (ignore-errors
9042 (org-heading-components))) "NONE"))))
9043 (if (string-match "::\\'" cpltxt)
9044 (setq cpltxt (substring cpltxt 0 -2)))
9045 (setq link cpltxt))))
9047 ((buffer-file-name (buffer-base-buffer))
9048 ;; Just link to this file here.
9049 (setq cpltxt (concat "file:"
9050 (abbreviate-file-name
9051 (buffer-file-name (buffer-base-buffer)))))
9052 ;; Add a context string
9053 (when (org-xor org-context-in-file-links arg)
9054 (setq txt (if (org-region-active-p)
9055 (buffer-substring (region-beginning) (region-end))
9056 (buffer-substring (point-at-bol) (point-at-eol))))
9057 ;; Only use search option if there is some text.
9058 (when (string-match "\\S-" txt)
9059 (setq cpltxt
9060 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9061 desc "NONE")))
9062 (setq link cpltxt))
9064 ((org-called-interactively-p 'interactive)
9065 (error "Cannot link to a buffer which is not visiting a file"))
9067 (t (setq link nil)))
9069 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9070 (setq link (or link cpltxt)
9071 desc (or desc cpltxt))
9072 (if (equal desc "NONE") (setq desc nil))
9074 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9075 (progn
9076 (setq org-stored-links
9077 (cons (list link desc) org-stored-links))
9078 (message "Stored: %s" (or desc link))
9079 (when custom-id
9080 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9081 "::#" custom-id))
9082 (setq org-stored-links
9083 (cons (list link desc) org-stored-links))))
9084 (or agenda-link (and link (org-make-link-string link desc)))))))
9086 (defun org-store-link-props (&rest plist)
9087 "Store link properties, extract names and addresses."
9088 (let (x adr)
9089 (when (setq x (plist-get plist :from))
9090 (setq adr (mail-extract-address-components x))
9091 (setq plist (plist-put plist :fromname (car adr)))
9092 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9093 (when (setq x (plist-get plist :to))
9094 (setq adr (mail-extract-address-components x))
9095 (setq plist (plist-put plist :toname (car adr)))
9096 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9097 (let ((from (plist-get plist :from))
9098 (to (plist-get plist :to)))
9099 (when (and from to org-from-is-user-regexp)
9100 (setq plist
9101 (plist-put plist :fromto
9102 (if (string-match org-from-is-user-regexp from)
9103 (concat "to %t")
9104 (concat "from %f"))))))
9105 (setq org-store-link-plist plist))
9107 (defun org-add-link-props (&rest plist)
9108 "Add these properties to the link property list."
9109 (let (key value)
9110 (while plist
9111 (setq key (pop plist) value (pop plist))
9112 (setq org-store-link-plist
9113 (plist-put org-store-link-plist key value)))))
9115 (defun org-email-link-description (&optional fmt)
9116 "Return the description part of an email link.
9117 This takes information from `org-store-link-plist' and formats it
9118 according to FMT (default from `org-email-link-description-format')."
9119 (setq fmt (or fmt org-email-link-description-format))
9120 (let* ((p org-store-link-plist)
9121 (to (plist-get p :toaddress))
9122 (from (plist-get p :fromaddress))
9123 (table
9124 (list
9125 (cons "%c" (plist-get p :fromto))
9126 (cons "%F" (plist-get p :from))
9127 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9128 (cons "%T" (plist-get p :to))
9129 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9130 (cons "%s" (plist-get p :subject))
9131 (cons "%d" (plist-get p :date))
9132 (cons "%m" (plist-get p :message-id)))))
9133 (when (string-match "%c" fmt)
9134 ;; Check if the user wrote this message
9135 (if (and org-from-is-user-regexp from to
9136 (save-match-data (string-match org-from-is-user-regexp from)))
9137 (setq fmt (replace-match "to %t" t t fmt))
9138 (setq fmt (replace-match "from %f" t t fmt))))
9139 (org-replace-escapes fmt table)))
9141 (defun org-make-org-heading-search-string (&optional string heading)
9142 "Make search string for STRING or current headline."
9143 (interactive)
9144 (let ((s (or string (org-get-heading)))
9145 (lines org-context-in-file-links))
9146 (unless (and string (not heading))
9147 ;; We are using a headline, clean up garbage in there.
9148 (if (string-match org-todo-regexp s)
9149 (setq s (replace-match "" t t s)))
9150 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9151 (setq s (replace-match "" t t s)))
9152 (setq s (org-trim s))
9153 (if (string-match (concat "^\\(" org-quote-string "\\|"
9154 org-comment-string "\\)") s)
9155 (setq s (replace-match "" t t s)))
9156 (while (string-match org-ts-regexp s)
9157 (setq s (replace-match "" t t s))))
9158 (or string (setq s (concat "*" s))) ; Add * for headlines
9159 (when (and string (integerp lines) (> lines 0))
9160 (let ((slines (org-split-string s "\n")))
9161 (when (< lines (length slines))
9162 (setq s (mapconcat
9163 'identity
9164 (reverse (nthcdr (- (length slines) lines)
9165 (reverse slines))) "\n")))))
9166 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9168 (defun org-make-link-string (link &optional description)
9169 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9170 (unless (string-match "\\S-" link)
9171 (error "Empty link"))
9172 (when (and description
9173 (stringp description)
9174 (not (string-match "\\S-" description)))
9175 (setq description nil))
9176 (when (stringp description)
9177 ;; Remove brackets from the description, they are fatal.
9178 (while (string-match "\\[" description)
9179 (setq description (replace-match "{" t t description)))
9180 (while (string-match "\\]" description)
9181 (setq description (replace-match "}" t t description))))
9182 (when (equal link description)
9183 ;; No description needed, it is identical
9184 (setq description nil))
9185 (when (and (not description)
9186 (not (string-match (org-image-file-name-regexp) link))
9187 (not (equal link (org-link-escape link))))
9188 (setq description (org-extract-attributes link)))
9189 (setq link
9190 (cond ((string-match (org-image-file-name-regexp) link) link)
9191 ((string-match org-link-types-re link)
9192 (concat (match-string 1 link)
9193 (org-link-escape (substring link (match-end 1)))))
9194 (t (org-link-escape link))))
9195 (concat "[[" link "]"
9196 (if description (concat "[" description "]") "")
9197 "]"))
9199 (defconst org-link-escape-chars
9200 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9201 "List of characters that should be escaped in link.
9202 This is the list that is used for internal purposes.")
9204 (defconst org-link-escape-chars-browser
9205 '(?\ )
9206 "List of escapes for characters that are problematic in links.
9207 This is the list that is used before handing over to the browser.")
9209 (defun org-link-escape (text &optional table merge)
9210 "Return percent escaped representation of TEXT.
9211 TEXT is a string with the text to escape.
9212 Optional argument TABLE is a list with characters that should be
9213 escaped. When nil, `org-link-escape-chars' is used.
9214 If optional argument MERGE is set, merge TABLE into
9215 `org-link-escape-chars'."
9216 (cond
9217 ((and table merge)
9218 (mapc (lambda (defchr)
9219 (unless (member defchr table)
9220 (setq table (cons defchr table)))) org-link-escape-chars))
9221 ((null table)
9222 (setq table org-link-escape-chars)))
9223 (mapconcat
9224 (lambda (char)
9225 (if (or (member char table)
9226 (and (or (< char 32) (= char 37) (> char 126))
9227 org-url-hexify-p))
9228 (mapconcat (lambda (sequence-element)
9229 (format "%%%.2X" sequence-element))
9230 (or (encode-coding-char char 'utf-8)
9231 (error "Unable to percent escape character: %s"
9232 (char-to-string char))) "")
9233 (char-to-string char))) text ""))
9235 (defun org-link-unescape (str)
9236 "Unhex hexified Unicode strings as returned from the JavaScript function
9237 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9238 (unless (and (null str) (string= "" str))
9239 (let ((pos 0) (case-fold-search t) unhexed)
9240 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9241 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9242 (setq str (replace-match unhexed t t str))
9243 (setq pos (+ pos (length unhexed))))))
9244 str)
9246 (defun org-link-unescape-compound (hex)
9247 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9248 Note: this function also decodes single byte encodings like
9249 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9250 (save-match-data
9251 (let* ((bytes (cdr (split-string hex "%")))
9252 (ret "")
9253 (eat 0)
9254 (sum 0))
9255 (while bytes
9256 (let* ((val (string-to-number (pop bytes) 16))
9257 (shift-xor
9258 (if (= 0 eat)
9259 (cond
9260 ((>= val 252) (cons 6 252))
9261 ((>= val 248) (cons 5 248))
9262 ((>= val 240) (cons 4 240))
9263 ((>= val 224) (cons 3 224))
9264 ((>= val 192) (cons 2 192))
9265 (t (cons 0 0)))
9266 (cons 6 128))))
9267 (if (>= val 192) (setq eat (car shift-xor)))
9268 (setq val (logxor val (cdr shift-xor)))
9269 (setq sum (+ (lsh sum (car shift-xor)) val))
9270 (if (> eat 0) (setq eat (- eat 1)))
9271 (cond
9272 ((= 0 eat) ;multi byte
9273 (setq ret (concat ret (org-char-to-string sum)))
9274 (setq sum 0))
9275 ((not bytes) ; single byte(s)
9276 (setq ret (org-link-unescape-single-byte-sequence hex))))
9277 )) ;; end (while bytes
9278 ret )))
9280 (defun org-link-unescape-single-byte-sequence (hex)
9281 "Unhexify hex-encoded single byte character sequences."
9282 (mapconcat (lambda (byte)
9283 (char-to-string (string-to-number byte 16)))
9284 (cdr (split-string hex "%")) ""))
9286 (defun org-xor (a b)
9287 "Exclusive or."
9288 (if a (not b) b))
9290 (defun org-fixup-message-id-for-http (s)
9291 "Replace special characters in a message id, so it can be used in an http query."
9292 (when (string-match "%" s)
9293 (setq s (mapconcat (lambda (c)
9294 (if (eq c ?%)
9295 "%25"
9296 (char-to-string c)))
9297 s "")))
9298 (while (string-match "<" s)
9299 (setq s (replace-match "%3C" t t s)))
9300 (while (string-match ">" s)
9301 (setq s (replace-match "%3E" t t s)))
9302 (while (string-match "@" s)
9303 (setq s (replace-match "%40" t t s)))
9306 (defun org-link-prettify (link)
9307 "Return a human-readable representation of LINK.
9308 The car of LINK must be a raw link the cdr of LINK must be either
9309 a link description or nil."
9310 (let ((desc (or (cadr link) "<no description>")))
9311 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9312 "<" (car link) ">")))
9314 ;;;###autoload
9315 (defun org-insert-link-global ()
9316 "Insert a link like Org-mode does.
9317 This command can be called in any mode to insert a link in Org-mode syntax."
9318 (interactive)
9319 (org-load-modules-maybe)
9320 (org-run-like-in-org-mode 'org-insert-link))
9322 (defun org-insert-all-links (&optional keep)
9323 "Insert all links in `org-stored-links'."
9324 (interactive "P")
9325 (let ((links (copy-sequence org-stored-links)) l)
9326 (while (setq l (if keep (pop links) (pop org-stored-links)))
9327 (insert "- ")
9328 (org-insert-link nil (car l) (cadr l))
9329 (insert "\n"))))
9331 (defun org-link-fontify-links-to-this-file ()
9332 "Fontify links to the current file in `org-stored-links'."
9333 (let ((f (buffer-file-name)) a b)
9334 (setq a (mapcar (lambda(l)
9335 (let ((ll (car l)))
9336 (when (and (string-match "^file:\\(.+\\)::" ll)
9337 (equal f (expand-file-name (match-string 1 ll))))
9338 ll)))
9339 org-stored-links))
9340 (when (featurep 'org-id)
9341 (setq b (mapcar (lambda(l)
9342 (let ((ll (car l)))
9343 (when (and (string-match "^id:\\(.+\\)$" ll)
9344 (equal f (expand-file-name
9345 (or (org-id-find-id-file
9346 (match-string 1 ll)) ""))))
9347 ll)))
9348 org-stored-links)))
9349 (mapcar (lambda(l)
9350 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9351 (delq nil (append a b)))))
9353 (defvar org-link-links-in-this-file nil)
9354 (defun org-insert-link (&optional complete-file link-location default-description)
9355 "Insert a link. At the prompt, enter the link.
9357 Completion can be used to insert any of the link protocol prefixes like
9358 http or ftp in use.
9360 The history can be used to select a link previously stored with
9361 `org-store-link'. When the empty string is entered (i.e. if you just
9362 press RET at the prompt), the link defaults to the most recently
9363 stored link. As SPC triggers completion in the minibuffer, you need to
9364 use M-SPC or C-q SPC to force the insertion of a space character.
9366 You will also be prompted for a description, and if one is given, it will
9367 be displayed in the buffer instead of the link.
9369 If there is already a link at point, this command will allow you to edit link
9370 and description parts.
9372 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9373 be selected using completion. The path to the file will be relative to the
9374 current directory if the file is in the current directory or a subdirectory.
9375 Otherwise, the link will be the absolute path as completed in the minibuffer
9376 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9377 option `org-link-file-path-type'.
9379 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9380 the current directory or below.
9382 With three \\[universal-argument] prefixes, negate the meaning of
9383 `org-keep-stored-link-after-insertion'.
9385 If `org-make-link-description-function' is non-nil, this function will be
9386 called with the link target, and the result will be the default
9387 link description.
9389 If the LINK-LOCATION parameter is non-nil, this value will be
9390 used as the link location instead of reading one interactively.
9392 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9393 be used as the default description."
9394 (interactive "P")
9395 (let* ((wcf (current-window-configuration))
9396 (region (if (org-region-active-p)
9397 (buffer-substring (region-beginning) (region-end))))
9398 (remove (and region (list (region-beginning) (region-end))))
9399 (desc region)
9400 tmphist ; byte-compile incorrectly complains about this
9401 (link link-location)
9402 (abbrevs org-link-abbrev-alist-local)
9403 entry file all-prefixes auto-desc)
9404 (cond
9405 (link-location) ; specified by arg, just use it.
9406 ((org-in-regexp org-bracket-link-regexp 1)
9407 ;; We do have a link at point, and we are going to edit it.
9408 (setq remove (list (match-beginning 0) (match-end 0)))
9409 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9410 (setq link (read-string "Link: "
9411 (org-link-unescape
9412 (org-match-string-no-properties 1)))))
9413 ((or (org-in-regexp org-angle-link-re)
9414 (org-in-regexp org-plain-link-re))
9415 ;; Convert to bracket link
9416 (setq remove (list (match-beginning 0) (match-end 0))
9417 link (read-string "Link: "
9418 (org-remove-angle-brackets (match-string 0)))))
9419 ((member complete-file '((4) (16)))
9420 ;; Completing read for file names.
9421 (setq link (org-file-complete-link complete-file)))
9423 ;; Read link, with completion for stored links.
9424 (org-link-fontify-links-to-this-file)
9425 (org-switch-to-buffer-other-window "*Org Links*")
9426 (with-current-buffer "*Org Links*"
9427 (erase-buffer)
9428 (insert "Insert a link.
9429 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9430 (when org-stored-links
9431 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9432 (insert (mapconcat 'org-link-prettify
9433 (reverse org-stored-links) "\n")))
9434 (goto-char (point-min)))
9435 (let ((cw (selected-window)))
9436 (select-window (get-buffer-window "*Org Links*" 'visible))
9437 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9438 (unless (pos-visible-in-window-p (point-max))
9439 (org-fit-window-to-buffer))
9440 (and (window-live-p cw) (select-window cw)))
9441 ;; Fake a link history, containing the stored links.
9442 (setq tmphist (append (mapcar 'car org-stored-links)
9443 org-insert-link-history))
9444 (setq all-prefixes (append (mapcar 'car abbrevs)
9445 (mapcar 'car org-link-abbrev-alist)
9446 org-link-types))
9447 (unwind-protect
9448 (progn
9449 (setq link
9450 (let ((org-completion-use-ido nil)
9451 (org-completion-use-iswitchb nil))
9452 (org-completing-read
9453 "Link: "
9454 (append
9455 (mapcar (lambda (x) (list (concat x ":")))
9456 all-prefixes)
9457 (mapcar 'car org-stored-links)
9458 (mapcar 'cadr org-stored-links))
9459 nil nil nil
9460 'tmphist
9461 (caar org-stored-links))))
9462 (if (not (string-match "\\S-" link))
9463 (error "No link selected"))
9464 (mapc (lambda(l)
9465 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9466 org-stored-links)
9467 (if (or (member link all-prefixes)
9468 (and (equal ":" (substring link -1))
9469 (member (substring link 0 -1) all-prefixes)
9470 (setq link (substring link 0 -1))))
9471 (setq link (org-link-try-special-completion link))))
9472 (set-window-configuration wcf)
9473 (kill-buffer "*Org Links*"))
9474 (setq entry (assoc link org-stored-links))
9475 (or entry (push link org-insert-link-history))
9476 (setq desc (or desc (nth 1 entry)))))
9478 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9479 (not org-keep-stored-link-after-insertion))
9480 (setq org-stored-links (delq (assoc link org-stored-links)
9481 org-stored-links)))
9483 (if (string-match org-plain-link-re link)
9484 ;; URL-like link, normalize the use of angular brackets.
9485 (setq link (org-remove-angle-brackets link)))
9487 ;; Check if we are linking to the current file with a search option
9488 ;; If yes, simplify the link by using only the search option.
9489 (when (and buffer-file-name
9490 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9491 (let* ((path (match-string 1 link))
9492 (case-fold-search nil)
9493 (search (match-string 2 link)))
9494 (save-match-data
9495 (if (equal (file-truename buffer-file-name) (file-truename path))
9496 ;; We are linking to this same file, with a search option
9497 (setq link search)))))
9499 ;; Check if we can/should use a relative path. If yes, simplify the link
9500 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9501 (let* ((type (match-string 1 link))
9502 (path (match-string 2 link))
9503 (origpath path)
9504 (case-fold-search nil))
9505 (cond
9506 ((or (eq org-link-file-path-type 'absolute)
9507 (equal complete-file '(16)))
9508 (setq path (abbreviate-file-name (expand-file-name path))))
9509 ((eq org-link-file-path-type 'noabbrev)
9510 (setq path (expand-file-name path)))
9511 ((eq org-link-file-path-type 'relative)
9512 (setq path (file-relative-name path)))
9514 (save-match-data
9515 (if (string-match (concat "^" (regexp-quote
9516 (expand-file-name
9517 (file-name-as-directory
9518 default-directory))))
9519 (expand-file-name path))
9520 ;; We are linking a file with relative path name.
9521 (setq path (substring (expand-file-name path)
9522 (match-end 0)))
9523 (setq path (abbreviate-file-name (expand-file-name path)))))))
9524 (setq link (concat type path))
9525 (if (equal desc origpath)
9526 (setq desc path))))
9528 (if org-make-link-description-function
9529 (setq desc (funcall org-make-link-description-function link desc))
9530 (if default-description (setq desc default-description)
9531 (setq desc (or (and auto-desc desc)
9532 (read-string "Description: " desc)))))
9534 (unless (string-match "\\S-" desc) (setq desc nil))
9535 (if remove (apply 'delete-region remove))
9536 (insert (org-make-link-string link desc))))
9538 (defun org-link-try-special-completion (type)
9539 "If there is completion support for link type TYPE, offer it."
9540 (let ((fun (intern (concat "org-" type "-complete-link"))))
9541 (if (functionp fun)
9542 (funcall fun)
9543 (read-string "Link (no completion support): " (concat type ":")))))
9545 (defun org-file-complete-link (&optional arg)
9546 "Create a file link using completion."
9547 (let (file link)
9548 (setq file (read-file-name "File: "))
9549 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9550 (pwd1 (file-name-as-directory (abbreviate-file-name
9551 (expand-file-name ".")))))
9552 (cond
9553 ((equal arg '(16))
9554 (setq link (concat
9555 "file:"
9556 (abbreviate-file-name (expand-file-name file)))))
9557 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9558 (setq link (concat "file:" (match-string 1 file))))
9559 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9560 (expand-file-name file))
9561 (setq link (concat
9562 "file:" (match-string 1 (expand-file-name file)))))
9563 (t (setq link (concat "file:" file)))))
9564 link))
9566 (defun org-completing-read (&rest args)
9567 "Completing-read with SPACE being a normal character."
9568 (let ((enable-recursive-minibuffers t)
9569 (minibuffer-local-completion-map
9570 (copy-keymap minibuffer-local-completion-map)))
9571 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9572 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9573 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9574 (apply 'org-icompleting-read args)))
9576 (defun org-completing-read-no-i (&rest args)
9577 (let (org-completion-use-ido org-completion-use-iswitchb)
9578 (apply 'org-completing-read args)))
9580 (defun org-iswitchb-completing-read (prompt choices &rest args)
9581 "Use iswitch as a completing-read replacement to choose from choices.
9582 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9583 from."
9584 (let* ((iswitchb-use-virtual-buffers nil)
9585 (iswitchb-make-buflist-hook
9586 (lambda ()
9587 (setq iswitchb-temp-buflist choices))))
9588 (iswitchb-read-buffer prompt)))
9590 (defun org-icompleting-read (&rest args)
9591 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9592 (org-without-partial-completion
9593 (if (and org-completion-use-ido
9594 (fboundp 'ido-completing-read)
9595 (boundp 'ido-mode) ido-mode
9596 (listp (second args)))
9597 (let ((ido-enter-matching-directory nil))
9598 (apply 'ido-completing-read (concat (car args))
9599 (if (consp (car (nth 1 args)))
9600 (mapcar 'car (nth 1 args))
9601 (nth 1 args))
9602 (cddr args)))
9603 (if (and org-completion-use-iswitchb
9604 (boundp 'iswitchb-mode) iswitchb-mode
9605 (listp (second args)))
9606 (apply 'org-iswitchb-completing-read (concat (car args))
9607 (if (consp (car (nth 1 args)))
9608 (mapcar 'car (nth 1 args))
9609 (nth 1 args))
9610 (cddr args))
9611 (apply 'completing-read args)))))
9613 (defun org-extract-attributes (s)
9614 "Extract the attributes cookie from a string and set as text property."
9615 (let (a attr (start 0) key value)
9616 (save-match-data
9617 (when (string-match "{{\\([^}]+\\)}}$" s)
9618 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9619 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9620 (setq key (match-string 1 a) value (match-string 2 a)
9621 start (match-end 0)
9622 attr (plist-put attr (intern key) value))))
9623 (org-add-props s nil 'org-attr attr))
9626 (defun org-extract-attributes-from-string (tag)
9627 (let (key value attr)
9628 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9629 (setq key (match-string 1 tag) value (match-string 2 tag)
9630 tag (replace-match "" t t tag)
9631 attr (plist-put attr (intern key) value)))
9632 (cons tag attr)))
9634 (defun org-attributes-to-string (plist)
9635 "Format a property list into an HTML attribute list."
9636 (let ((s "") key value)
9637 (while plist
9638 (setq key (pop plist) value (pop plist))
9639 (and value
9640 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9643 ;;; Opening/following a link
9645 (defvar org-link-search-failed nil)
9647 (defvar org-open-link-functions nil
9648 "Hook for functions finding a plain text link.
9649 These functions must take a single argument, the link content.
9650 They will be called for links that look like [[link text][description]]
9651 when LINK TEXT does not have a protocol like \"http:\" and does not look
9652 like a filename (e.g. \"./blue.png\").
9654 These functions will be called *before* Org attempts to resolve the
9655 link by doing text searches in the current buffer - so if you want a
9656 link \"[[target]]\" to still find \"<<target>>\", your function should
9657 handle this as a special case.
9659 When the function does handle the link, it must return a non-nil value.
9660 If it decides that it is not responsible for this link, it must return
9661 nil to indicate that that Org-mode can continue with other options
9662 like exact and fuzzy text search.")
9664 (defun org-next-link ()
9665 "Move forward to the next link.
9666 If the link is in hidden text, expose it."
9667 (interactive)
9668 (when (and org-link-search-failed (eq this-command last-command))
9669 (goto-char (point-min))
9670 (message "Link search wrapped back to beginning of buffer"))
9671 (setq org-link-search-failed nil)
9672 (let* ((pos (point))
9673 (ct (org-context))
9674 (a (assoc :link ct)))
9675 (if a (goto-char (nth 2 a)))
9676 (if (re-search-forward org-any-link-re nil t)
9677 (progn
9678 (goto-char (match-beginning 0))
9679 (if (outline-invisible-p) (org-show-context)))
9680 (goto-char pos)
9681 (setq org-link-search-failed t)
9682 (error "No further link found"))))
9684 (defun org-previous-link ()
9685 "Move backward to the previous link.
9686 If the link is in hidden text, expose it."
9687 (interactive)
9688 (when (and org-link-search-failed (eq this-command last-command))
9689 (goto-char (point-max))
9690 (message "Link search wrapped back to end of buffer"))
9691 (setq org-link-search-failed nil)
9692 (let* ((pos (point))
9693 (ct (org-context))
9694 (a (assoc :link ct)))
9695 (if a (goto-char (nth 1 a)))
9696 (if (re-search-backward org-any-link-re nil t)
9697 (progn
9698 (goto-char (match-beginning 0))
9699 (if (outline-invisible-p) (org-show-context)))
9700 (goto-char pos)
9701 (setq org-link-search-failed t)
9702 (error "No further link found"))))
9704 (defun org-translate-link (s)
9705 "Translate a link string if a translation function has been defined."
9706 (if (and org-link-translation-function
9707 (fboundp org-link-translation-function)
9708 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9709 (progn
9710 (setq s (funcall org-link-translation-function
9711 (match-string 1 s) (match-string 2 s)))
9712 (concat (car s) ":" (cdr s)))
9715 (defun org-translate-link-from-planner (type path)
9716 "Translate a link from Emacs Planner syntax so that Org can follow it.
9717 This is still an experimental function, your mileage may vary."
9718 (cond
9719 ((member type '("http" "https" "news" "ftp"))
9720 ;; standard Internet links are the same.
9721 nil)
9722 ((and (equal type "irc") (string-match "^//" path))
9723 ;; Planner has two / at the beginning of an irc link, we have 1.
9724 ;; We should have zero, actually....
9725 (setq path (substring path 1)))
9726 ((and (equal type "lisp") (string-match "^/" path))
9727 ;; Planner has a slash, we do not.
9728 (setq type "elisp" path (substring path 1)))
9729 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9730 ;; A typical message link. Planner has the id after the final slash,
9731 ;; we separate it with a hash mark
9732 (setq path (concat (match-string 1 path) "#"
9733 (org-remove-angle-brackets (match-string 2 path)))))
9735 (cons type path))
9737 (defun org-find-file-at-mouse (ev)
9738 "Open file link or URL at mouse."
9739 (interactive "e")
9740 (mouse-set-point ev)
9741 (org-open-at-point 'in-emacs))
9743 (defun org-open-at-mouse (ev)
9744 "Open file link or URL at mouse.
9745 See the docstring of `org-open-file' for details."
9746 (interactive "e")
9747 (mouse-set-point ev)
9748 (if (eq major-mode 'org-agenda-mode)
9749 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9750 (org-open-at-point))
9752 (defvar org-window-config-before-follow-link nil
9753 "The window configuration before following a link.
9754 This is saved in case the need arises to restore it.")
9756 (defvar org-open-link-marker (make-marker)
9757 "Marker pointing to the location where `org-open-at-point; was called.")
9759 ;;;###autoload
9760 (defun org-open-at-point-global ()
9761 "Follow a link like Org-mode does.
9762 This command can be called in any mode to follow a link that has
9763 Org-mode syntax."
9764 (interactive)
9765 (org-run-like-in-org-mode 'org-open-at-point))
9767 ;;;###autoload
9768 (defun org-open-link-from-string (s &optional arg reference-buffer)
9769 "Open a link in the string S, as if it was in Org-mode."
9770 (interactive "sLink: \nP")
9771 (let ((reference-buffer (or reference-buffer (current-buffer))))
9772 (with-temp-buffer
9773 (let ((org-inhibit-startup (not reference-buffer)))
9774 (org-mode)
9775 (insert s)
9776 (goto-char (point-min))
9777 (when reference-buffer
9778 (setq org-link-abbrev-alist-local
9779 (with-current-buffer reference-buffer
9780 org-link-abbrev-alist-local)))
9781 (org-open-at-point arg reference-buffer)))))
9783 (defvar org-open-at-point-functions nil
9784 "Hook that is run when following a link at point.
9786 Functions in this hook must return t if they identify and follow
9787 a link at point. If they don't find anything interesting at point,
9788 they must return nil.")
9790 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9791 (defun org-open-at-point (&optional arg reference-buffer)
9792 "Open link at or after point.
9793 If there is no link at point, this function will search forward up to
9794 the end of the current line.
9795 Normally, files will be opened by an appropriate application. If the
9796 optional prefix argument ARG is non-nil, Emacs will visit the file.
9797 With a double prefix argument, try to open outside of Emacs, in the
9798 application the system uses for this file type."
9799 (interactive "P")
9800 ;; if in a code block, then open the block's results
9801 (unless (call-interactively #'org-babel-open-src-block-result)
9802 (org-load-modules-maybe)
9803 (move-marker org-open-link-marker (point))
9804 (setq org-window-config-before-follow-link (current-window-configuration))
9805 (org-remove-occur-highlights nil nil t)
9806 (cond
9807 ((and (org-at-heading-p)
9808 (not (org-at-timestamp-p t))
9809 (not (org-in-regexp
9810 (concat org-plain-link-re "\\|"
9811 org-bracket-link-regexp "\\|"
9812 org-angle-link-re "\\|"
9813 "[ \t]:[^ \t\n]+:[ \t]*$")))
9814 (not (get-text-property (point) 'org-linked-text)))
9815 (or (org-offer-links-in-entry arg)
9816 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9817 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9818 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9819 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9820 (not (org-in-regexp org-bracket-link-regexp)))
9821 (org-footnote-action))
9823 (let (type path link line search (pos (point)))
9824 (catch 'match
9825 (save-excursion
9826 (skip-chars-forward "^]\n\r")
9827 (when (org-in-regexp org-bracket-link-regexp 1)
9828 (setq link (org-extract-attributes
9829 (org-link-unescape (org-match-string-no-properties 1))))
9830 (while (string-match " *\n *" link)
9831 (setq link (replace-match " " t t link)))
9832 (setq link (org-link-expand-abbrev link))
9833 (cond
9834 ((or (file-name-absolute-p link)
9835 (string-match "^\\.\\.?/" link))
9836 (setq type "file" path link))
9837 ((string-match org-link-re-with-space3 link)
9838 (setq type (match-string 1 link) path (match-string 2 link)))
9839 ((string-match "^help:+\\(.+\\)" link)
9840 (setq type "help" path (match-string 1 link)))
9841 (t (setq type "thisfile" path link)))
9842 (throw 'match t)))
9844 (when (get-text-property (point) 'org-linked-text)
9845 (setq type "thisfile"
9846 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9847 (1+ (point)) (point))
9848 path (buffer-substring
9849 (or (previous-single-property-change pos 'org-linked-text)
9850 (point-min))
9851 (or (next-single-property-change pos 'org-linked-text)
9852 (point-max))))
9853 (throw 'match t))
9855 (save-excursion
9856 (when (or (org-in-regexp org-angle-link-re)
9857 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9858 (save-match-data (not (looking-back "\\[\\[")))))
9859 (setq type (match-string 1)
9860 path (org-link-unescape (match-string 2)))
9861 (throw 'match t)))
9862 (save-excursion
9863 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9864 (setq type "tags"
9865 path (match-string 1))
9866 (while (string-match ":" path)
9867 (setq path (replace-match "+" t t path)))
9868 (throw 'match t)))
9869 (when (org-in-regexp "<\\([^><\n]+\\)>")
9870 (setq type "tree-match"
9871 path (match-string 1))
9872 (throw 'match t)))
9873 (unless path
9874 (error "No link found"))
9876 ;; switch back to reference buffer
9877 ;; needed when if called in a temporary buffer through
9878 ;; org-open-link-from-string
9879 (with-current-buffer (or reference-buffer (current-buffer))
9881 ;; Remove any trailing spaces in path
9882 (if (string-match " +\\'" path)
9883 (setq path (replace-match "" t t path)))
9884 (if (and org-link-translation-function
9885 (fboundp org-link-translation-function))
9886 ;; Check if we need to translate the link
9887 (let ((tmp (funcall org-link-translation-function type path)))
9888 (setq type (car tmp) path (cdr tmp))))
9890 (cond
9892 ((assoc type org-link-protocols)
9893 (funcall (nth 1 (assoc type org-link-protocols)) path))
9895 ((equal type "help")
9896 (let ((f-or-v (intern path)))
9897 (cond ((fboundp f-or-v)
9898 (describe-function f-or-v))
9899 ((boundp f-or-v)
9900 (describe-variable f-or-v))
9901 (t (error "Not a known function or variable")))))
9903 ((equal type "mailto")
9904 (let ((cmd (car org-link-mailto-program))
9905 (args (cdr org-link-mailto-program)) args1
9906 (address path) (subject "") a)
9907 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9908 (setq address (match-string 1 path)
9909 subject (org-link-escape (match-string 2 path))))
9910 (while args
9911 (cond
9912 ((not (stringp (car args))) (push (pop args) args1))
9913 (t (setq a (pop args))
9914 (if (string-match "%a" a)
9915 (setq a (replace-match address t t a)))
9916 (if (string-match "%s" a)
9917 (setq a (replace-match subject t t a)))
9918 (push a args1))))
9919 (apply cmd (nreverse args1))))
9921 ((member type '("http" "https" "ftp" "news"))
9922 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9923 (org-link-escape
9924 path org-link-escape-chars-browser)
9925 path))))
9927 ((string= type "doi")
9928 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9929 (org-link-escape
9930 path org-link-escape-chars-browser)
9931 path))))
9933 ((member type '("message"))
9934 (browse-url (concat type ":" path)))
9936 ((string= type "tags")
9937 (org-tags-view arg path))
9939 ((string= type "tree-match")
9940 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9942 ((string= type "file")
9943 (if (string-match "::\\([0-9]+\\)\\'" path)
9944 (setq line (string-to-number (match-string 1 path))
9945 path (substring path 0 (match-beginning 0)))
9946 (if (string-match "::\\(.+\\)\\'" path)
9947 (setq search (match-string 1 path)
9948 path (substring path 0 (match-beginning 0)))))
9949 (if (string-match "[*?{]" (file-name-nondirectory path))
9950 (dired path)
9951 (org-open-file path arg line search)))
9953 ((string= type "shell")
9954 (let ((buf (generate-new-buffer "*Org Shell Output"))
9955 (cmd path))
9956 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9957 (string-match org-confirm-shell-link-not-regexp cmd))
9958 (not org-confirm-shell-link-function)
9959 (funcall org-confirm-shell-link-function
9960 (format "Execute \"%s\" in shell? "
9961 (org-add-props cmd nil
9962 'face 'org-warning))))
9963 (progn
9964 (message "Executing %s" cmd)
9965 (shell-command cmd buf)
9966 (if (featurep 'midnight)
9967 (setq clean-buffer-list-kill-buffer-names
9968 (cons buf clean-buffer-list-kill-buffer-names))))
9969 (error "Abort"))))
9971 ((string= type "elisp")
9972 (let ((cmd path))
9973 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9974 (string-match org-confirm-elisp-link-not-regexp cmd))
9975 (not org-confirm-elisp-link-function)
9976 (funcall org-confirm-elisp-link-function
9977 (format "Execute \"%s\" as elisp? "
9978 (org-add-props cmd nil
9979 'face 'org-warning))))
9980 (message "%s => %s" cmd
9981 (if (equal (string-to-char cmd) ?\()
9982 (eval (read cmd))
9983 (call-interactively (read cmd))))
9984 (error "Abort"))))
9986 ((and (string= type "thisfile")
9987 (run-hook-with-args-until-success
9988 'org-open-link-functions path)))
9990 ((string= type "thisfile")
9991 (if arg
9992 (switch-to-buffer-other-window
9993 (org-get-buffer-for-internal-link (current-buffer)))
9994 (org-mark-ring-push))
9995 (let ((cmd `(org-link-search
9996 ,path
9997 ,(cond ((equal arg '(4)) ''occur)
9998 ((equal arg '(16)) ''org-occur))
9999 ,pos)))
10000 (condition-case nil (let ((org-link-search-inhibit-query t))
10001 (eval cmd))
10002 (error (progn (widen) (eval cmd))))))
10004 (t (browse-url-at-point)))))))
10005 (move-marker org-open-link-marker nil)
10006 (run-hook-with-args 'org-follow-link-hook)))
10008 (defun org-offer-links-in-entry (&optional nth zero)
10009 "Offer links in the current entry and follow the selected link.
10010 If there is only one link, follow it immediately as well.
10011 If NTH is an integer, immediately pick the NTH link found.
10012 If ZERO is a string, check also this string for a link, and if
10013 there is one, offer it as link number zero."
10014 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10015 "\\(" org-angle-link-re "\\)\\|"
10016 "\\(" org-plain-link-re "\\)"))
10017 (cnt ?0)
10018 (in-emacs (if (integerp nth) nil nth))
10019 have-zero end links link c)
10020 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10021 (push (match-string 0 zero) links)
10022 (setq cnt (1- cnt) have-zero t))
10023 (save-excursion
10024 (org-back-to-heading t)
10025 (setq end (save-excursion (outline-next-heading) (point)))
10026 (while (re-search-forward re end t)
10027 (push (match-string 0) links))
10028 (setq links (org-uniquify (reverse links))))
10030 (cond
10031 ((null links)
10032 (message "No links"))
10033 ((equal (length links) 1)
10034 (setq link (list (car links))))
10035 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10036 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10037 (t ; we have to select a link
10038 (save-excursion
10039 (save-window-excursion
10040 (delete-other-windows)
10041 (with-output-to-temp-buffer "*Select Link*"
10042 (mapc (lambda (l)
10043 (if (not (string-match org-bracket-link-regexp l))
10044 (princ (format "[%c] %s\n" (incf cnt)
10045 (org-remove-angle-brackets l)))
10046 (if (match-end 3)
10047 (princ (format "[%c] %s (%s)\n" (incf cnt)
10048 (match-string 3 l) (match-string 1 l)))
10049 (princ (format "[%c] %s\n" (incf cnt)
10050 (match-string 1 l))))))
10051 links))
10052 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10053 (message "Select link to open, RET to open all:")
10054 (setq c (read-char-exclusive))
10055 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10056 (when (equal c ?q) (error "Abort"))
10057 (if (equal c ?\C-m)
10058 (setq link links)
10059 (setq nth (- c ?0))
10060 (if have-zero (setq nth (1+ nth)))
10061 (unless (and (integerp nth) (>= (length links) nth))
10062 (error "Invalid link selection"))
10063 (setq link (list (nth (1- nth) links))))))
10064 (if link
10065 (let ((buf (current-buffer)))
10066 (dolist (l link)
10067 (org-open-link-from-string l in-emacs buf))
10069 nil)))
10071 ;; Add special file links that specify the way of opening
10073 (org-add-link-type "file+sys" 'org-open-file-with-system)
10074 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10075 (defun org-open-file-with-system (path)
10076 "Open file at PATH using the system way of opening it."
10077 (org-open-file path 'system))
10078 (defun org-open-file-with-emacs (path)
10079 "Open file at PATH in Emacs."
10080 (org-open-file path 'emacs))
10081 (defun org-remove-file-link-modifiers ()
10082 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10083 (goto-char (point-min))
10084 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10085 (org-if-unprotected
10086 (replace-match "file:" t t))))
10087 (eval-after-load "org-exp"
10088 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10089 'org-remove-file-link-modifiers))
10091 ;;;; Time estimates
10093 (defun org-get-effort (&optional pom)
10094 "Get the effort estimate for the current entry."
10095 (org-entry-get pom org-effort-property))
10097 ;;; File search
10099 (defvar org-create-file-search-functions nil
10100 "List of functions to construct the right search string for a file link.
10101 These functions are called in turn with point at the location to
10102 which the link should point.
10104 A function in the hook should first test if it would like to
10105 handle this file type, for example by checking the `major-mode'
10106 or the file extension. If it decides not to handle this file, it
10107 should just return nil to give other functions a chance. If it
10108 does handle the file, it must return the search string to be used
10109 when following the link. The search string will be part of the
10110 file link, given after a double colon, and `org-open-at-point'
10111 will automatically search for it. If special measures must be
10112 taken to make the search successful, another function should be
10113 added to the companion hook `org-execute-file-search-functions',
10114 which see.
10116 A function in this hook may also use `setq' to set the variable
10117 `description' to provide a suggestion for the descriptive text to
10118 be used for this link when it gets inserted into an Org-mode
10119 buffer with \\[org-insert-link].")
10121 (defvar org-execute-file-search-functions nil
10122 "List of functions to execute a file search triggered by a link.
10124 Functions added to this hook must accept a single argument, the
10125 search string that was part of the file link, the part after the
10126 double colon. The function must first check if it would like to
10127 handle this search, for example by checking the `major-mode' or
10128 the file extension. If it decides not to handle this search, it
10129 should just return nil to give other functions a chance. If it
10130 does handle the search, it must return a non-nil value to keep
10131 other functions from trying.
10133 Each function can access the current prefix argument through the
10134 variable `current-prefix-argument'. Note that a single prefix is
10135 used to force opening a link in Emacs, so it may be good to only
10136 use a numeric or double prefix to guide the search function.
10138 In case this is needed, a function in this hook can also restore
10139 the window configuration before `org-open-at-point' was called using:
10141 (set-window-configuration org-window-config-before-follow-link)")
10143 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10144 (defun org-link-search (s &optional type avoid-pos stealth)
10145 "Search for a link search option.
10146 If S is surrounded by forward slashes, it is interpreted as a
10147 regular expression. In org-mode files, this will create an `org-occur'
10148 sparse tree. In ordinary files, `occur' will be used to list matches.
10149 If the current buffer is in `dired-mode', grep will be used to search
10150 in all files. If AVOID-POS is given, ignore matches near that position.
10152 When optional argument STEALTH is non-nil, do not modify
10153 visibility around point, thus ignoring
10154 `org-show-hierarchy-above', `org-show-following-heading' and
10155 `org-show-siblings' variables."
10156 (let ((case-fold-search t)
10157 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10158 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10159 (append '(("") (" ") ("\t") ("\n"))
10160 org-emphasis-alist)
10161 "\\|") "\\)"))
10162 (pos (point))
10163 (pre nil) (post nil)
10164 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10165 (cond
10166 ;; First check if there are any special search functions
10167 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10168 ;; Now try the builtin stuff
10169 ((and (equal (string-to-char s0) ?#)
10170 (> (length s0) 1)
10171 (save-excursion
10172 (goto-char (point-min))
10173 (and
10174 (re-search-forward
10175 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10176 (setq type 'dedicated
10177 pos (match-beginning 0))))
10178 ;; There is an exact target for this
10179 (goto-char pos)
10180 (org-back-to-heading t)))
10181 ((save-excursion
10182 (goto-char (point-min))
10183 (and
10184 (re-search-forward
10185 (concat "<<" (regexp-quote s0) ">>") nil t)
10186 (setq type 'dedicated
10187 pos (match-beginning 0))))
10188 ;; There is an exact target for this
10189 (goto-char pos))
10190 ((save-excursion
10191 (goto-char (point-min))
10192 (and
10193 (re-search-forward
10194 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10195 (setq type 'dedicated pos (match-beginning 0))))
10196 ;; Found an invisible target.
10197 (goto-char pos))
10198 ((save-excursion
10199 (goto-char (point-min))
10200 (and
10201 (re-search-forward
10202 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10203 (setq type 'dedicated pos (match-beginning 0))))
10204 ;; Found an element with a matching #+name affiliated keyword.
10205 (goto-char pos))
10206 ((and (string-match "^(\\(.*\\))$" s0)
10207 (save-excursion
10208 (goto-char (point-min))
10209 (and
10210 (re-search-forward
10211 (concat "[^[]" (regexp-quote
10212 (format org-coderef-label-format
10213 (match-string 1 s0))))
10214 nil t)
10215 (setq type 'dedicated
10216 pos (1+ (match-beginning 0))))))
10217 ;; There is a coderef target for this
10218 (goto-char pos))
10219 ((string-match "^/\\(.*\\)/$" s)
10220 ;; A regular expression
10221 (cond
10222 ((derived-mode-p 'org-mode)
10223 (org-occur (match-string 1 s)))
10224 ;;((eq major-mode 'dired-mode)
10225 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10226 (t (org-do-occur (match-string 1 s)))))
10227 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10228 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10229 (goto-char (point-min))
10230 (cond
10231 ((let (case-fold-search)
10232 (re-search-forward (format org-complex-heading-regexp-format
10233 (regexp-quote s))
10234 nil t))
10235 ;; OK, found a match
10236 (setq type 'dedicated)
10237 (goto-char (match-beginning 0)))
10238 ((and (not org-link-search-inhibit-query)
10239 (eq org-link-search-must-match-exact-headline 'query-to-create)
10240 (y-or-n-p "No match - create this as a new heading? "))
10241 (goto-char (point-max))
10242 (or (bolp) (newline))
10243 (insert "* " s "\n")
10244 (beginning-of-line 0))
10246 (goto-char pos)
10247 (error "No match"))))
10249 ;; A normal search string
10250 (when (equal (string-to-char s) ?*)
10251 ;; Anchor on headlines, post may include tags.
10252 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10253 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10254 s (substring s 1)))
10255 (remove-text-properties
10256 0 (length s)
10257 '(face nil mouse-face nil keymap nil fontified nil) s)
10258 ;; Make a series of regular expressions to find a match
10259 (setq words (org-split-string s "[ \n\r\t]+")
10261 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10262 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10263 "\\)" markers)
10264 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10265 re2a (concat "[ \t\r\n]" re2a_)
10266 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10267 re4 (concat "[^a-zA-Z_]" re4_)
10269 re1 (concat pre re2 post)
10270 re3 (concat pre (if pre re4_ re4) post)
10271 re5 (concat pre ".*" re4)
10272 re2 (concat pre re2)
10273 re2a (concat pre (if pre re2a_ re2a))
10274 re4 (concat pre (if pre re4_ re4))
10275 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10276 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10277 re5 "\\)"
10279 (cond
10280 ((eq type 'org-occur) (org-occur reall))
10281 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10282 (t (goto-char (point-min))
10283 (setq type 'fuzzy)
10284 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10285 (org-search-not-self 1 re1 nil t)
10286 (org-search-not-self 1 re2 nil t)
10287 (org-search-not-self 1 re2a nil t)
10288 (org-search-not-self 1 re3 nil t)
10289 (org-search-not-self 1 re4 nil t)
10290 (org-search-not-self 1 re5 nil t)
10292 (goto-char (match-beginning 1))
10293 (goto-char pos)
10294 (error "No match"))))))
10295 (and (derived-mode-p 'org-mode)
10296 (not stealth)
10297 (org-show-context 'link-search))
10298 type))
10300 (defun org-search-not-self (group &rest args)
10301 "Execute `re-search-forward', but only accept matches that do not
10302 enclose the position of `org-open-link-marker'."
10303 (let ((m org-open-link-marker))
10304 (catch 'exit
10305 (while (apply 're-search-forward args)
10306 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10307 (goto-char (match-end group))
10308 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10309 (> (match-beginning 0) (marker-position m))
10310 (< (match-end 0) (marker-position m)))
10311 (save-match-data
10312 (or (not (org-in-regexp
10313 org-bracket-link-analytic-regexp 1))
10314 (not (match-end 4)) ; no description
10315 (and (<= (match-beginning 4) (point))
10316 (>= (match-end 4) (point))))))
10317 (throw 'exit (point))))))))
10319 (defun org-get-buffer-for-internal-link (buffer)
10320 "Return a buffer to be used for displaying the link target of internal links."
10321 (cond
10322 ((not org-display-internal-link-with-indirect-buffer)
10323 buffer)
10324 ((string-match "(Clone)$" (buffer-name buffer))
10325 (message "Buffer is already a clone, not making another one")
10326 ;; we also do not modify visibility in this case
10327 buffer)
10328 (t ; make a new indirect buffer for displaying the link
10329 (let* ((bn (buffer-name buffer))
10330 (ibn (concat bn "(Clone)"))
10331 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10332 (with-current-buffer ib (org-overview))
10333 ib))))
10335 (defun org-do-occur (regexp &optional cleanup)
10336 "Call the Emacs command `occur'.
10337 If CLEANUP is non-nil, remove the printout of the regular expression
10338 in the *Occur* buffer. This is useful if the regex is long and not useful
10339 to read."
10340 (occur regexp)
10341 (when cleanup
10342 (let ((cwin (selected-window)) win beg end)
10343 (when (setq win (get-buffer-window "*Occur*"))
10344 (select-window win))
10345 (goto-char (point-min))
10346 (when (re-search-forward "match[a-z]+" nil t)
10347 (setq beg (match-end 0))
10348 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10349 (setq end (1- (match-beginning 0)))))
10350 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10351 (goto-char (point-min))
10352 (select-window cwin))))
10354 ;;; The mark ring for links jumps
10356 (defvar org-mark-ring nil
10357 "Mark ring for positions before jumps in Org-mode.")
10358 (defvar org-mark-ring-last-goto nil
10359 "Last position in the mark ring used to go back.")
10360 ;; Fill and close the ring
10361 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10362 (loop for i from 1 to org-mark-ring-length do
10363 (push (make-marker) org-mark-ring))
10364 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10365 org-mark-ring)
10367 (defun org-mark-ring-push (&optional pos buffer)
10368 "Put the current position or POS into the mark ring and rotate it."
10369 (interactive)
10370 (setq pos (or pos (point)))
10371 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10372 (move-marker (car org-mark-ring)
10373 (or pos (point))
10374 (or buffer (current-buffer)))
10375 (message "%s"
10376 (substitute-command-keys
10377 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10379 (defun org-mark-ring-goto (&optional n)
10380 "Jump to the previous position in the mark ring.
10381 With prefix arg N, jump back that many stored positions. When
10382 called several times in succession, walk through the entire ring.
10383 Org-mode commands jumping to a different position in the current file,
10384 or to another Org-mode file, automatically push the old position
10385 onto the ring."
10386 (interactive "p")
10387 (let (p m)
10388 (if (eq last-command this-command)
10389 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10390 (setq p org-mark-ring))
10391 (setq org-mark-ring-last-goto p)
10392 (setq m (car p))
10393 (org-pop-to-buffer-same-window (marker-buffer m))
10394 (goto-char m)
10395 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10397 (defun org-remove-angle-brackets (s)
10398 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10399 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10401 (defun org-add-angle-brackets (s)
10402 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10403 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10405 (defun org-remove-double-quotes (s)
10406 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10407 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10410 ;;; Following specific links
10412 (defun org-follow-timestamp-link ()
10413 (cond
10414 ((org-at-date-range-p t)
10415 (let ((org-agenda-start-on-weekday)
10416 (t1 (match-string 1))
10417 (t2 (match-string 2)))
10418 (setq t1 (time-to-days (org-time-string-to-time t1))
10419 t2 (time-to-days (org-time-string-to-time t2)))
10420 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10421 ((org-at-timestamp-p t)
10422 (org-agenda-list nil (time-to-days (org-time-string-to-time
10423 (substring (match-string 1) 0 10)))
10425 (t (error "This should not happen"))))
10428 ;;; Following file links
10429 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10430 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10431 (declare-function mailcap-mime-info
10432 "mailcap" (string &optional request no-decode))
10433 (defvar org-wait nil)
10434 (defun org-open-file (path &optional in-emacs line search)
10435 "Open the file at PATH.
10436 First, this expands any special file name abbreviations. Then the
10437 configuration variable `org-file-apps' is checked if it contains an
10438 entry for this file type, and if yes, the corresponding command is launched.
10440 If no application is found, Emacs simply visits the file.
10442 With optional prefix argument IN-EMACS, Emacs will visit the file.
10443 With a double \\[universal-argument] \\[universal-argument] \
10444 prefix arg, Org tries to avoid opening in Emacs
10445 and to use an external application to visit the file.
10447 Optional LINE specifies a line to go to, optional SEARCH a string
10448 to search for. If LINE or SEARCH is given, the file will be
10449 opened in Emacs, unless an entry from org-file-apps that makes
10450 use of groups in a regexp matches.
10452 If you want to change the way frames are used when following a
10453 link, please customize `org-link-frame-setup'.
10455 If the file does not exist, an error is thrown."
10456 (let* ((file (if (equal path "")
10457 buffer-file-name
10458 (substitute-in-file-name (expand-file-name path))))
10459 (file-apps (append org-file-apps (org-default-apps)))
10460 (apps (org-remove-if
10461 'org-file-apps-entry-match-against-dlink-p file-apps))
10462 (apps-dlink (org-remove-if-not
10463 'org-file-apps-entry-match-against-dlink-p file-apps))
10464 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10465 (dirp (if remp nil (file-directory-p file)))
10466 (file (if (and dirp org-open-directory-means-index-dot-org)
10467 (concat (file-name-as-directory file) "index.org")
10468 file))
10469 (a-m-a-p (assq 'auto-mode apps))
10470 (dfile (downcase file))
10471 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10472 (link (cond ((and (eq line nil)
10473 (eq search nil))
10474 file)
10475 (line
10476 (concat file "::" (number-to-string line)))
10477 (search
10478 (concat file "::" search))))
10479 (dlink (downcase link))
10480 (old-buffer (current-buffer))
10481 (old-pos (point))
10482 (old-mode major-mode)
10483 ext cmd link-match-data)
10484 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10485 (setq ext (match-string 1 dfile))
10486 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10487 (setq ext (match-string 1 dfile))))
10488 (cond
10489 ((member in-emacs '((16) system))
10490 (setq cmd (cdr (assoc 'system apps))))
10491 (in-emacs (setq cmd 'emacs))
10493 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10494 (and dirp (cdr (assoc 'directory apps)))
10495 ; first, try matching against apps-dlink
10496 ; if we get a match here, store the match data for later
10497 (let ((match (assoc-default dlink apps-dlink
10498 'string-match)))
10499 (if match
10500 (progn (setq link-match-data (match-data))
10501 match)
10502 (progn (setq in-emacs (or in-emacs line search))
10503 nil))) ; if we have no match in apps-dlink,
10504 ; always open the file in emacs if line or search
10505 ; is given (for backwards compatibility)
10506 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10507 'string-match)
10508 (cdr (assoc ext apps))
10509 (cdr (assoc t apps))))))
10510 (when (eq cmd 'system)
10511 (setq cmd (cdr (assoc 'system apps))))
10512 (when (eq cmd 'default)
10513 (setq cmd (cdr (assoc t apps))))
10514 (when (eq cmd 'mailcap)
10515 (require 'mailcap)
10516 (mailcap-parse-mailcaps)
10517 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10518 (command (mailcap-mime-info mime-type)))
10519 (if (stringp command)
10520 (setq cmd command)
10521 (setq cmd 'emacs))))
10522 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10523 (not (file-exists-p file))
10524 (not org-open-non-existing-files))
10525 (error "No such file: %s" file))
10526 (cond
10527 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10528 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10529 (while (string-match "['\"]%s['\"]" cmd)
10530 (setq cmd (replace-match "%s" t t cmd)))
10531 (while (string-match "%s" cmd)
10532 (setq cmd (replace-match
10533 (save-match-data
10534 (shell-quote-argument
10535 (convert-standard-filename file)))
10536 t t cmd)))
10538 ;; Replace "%1", "%2" etc. in command with group matches from regex
10539 (save-match-data
10540 (let ((match-index 1)
10541 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10542 (set-match-data link-match-data)
10543 (while (<= match-index number-of-groups)
10544 (let ((regex (concat "%" (number-to-string match-index)))
10545 (replace-with (match-string match-index dlink)))
10546 (while (string-match regex cmd)
10547 (setq cmd (replace-match replace-with t t cmd))))
10548 (setq match-index (+ match-index 1)))))
10550 (save-window-excursion
10551 (start-process-shell-command cmd nil cmd)
10552 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10554 ((or (stringp cmd)
10555 (eq cmd 'emacs))
10556 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10557 (widen)
10558 (if line (org-goto-line line)
10559 (if search (org-link-search search))))
10560 ((consp cmd)
10561 (let ((file (convert-standard-filename file)))
10562 (save-match-data
10563 (set-match-data link-match-data)
10564 (eval cmd))))
10565 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10566 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10567 (or (not (equal old-buffer (current-buffer)))
10568 (not (equal old-pos (point))))
10569 (org-mark-ring-push old-pos old-buffer))))
10571 (defun org-file-apps-entry-match-against-dlink-p (entry)
10572 "This function returns non-nil if `entry' uses a regular
10573 expression which should be matched against the whole link by
10574 org-open-file.
10576 It assumes that is the case when the entry uses a regular
10577 expression which has at least one grouping construct and the
10578 action is either a lisp form or a command string containing
10579 '%1', i.e. using at least one subexpression match as a
10580 parameter."
10581 (let ((selector (car entry))
10582 (action (cdr entry)))
10583 (if (stringp selector)
10584 (and (> (regexp-opt-depth selector) 0)
10585 (or (and (stringp action)
10586 (string-match "%[0-9]" action))
10587 (consp action)))
10588 nil)))
10590 (defun org-default-apps ()
10591 "Return the default applications for this operating system."
10592 (cond
10593 ((eq system-type 'darwin)
10594 org-file-apps-defaults-macosx)
10595 ((eq system-type 'windows-nt)
10596 org-file-apps-defaults-windowsnt)
10597 (t org-file-apps-defaults-gnu)))
10599 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10600 "Convert extensions to regular expressions in the cars of LIST.
10601 Also, weed out any non-string entries, because the return value is used
10602 only for regexp matching.
10603 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10604 point to the symbol `emacs', indicating that the file should
10605 be opened in Emacs."
10606 (append
10607 (delq nil
10608 (mapcar (lambda (x)
10609 (if (not (stringp (car x)))
10611 (if (string-match "\\W" (car x))
10613 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10614 list))
10615 (if add-auto-mode
10616 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10618 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10619 (defun org-file-remote-p (file)
10620 "Test whether FILE specifies a location on a remote system.
10621 Return non-nil if the location is indeed remote.
10623 For example, the filename \"/user@host:/foo\" specifies a location
10624 on the system \"/user@host:\"."
10625 (cond ((fboundp 'file-remote-p)
10626 (file-remote-p file))
10627 ((fboundp 'tramp-handle-file-remote-p)
10628 (tramp-handle-file-remote-p file))
10629 ((and (boundp 'ange-ftp-name-format)
10630 (string-match (car ange-ftp-name-format) file))
10631 t)))
10634 ;;;; Refiling
10636 (defun org-get-org-file ()
10637 "Read a filename, with default directory `org-directory'."
10638 (let ((default (or org-default-notes-file remember-data-file)))
10639 (read-file-name (format "File name [%s]: " default)
10640 (file-name-as-directory org-directory)
10641 default)))
10643 (defun org-notes-order-reversed-p ()
10644 "Check if the current file should receive notes in reversed order."
10645 (cond
10646 ((not org-reverse-note-order) nil)
10647 ((eq t org-reverse-note-order) t)
10648 ((not (listp org-reverse-note-order)) nil)
10649 (t (catch 'exit
10650 (let ((all org-reverse-note-order)
10651 entry)
10652 (while (setq entry (pop all))
10653 (if (string-match (car entry) buffer-file-name)
10654 (throw 'exit (cdr entry))))
10655 nil)))))
10657 (defvar org-refile-target-table nil
10658 "The list of refile targets, created by `org-refile'.")
10660 (defvar org-agenda-new-buffers nil
10661 "Buffers created to visit agenda files.")
10663 (defvar org-refile-cache nil
10664 "Cache for refile targets.")
10666 (defvar org-refile-markers nil
10667 "All the markers used for caching refile locations.")
10669 (defun org-refile-marker (pos)
10670 "Get a new refile marker, but only if caching is in use."
10671 (if (not org-refile-use-cache)
10673 (let ((m (make-marker)))
10674 (move-marker m pos)
10675 (push m org-refile-markers)
10676 m)))
10678 (defun org-refile-cache-clear ()
10679 "Clear the refile cache and disable all the markers."
10680 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10681 (setq org-refile-markers nil)
10682 (setq org-refile-cache nil)
10683 (message "Refile cache has been cleared"))
10685 (defun org-refile-cache-check-set (set)
10686 "Check if all the markers in the cache still have live buffers."
10687 (let (marker)
10688 (catch 'exit
10689 (while (and set (setq marker (nth 3 (pop set))))
10690 ;; if org-refile-use-outline-path is 'file, marker may be nil
10691 (when (and marker (null (marker-buffer marker)))
10692 (message "not found") (sit-for 3)
10693 (throw 'exit nil)))
10694 t)))
10696 (defun org-refile-cache-put (set &rest identifiers)
10697 "Push the refile targets SET into the cache, under IDENTIFIERS."
10698 (let* ((key (sha1 (prin1-to-string identifiers)))
10699 (entry (assoc key org-refile-cache)))
10700 (if entry
10701 (setcdr entry set)
10702 (push (cons key set) org-refile-cache))))
10704 (defun org-refile-cache-get (&rest identifiers)
10705 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10706 (cond
10707 ((not org-refile-cache) nil)
10708 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10710 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10711 org-refile-cache))))
10712 (and set (org-refile-cache-check-set set) set)))))
10714 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10715 "Produce a table with refile targets."
10716 (let ((case-fold-search nil)
10717 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10718 (entries (or org-refile-targets '((nil . (:level . 1)))))
10719 targets tgs txt re files f desc descre fast-path-p level pos0)
10720 (message "Getting targets...")
10721 (with-current-buffer (or default-buffer (current-buffer))
10722 (while (setq entry (pop entries))
10723 (setq files (car entry) desc (cdr entry))
10724 (setq fast-path-p nil)
10725 (cond
10726 ((null files) (setq files (list (current-buffer))))
10727 ((eq files 'org-agenda-files)
10728 (setq files (org-agenda-files 'unrestricted)))
10729 ((and (symbolp files) (fboundp files))
10730 (setq files (funcall files)))
10731 ((and (symbolp files) (boundp files))
10732 (setq files (symbol-value files))))
10733 (if (stringp files) (setq files (list files)))
10734 (cond
10735 ((eq (car desc) :tag)
10736 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10737 ((eq (car desc) :todo)
10738 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10739 ((eq (car desc) :regexp)
10740 (setq descre (cdr desc)))
10741 ((eq (car desc) :level)
10742 (setq descre (concat "^\\*\\{" (number-to-string
10743 (if org-odd-levels-only
10744 (1- (* 2 (cdr desc)))
10745 (cdr desc)))
10746 "\\}[ \t]")))
10747 ((eq (car desc) :maxlevel)
10748 (setq fast-path-p t)
10749 (setq descre (concat "^\\*\\{1," (number-to-string
10750 (if org-odd-levels-only
10751 (1- (* 2 (cdr desc)))
10752 (cdr desc)))
10753 "\\}[ \t]")))
10754 (t (error "Bad refiling target description %s" desc)))
10755 (while (setq f (pop files))
10756 (with-current-buffer
10757 (if (bufferp f) f (org-get-agenda-file-buffer f))
10759 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10760 (progn
10761 (if (bufferp f) (setq f (buffer-file-name
10762 (buffer-base-buffer f))))
10763 (setq f (and f (expand-file-name f)))
10764 (if (eq org-refile-use-outline-path 'file)
10765 (push (list (file-name-nondirectory f) f nil nil) tgs))
10766 (save-excursion
10767 (save-restriction
10768 (widen)
10769 (goto-char (point-min))
10770 (while (re-search-forward descre nil t)
10771 (goto-char (setq pos0 (point-at-bol)))
10772 (catch 'next
10773 (when org-refile-target-verify-function
10774 (save-match-data
10775 (or (funcall org-refile-target-verify-function)
10776 (throw 'next t))))
10777 (when (and (looking-at org-complex-heading-regexp)
10778 (not (member (match-string 4) excluded-entries))
10779 (match-string 4))
10780 (setq level (org-reduced-level
10781 (- (match-end 1) (match-beginning 1)))
10782 txt (org-link-display-format (match-string 4))
10783 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10784 re (format org-complex-heading-regexp-format
10785 (regexp-quote (match-string 4))))
10786 (when org-refile-use-outline-path
10787 (setq txt (mapconcat
10788 'org-protect-slash
10789 (append
10790 (if (eq org-refile-use-outline-path
10791 'file)
10792 (list (file-name-nondirectory
10793 (buffer-file-name
10794 (buffer-base-buffer))))
10795 (if (eq org-refile-use-outline-path
10796 'full-file-path)
10797 (list (buffer-file-name
10798 (buffer-base-buffer)))))
10799 (org-get-outline-path fast-path-p
10800 level txt)
10801 (list txt))
10802 "/")))
10803 (push (list txt f re (org-refile-marker (point)))
10804 tgs)))
10805 (when (= (point) pos0)
10806 ;; verification function has not moved point
10807 (goto-char (point-at-eol))))))))
10808 (when org-refile-use-cache
10809 (org-refile-cache-put tgs (buffer-file-name) descre))
10810 (setq targets (append tgs targets))
10811 ))))
10812 (message "Getting targets...done")
10813 (nreverse targets)))
10815 (defun org-protect-slash (s)
10816 (while (string-match "/" s)
10817 (setq s (replace-match "\\" t t s)))
10820 (defvar org-olpa (make-vector 20 nil))
10822 (defun org-get-outline-path (&optional fastp level heading)
10823 "Return the outline path to the current entry, as a list.
10825 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10826 routine which makes outline path derivations for an entire file,
10827 avoiding backtracing. Refile target collection makes use of that."
10828 (if fastp
10829 (progn
10830 (if (> level 19)
10831 (error "Outline path failure, more than 19 levels"))
10832 (loop for i from level upto 19 do
10833 (aset org-olpa i nil))
10834 (prog1
10835 (delq nil (append org-olpa nil))
10836 (aset org-olpa level heading)))
10837 (let (rtn case-fold-search)
10838 (save-excursion
10839 (save-restriction
10840 (widen)
10841 (while (org-up-heading-safe)
10842 (when (looking-at org-complex-heading-regexp)
10843 (push (org-match-string-no-properties 4) rtn)))
10844 rtn)))))
10846 (defun org-format-outline-path (path &optional width prefix)
10847 "Format the outline path PATH for display.
10848 Width is the maximum number of characters that is available.
10849 Prefix is a prefix to be included in the returned string,
10850 such as the file name."
10851 (setq width (or width 79))
10852 (if prefix (setq width (- width (length prefix))))
10853 (if (not path)
10854 (or prefix "")
10855 (let* ((nsteps (length path))
10856 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10857 (maxwidth (if (<= total-width width)
10858 10000 ;; everything fits
10859 ;; we need to shorten the level headings
10860 (/ (- width nsteps) nsteps)))
10861 (org-odd-levels-only nil)
10862 (n 0)
10863 (total (1+ (length prefix))))
10864 (setq maxwidth (max maxwidth 10))
10865 (concat prefix
10866 (mapconcat
10867 (lambda (h)
10868 (setq n (1+ n))
10869 (if (and (= n nsteps) (< maxwidth 10000))
10870 (setq maxwidth (- total-width total)))
10871 (if (< (length h) maxwidth)
10872 (progn (setq total (+ total (length h) 1)) h)
10873 (setq h (substring h 0 (- maxwidth 2))
10874 total (+ total maxwidth 1))
10875 (if (string-match "[ \t]+\\'" h)
10876 (setq h (substring h 0 (match-beginning 0))))
10877 (setq h (concat h "..")))
10878 (org-add-props h nil 'face
10879 (nth (% (1- n) org-n-level-faces)
10880 org-level-faces))
10882 path "/")))))
10884 (defun org-display-outline-path (&optional file current)
10885 "Display the current outline path in the echo area."
10886 (interactive "P")
10887 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10888 (case-fold-search nil)
10889 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10890 (if current (setq path (append path
10891 (save-excursion
10892 (org-back-to-heading t)
10893 (if (looking-at org-complex-heading-regexp)
10894 (list (match-string 4)))))))
10895 (message "%s"
10896 (org-format-outline-path
10897 path
10898 (1- (frame-width))
10899 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10901 (defvar org-refile-history nil
10902 "History for refiling operations.")
10904 (defvar org-after-refile-insert-hook nil
10905 "Hook run after `org-refile' has inserted its stuff at the new location.
10906 Note that this is still *before* the stuff will be removed from
10907 the *old* location.")
10909 (defvar org-capture-last-stored-marker)
10910 (defun org-refile (&optional goto default-buffer rfloc)
10911 "Move the entry or entries at point to another heading.
10912 The list of target headings is compiled using the information in
10913 `org-refile-targets', which see.
10915 At the target location, the entry is filed as a subitem of the target
10916 heading. Depending on `org-reverse-note-order', the new subitem will
10917 either be the first or the last subitem.
10919 If there is an active region, all entries in that region will be moved.
10920 However, the region must fulfill the requirement that the first heading
10921 is the first one sets the top-level of the moved text - at most siblings
10922 below it are allowed.
10924 With prefix arg GOTO, the command will only visit the target location
10925 and not actually move anything.
10927 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10928 go to the location where the last refiling operation has put the subtree.
10929 With a prefix argument of `2', refile to the running clock.
10931 RFLOC can be a refile location obtained in a different way.
10933 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10935 If you are using target caching (see `org-refile-use-cache'),
10936 you have to clear the target cache in order to find new targets.
10937 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10938 prefix argument (`C-u C-u C-u C-c C-w')."
10940 (interactive "P")
10941 (if (member goto '(0 (64)))
10942 (org-refile-cache-clear)
10943 (let* ((cbuf (current-buffer))
10944 (regionp (org-region-active-p))
10945 (region-start (and regionp (region-beginning)))
10946 (region-end (and regionp (region-end)))
10947 (region-length (and regionp (- region-end region-start)))
10948 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10949 pos it nbuf file re level reversed)
10950 (setq last-command nil)
10951 (when regionp
10952 (goto-char region-start)
10953 (or (bolp) (goto-char (point-at-bol)))
10954 (setq region-start (point))
10955 (unless (or (org-kill-is-subtree-p
10956 (buffer-substring region-start region-end))
10957 (prog1 org-refile-active-region-within-subtree
10958 (org-toggle-heading)))
10959 (error "The region is not a (sequence of) subtree(s)")))
10960 (if (equal goto '(16))
10961 (org-refile-goto-last-stored)
10962 (when (or
10963 (and (equal goto 2)
10964 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10965 (prog1
10966 (setq it (list (or org-clock-heading "running clock")
10967 (buffer-file-name
10968 (marker-buffer org-clock-hd-marker))
10970 (marker-position org-clock-hd-marker)))
10971 (setq goto nil)))
10972 (setq it (or rfloc
10973 (let (heading-text)
10974 (save-excursion
10975 (unless goto
10976 (org-back-to-heading t)
10977 (setq heading-text
10978 (nth 4 (org-heading-components))))
10979 (org-refile-get-location
10980 (cond (goto "Goto")
10981 (regionp "Refile region to")
10982 (t (concat "Refile subtree \""
10983 heading-text "\" to")))
10984 default-buffer
10985 (and (not (equal '(4) goto))
10986 org-refile-allow-creating-parent-nodes)
10987 goto))))))
10988 (setq file (nth 1 it)
10989 re (nth 2 it)
10990 pos (nth 3 it))
10991 (if (and (not goto)
10993 (equal (buffer-file-name) file)
10994 (if regionp
10995 (and (>= pos region-start)
10996 (<= pos region-end))
10997 (and (>= pos (point))
10998 (< pos (save-excursion
10999 (org-end-of-subtree t t))))))
11000 (error "Cannot refile to position inside the tree or region"))
11002 (setq nbuf (or (find-buffer-visiting file)
11003 (find-file-noselect file)))
11004 (if goto
11005 (progn
11006 (org-pop-to-buffer-same-window nbuf)
11007 (goto-char pos)
11008 (org-show-context 'org-goto))
11009 (if regionp
11010 (progn
11011 (org-kill-new (buffer-substring region-start region-end))
11012 (org-save-markers-in-region region-start region-end))
11013 (org-copy-subtree 1 nil t))
11014 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11015 (find-file-noselect file)))
11016 (setq reversed (org-notes-order-reversed-p))
11017 (save-excursion
11018 (save-restriction
11019 (widen)
11020 (if pos
11021 (progn
11022 (goto-char pos)
11023 (looking-at org-outline-regexp)
11024 (setq level (org-get-valid-level (funcall outline-level) 1))
11025 (goto-char
11026 (if reversed
11027 (or (outline-next-heading) (point-max))
11028 (or (save-excursion (org-get-next-sibling))
11029 (org-end-of-subtree t t)
11030 (point-max)))))
11031 (setq level 1)
11032 (if (not reversed)
11033 (goto-char (point-max))
11034 (goto-char (point-min))
11035 (or (outline-next-heading) (goto-char (point-max)))))
11036 (if (not (bolp)) (newline))
11037 (org-paste-subtree level)
11038 (when org-log-refile
11039 (org-add-log-setup 'refile nil nil 'findpos
11040 org-log-refile)
11041 (unless (eq org-log-refile 'note)
11042 (save-excursion (org-add-log-note))))
11043 (and org-auto-align-tags
11044 (let ((org-loop-over-headlines-in-active-region nil))
11045 (org-set-tags nil t)))
11046 (bookmark-set "org-refile-last-stored")
11047 ;; If we are refiling for capture, make sure that the
11048 ;; last-capture pointers point here
11049 (when (org-bound-and-true-p org-refile-for-capture)
11050 (bookmark-set "org-capture-last-stored-marker")
11051 (move-marker org-capture-last-stored-marker (point)))
11052 (if (fboundp 'deactivate-mark) (deactivate-mark))
11053 (run-hooks 'org-after-refile-insert-hook))))
11054 (if regionp
11055 (delete-region (point) (+ (point) region-length))
11056 (org-cut-subtree))
11057 (when (featurep 'org-inlinetask)
11058 (org-inlinetask-remove-END-maybe))
11059 (setq org-markers-to-move nil)
11060 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11062 (defun org-refile-goto-last-stored ()
11063 "Go to the location where the last refile was stored."
11064 (interactive)
11065 (bookmark-jump "org-refile-last-stored")
11066 (message "This is the location of the last refile"))
11068 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11069 no-exclude)
11070 "Prompt the user for a refile location, using PROMPT.
11071 PROMPT should not be suffixed with a colon and a space, because
11072 this function appends the default value from
11073 `org-refile-history' automatically, if that is not empty.
11074 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11075 this is used for the GOTO interface."
11076 (let ((org-refile-targets org-refile-targets)
11077 (org-refile-use-outline-path org-refile-use-outline-path)
11078 excluded-entries)
11079 (when (and (derived-mode-p 'org-mode)
11080 (not org-refile-use-cache)
11081 (not no-exclude))
11082 (org-map-tree
11083 (lambda()
11084 (setq excluded-entries
11085 (append excluded-entries (list (org-get-heading t t)))))))
11086 (setq org-refile-target-table
11087 (org-refile-get-targets default-buffer excluded-entries)))
11088 (unless org-refile-target-table
11089 (error "No refile targets"))
11090 (let* ((prompt (concat prompt
11091 (and (car org-refile-history)
11092 (concat " (default " (car org-refile-history) ")"))
11093 ": "))
11094 (cbuf (current-buffer))
11095 (partial-completion-mode nil)
11096 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11097 (cfunc (if (and org-refile-use-outline-path
11098 org-outline-path-complete-in-steps)
11099 'org-olpath-completing-read
11100 'org-icompleting-read))
11101 (extra (if org-refile-use-outline-path "/" ""))
11102 (filename (and cfn (expand-file-name cfn)))
11103 (tbl (mapcar
11104 (lambda (x)
11105 (if (and (not (member org-refile-use-outline-path
11106 '(file full-file-path)))
11107 (not (equal filename (nth 1 x))))
11108 (cons (concat (car x) extra " ("
11109 (file-name-nondirectory (nth 1 x)) ")")
11110 (cdr x))
11111 (cons (concat (car x) extra) (cdr x))))
11112 org-refile-target-table))
11113 (completion-ignore-case t)
11114 pa answ parent-target child parent old-hist)
11115 (setq old-hist org-refile-history)
11116 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11117 nil 'org-refile-history (car org-refile-history)))
11118 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11119 (org-refile-check-position pa)
11120 (if pa
11121 (progn
11122 (when (or (not org-refile-history)
11123 (not (eq old-hist org-refile-history))
11124 (not (equal (car pa) (car org-refile-history))))
11125 (setq org-refile-history
11126 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11127 org-refile-history
11128 (cdr org-refile-history))))
11129 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11130 (pop org-refile-history)))
11132 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11133 (progn
11134 (setq parent (match-string 1 answ)
11135 child (match-string 2 answ))
11136 (setq parent-target (or (assoc parent tbl)
11137 (assoc (concat parent "/") tbl)))
11138 (when (and parent-target
11139 (or (eq new-nodes t)
11140 (and (eq new-nodes 'confirm)
11141 (y-or-n-p (format "Create new node \"%s\"? "
11142 child)))))
11143 (org-refile-new-child parent-target child)))
11144 (error "Invalid target location")))))
11146 (declare-function org-string-nw-p "org-macs.el" (s))
11147 (defun org-refile-check-position (refile-pointer)
11148 "Check if the refile pointer matches the readline to which it points."
11149 (let* ((file (nth 1 refile-pointer))
11150 (re (nth 2 refile-pointer))
11151 (pos (nth 3 refile-pointer))
11152 buffer)
11153 (when (org-string-nw-p re)
11154 (setq buffer (if (markerp pos)
11155 (marker-buffer pos)
11156 (or (find-buffer-visiting file)
11157 (find-file-noselect file))))
11158 (with-current-buffer buffer
11159 (save-excursion
11160 (save-restriction
11161 (widen)
11162 (goto-char pos)
11163 (beginning-of-line 1)
11164 (unless (org-looking-at-p re)
11165 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11167 (defun org-refile-new-child (parent-target child)
11168 "Use refile target PARENT-TARGET to add new CHILD below it."
11169 (unless parent-target
11170 (error "Cannot find parent for new node"))
11171 (let ((file (nth 1 parent-target))
11172 (pos (nth 3 parent-target))
11173 level)
11174 (with-current-buffer (or (find-buffer-visiting file)
11175 (find-file-noselect file))
11176 (save-excursion
11177 (save-restriction
11178 (widen)
11179 (if pos
11180 (goto-char pos)
11181 (goto-char (point-max))
11182 (if (not (bolp)) (newline)))
11183 (when (looking-at org-outline-regexp)
11184 (setq level (funcall outline-level))
11185 (org-end-of-subtree t t))
11186 (org-back-over-empty-lines)
11187 (insert "\n" (make-string
11188 (if pos (org-get-valid-level level 1) 1) ?*)
11189 " " child "\n")
11190 (beginning-of-line 0)
11191 (list (concat (car parent-target) "/" child) file "" (point)))))))
11193 (defun org-olpath-completing-read (prompt collection &rest args)
11194 "Read an outline path like a file name."
11195 (let ((thetable collection)
11196 (org-completion-use-ido nil) ; does not work with ido.
11197 (org-completion-use-iswitchb nil)) ; or iswitchb
11198 (apply
11199 'org-icompleting-read prompt
11200 (lambda (string predicate &optional flag)
11201 (let (rtn r f (l (length string)))
11202 (cond
11203 ((eq flag nil)
11204 ;; try completion
11205 (try-completion string thetable))
11206 ((eq flag t)
11207 ;; all-completions
11208 (setq rtn (all-completions string thetable predicate))
11209 (mapcar
11210 (lambda (x)
11211 (setq r (substring x l))
11212 (if (string-match " ([^)]*)$" x)
11213 (setq f (match-string 0 x))
11214 (setq f ""))
11215 (if (string-match "/" r)
11216 (concat string (substring r 0 (match-end 0)) f)
11218 rtn))
11219 ((eq flag 'lambda)
11220 ;; exact match?
11221 (assoc string thetable)))))
11222 args)))
11224 ;;;; Dynamic blocks
11226 (defun org-find-dblock (name)
11227 "Find the first dynamic block with name NAME in the buffer.
11228 If not found, stay at current position and return nil."
11229 (let ((case-fold-search t) pos)
11230 (save-excursion
11231 (goto-char (point-min))
11232 (setq pos (and (re-search-forward
11233 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11234 (match-beginning 0))))
11235 (if pos (goto-char pos))
11236 pos))
11238 (defconst org-dblock-start-re
11239 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11240 "Matches the start line of a dynamic block, with parameters.")
11242 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11243 "Matches the end of a dynamic block.")
11245 (defun org-create-dblock (plist)
11246 "Create a dynamic block section, with parameters taken from PLIST.
11247 PLIST must contain a :name entry which is used as name of the block."
11248 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11249 (end-of-line 1)
11250 (newline))
11251 (let ((col (current-column))
11252 (name (plist-get plist :name)))
11253 (insert "#+BEGIN: " name)
11254 (while plist
11255 (if (eq (car plist) :name)
11256 (setq plist (cddr plist))
11257 (insert " " (prin1-to-string (pop plist)))))
11258 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11259 (beginning-of-line -2)))
11261 (defun org-prepare-dblock ()
11262 "Prepare dynamic block for refresh.
11263 This empties the block, puts the cursor at the insert position and returns
11264 the property list including an extra property :name with the block name."
11265 (unless (looking-at org-dblock-start-re)
11266 (error "Not at a dynamic block"))
11267 (let* ((begdel (1+ (match-end 0)))
11268 (name (org-no-properties (match-string 1)))
11269 (params (append (list :name name)
11270 (read (concat "(" (match-string 3) ")")))))
11271 (save-excursion
11272 (beginning-of-line 1)
11273 (skip-chars-forward " \t")
11274 (setq params (plist-put params :indentation-column (current-column))))
11275 (unless (re-search-forward org-dblock-end-re nil t)
11276 (error "Dynamic block not terminated"))
11277 (setq params
11278 (append params
11279 (list :content (buffer-substring
11280 begdel (match-beginning 0)))))
11281 (delete-region begdel (match-beginning 0))
11282 (goto-char begdel)
11283 (open-line 1)
11284 params))
11286 (defun org-map-dblocks (&optional command)
11287 "Apply COMMAND to all dynamic blocks in the current buffer.
11288 If COMMAND is not given, use `org-update-dblock'."
11289 (let ((cmd (or command 'org-update-dblock)))
11290 (save-excursion
11291 (goto-char (point-min))
11292 (while (re-search-forward org-dblock-start-re nil t)
11293 (goto-char (match-beginning 0))
11294 (save-excursion
11295 (condition-case nil
11296 (funcall cmd)
11297 (error (message "Error during update of dynamic block"))))
11298 (unless (re-search-forward org-dblock-end-re nil t)
11299 (error "Dynamic block not terminated"))))))
11301 (defun org-dblock-update (&optional arg)
11302 "User command for updating dynamic blocks.
11303 Update the dynamic block at point. With prefix ARG, update all dynamic
11304 blocks in the buffer."
11305 (interactive "P")
11306 (if arg
11307 (org-update-all-dblocks)
11308 (or (looking-at org-dblock-start-re)
11309 (org-beginning-of-dblock))
11310 (org-update-dblock)))
11312 (defun org-update-dblock ()
11313 "Update the dynamic block at point.
11314 This means to empty the block, parse for parameters and then call
11315 the correct writing function."
11316 (interactive)
11317 (save-window-excursion
11318 (let* ((pos (point))
11319 (line (org-current-line))
11320 (params (org-prepare-dblock))
11321 (name (plist-get params :name))
11322 (indent (plist-get params :indentation-column))
11323 (cmd (intern (concat "org-dblock-write:" name))))
11324 (message "Updating dynamic block `%s' at line %d..." name line)
11325 (funcall cmd params)
11326 (message "Updating dynamic block `%s' at line %d...done" name line)
11327 (goto-char pos)
11328 (when (and indent (> indent 0))
11329 (setq indent (make-string indent ?\ ))
11330 (save-excursion
11331 (org-beginning-of-dblock)
11332 (forward-line 1)
11333 (while (not (looking-at org-dblock-end-re))
11334 (insert indent)
11335 (beginning-of-line 2))
11336 (when (looking-at org-dblock-end-re)
11337 (and (looking-at "[ \t]+")
11338 (replace-match ""))
11339 (insert indent)))))))
11341 (defun org-beginning-of-dblock ()
11342 "Find the beginning of the dynamic block at point.
11343 Error if there is no such block at point."
11344 (let ((pos (point))
11345 beg)
11346 (end-of-line 1)
11347 (if (and (re-search-backward org-dblock-start-re nil t)
11348 (setq beg (match-beginning 0))
11349 (re-search-forward org-dblock-end-re nil t)
11350 (> (match-end 0) pos))
11351 (goto-char beg)
11352 (goto-char pos)
11353 (error "Not in a dynamic block"))))
11355 ;;;###autoload
11356 (defun org-update-all-dblocks ()
11357 "Update all dynamic blocks in the buffer.
11358 This function can be used in a hook."
11359 (interactive)
11360 (when (derived-mode-p 'org-mode)
11361 (org-map-dblocks 'org-update-dblock)))
11364 ;;;; Completion
11366 (defconst org-additional-option-like-keywords
11367 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11368 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11369 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11370 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11371 "BEGIN:" "END:"
11372 "ORGTBL" "TBLFM:" "TBLNAME:"
11373 "BEGIN_EXAMPLE" "END_EXAMPLE"
11374 "BEGIN_VERBATIM" "END_VERBATIM"
11375 "BEGIN_QUOTE" "END_QUOTE"
11376 "BEGIN_VERSE" "END_VERSE"
11377 "BEGIN_CENTER" "END_CENTER"
11378 "BEGIN_SRC" "END_SRC"
11379 "BEGIN_RESULT" "END_RESULT"
11380 "BEGIN_lstlisting" "END_lstlisting"
11381 "NAME:" "RESULTS:"
11382 "HEADER:" "HEADERS:"
11383 "COLUMNS:" "PROPERTY:"
11384 "CAPTION:" "LABEL:"
11385 "SETUPFILE:"
11386 "INCLUDE:"
11387 "BIND:"
11388 "MACRO:"))
11390 (defconst org-options-keywords
11391 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11392 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11393 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11394 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11395 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11396 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11397 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11399 (defconst org-additional-option-like-keywords-for-flyspell
11400 (delete-dups
11401 (split-string
11402 (mapconcat (lambda(k)
11403 (replace-regexp-in-string
11404 "_\\|:" " "
11405 (concat k " " (downcase k) " " (upcase k))))
11406 (append org-options-keywords org-additional-option-like-keywords)
11407 " ")
11408 " +" t)))
11410 (defcustom org-structure-template-alist
11412 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11413 "<src lang=\"?\">\n\n</src>")
11414 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11415 "<example>\n?\n</example>")
11416 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11417 "<quote>\n?\n</quote>")
11418 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11419 "<verse>\n?\n</verse>")
11420 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11421 "<center>\n?\n</center>")
11422 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11423 "<literal style=\"latex\">\n?\n</literal>")
11424 ("L" "#+LaTeX: "
11425 "<literal style=\"latex\">?</literal>")
11426 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11427 "<literal style=\"html\">\n?\n</literal>")
11428 ("H" "#+HTML: "
11429 "<literal style=\"html\">?</literal>")
11430 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11431 ("A" "#+ASCII: ")
11432 ("i" "#+INDEX: ?"
11433 "#+INDEX: ?")
11434 ("I" "#+INCLUDE: %file ?"
11435 "<include file=%file markup=\"?\">")
11437 "Structure completion elements.
11438 This is a list of abbreviation keys and values. The value gets inserted
11439 if you type `<' followed by the key and then press the completion key,
11440 usually `M-TAB'. %file will be replaced by a file name after prompting
11441 for the file using completion. The cursor will be placed at the position
11442 of the `?` in the template.
11443 There are two templates for each key, the first uses the original Org syntax,
11444 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11445 the default when the /org-mtags.el/ module has been loaded. See also the
11446 variable `org-mtags-prefer-muse-templates'."
11447 :group 'org-completion
11448 :type '(repeat
11449 (string :tag "Key")
11450 (string :tag "Template")
11451 (string :tag "Muse Template")))
11453 (defun org-try-structure-completion ()
11454 "Try to complete a structure template before point.
11455 This looks for strings like \"<e\" on an otherwise empty line and
11456 expands them."
11457 (let ((l (buffer-substring (point-at-bol) (point)))
11459 (when (and (looking-at "[ \t]*$")
11460 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11461 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11462 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11463 (match-beginning 1)) a)
11464 t)))
11466 (defun org-complete-expand-structure-template (start cell)
11467 "Expand a structure template."
11468 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11469 (rpl (nth (if musep 2 1) cell))
11470 (ind ""))
11471 (delete-region start (point))
11472 (when (string-match "\\`#\\+" rpl)
11473 (cond
11474 ((bolp))
11475 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11476 (setq ind (buffer-substring (point-at-bol) (point))))
11477 (t (newline))))
11478 (setq start (point))
11479 (if (string-match "%file" rpl)
11480 (setq rpl (replace-match
11481 (concat
11482 "\""
11483 (save-match-data
11484 (abbreviate-file-name (read-file-name "Include file: ")))
11485 "\"")
11486 t t rpl)))
11487 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11488 (concat "\n" ind)))
11489 (insert rpl)
11490 (if (re-search-backward "\\?" start t) (delete-char 1))))
11492 ;;;; TODO, DEADLINE, Comments
11494 (defun org-toggle-comment ()
11495 "Change the COMMENT state of an entry."
11496 (interactive)
11497 (save-excursion
11498 (org-back-to-heading)
11499 (let (case-fold-search)
11500 (cond
11501 ((looking-at (format org-heading-keyword-regexp-format
11502 org-comment-string))
11503 (goto-char (match-end 1))
11504 (looking-at (concat " +" org-comment-string))
11505 (replace-match "" t t)
11506 (when (eolp) (insert " ")))
11507 ((looking-at org-outline-regexp)
11508 (goto-char (match-end 0))
11509 (insert org-comment-string " "))))))
11511 (defvar org-last-todo-state-is-todo nil
11512 "This is non-nil when the last TODO state change led to a TODO state.
11513 If the last change removed the TODO tag or switched to DONE, then
11514 this is nil.")
11516 (defvar org-setting-tags nil) ; dynamically skipped
11518 (defvar org-todo-setup-filter-hook nil
11519 "Hook for functions that pre-filter todo specs.
11520 Each function takes a todo spec and returns either nil or the spec
11521 transformed into canonical form." )
11523 (defvar org-todo-get-default-hook nil
11524 "Hook for functions that get a default item for todo.
11525 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11526 nil or a string to be used for the todo mark." )
11528 (defvar org-agenda-headline-snapshot-before-repeat)
11530 (defun org-current-effective-time ()
11531 "Return current time adjusted for `org-extend-today-until' variable."
11532 (let* ((ct (org-current-time))
11533 (dct (decode-time ct))
11534 (ct1
11535 (if (and org-use-effective-time
11536 (< (nth 2 dct) org-extend-today-until))
11537 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11538 ct)))
11539 ct1))
11541 (defun org-todo-yesterday (&optional arg)
11542 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11543 (interactive "P")
11544 (if (eq major-mode 'org-agenda-mode)
11545 (apply 'org-agenda-todo-yesterday arg)
11546 (let* ((hour (third (decode-time
11547 (org-current-time))))
11548 (org-extend-today-until (1+ hour)))
11549 (org-todo arg))))
11551 (defun org-todo (&optional arg)
11552 "Change the TODO state of an item.
11553 The state of an item is given by a keyword at the start of the heading,
11554 like
11555 *** TODO Write paper
11556 *** DONE Call mom
11558 The different keywords are specified in the variable `org-todo-keywords'.
11559 By default the available states are \"TODO\" and \"DONE\".
11560 So for this example: when the item starts with TODO, it is changed to DONE.
11561 When it starts with DONE, the DONE is removed. And when neither TODO nor
11562 DONE are present, add TODO at the beginning of the heading.
11564 With \\[universal-argument] prefix arg, use completion to determine the new \
11565 state.
11566 With numeric prefix arg, switch to that state.
11567 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11568 keywords (nextset).
11569 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11570 With a numeric prefix arg of 0, inhibit note taking for the change.
11572 For calling through lisp, arg is also interpreted in the following way:
11573 'none -> empty state
11574 \"\"(empty string) -> switch to empty state
11575 'done -> switch to DONE
11576 'nextset -> switch to the next set of keywords
11577 'previousset -> switch to the previous set of keywords
11578 \"WAITING\" -> switch to the specified keyword, but only if it
11579 really is a member of `org-todo-keywords'."
11580 (interactive "P")
11581 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11582 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11583 'region-start-level 'region))
11584 org-loop-over-headlines-in-active-region)
11585 (org-map-entries
11586 `(org-todo ,arg)
11587 org-loop-over-headlines-in-active-region
11588 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11589 (if (equal arg '(16)) (setq arg 'nextset))
11590 (let ((org-blocker-hook org-blocker-hook)
11591 (case-fold-search nil))
11592 (when (equal arg '(64))
11593 (setq arg nil org-blocker-hook nil))
11594 (when (and org-blocker-hook
11595 (or org-inhibit-blocking
11596 (org-entry-get nil "NOBLOCKING")))
11597 (setq org-blocker-hook nil))
11598 (save-excursion
11599 (catch 'exit
11600 (org-back-to-heading t)
11601 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11602 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11603 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11604 (let* ((match-data (match-data))
11605 (startpos (point-at-bol))
11606 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11607 (org-log-done org-log-done)
11608 (org-log-repeat org-log-repeat)
11609 (org-todo-log-states org-todo-log-states)
11610 (org-inhibit-logging
11611 (if (equal arg 0)
11612 (progn (setq arg nil) 'note) org-inhibit-logging))
11613 (this (match-string 1))
11614 (hl-pos (match-beginning 0))
11615 (head (org-get-todo-sequence-head this))
11616 (ass (assoc head org-todo-kwd-alist))
11617 (interpret (nth 1 ass))
11618 (done-word (nth 3 ass))
11619 (final-done-word (nth 4 ass))
11620 (org-last-state (or this ""))
11621 (completion-ignore-case t)
11622 (member (member this org-todo-keywords-1))
11623 (tail (cdr member))
11624 (org-state (cond
11625 ((and org-todo-key-trigger
11626 (or (and (equal arg '(4))
11627 (eq org-use-fast-todo-selection 'prefix))
11628 (and (not arg) org-use-fast-todo-selection
11629 (not (eq org-use-fast-todo-selection
11630 'prefix)))))
11631 ;; Use fast selection
11632 (org-fast-todo-selection))
11633 ((and (equal arg '(4))
11634 (or (not org-use-fast-todo-selection)
11635 (not org-todo-key-trigger)))
11636 ;; Read a state with completion
11637 (org-icompleting-read
11638 "State: " (mapcar (lambda(x) (list x))
11639 org-todo-keywords-1)
11640 nil t))
11641 ((eq arg 'right)
11642 (if this
11643 (if tail (car tail) nil)
11644 (car org-todo-keywords-1)))
11645 ((eq arg 'left)
11646 (if (equal member org-todo-keywords-1)
11648 (if this
11649 (nth (- (length org-todo-keywords-1)
11650 (length tail) 2)
11651 org-todo-keywords-1)
11652 (org-last org-todo-keywords-1))))
11653 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11654 (setq arg nil))) ; hack to fall back to cycling
11655 (arg
11656 ;; user or caller requests a specific state
11657 (cond
11658 ((equal arg "") nil)
11659 ((eq arg 'none) nil)
11660 ((eq arg 'done) (or done-word (car org-done-keywords)))
11661 ((eq arg 'nextset)
11662 (or (car (cdr (member head org-todo-heads)))
11663 (car org-todo-heads)))
11664 ((eq arg 'previousset)
11665 (let ((org-todo-heads (reverse org-todo-heads)))
11666 (or (car (cdr (member head org-todo-heads)))
11667 (car org-todo-heads))))
11668 ((car (member arg org-todo-keywords-1)))
11669 ((stringp arg)
11670 (error "State `%s' not valid in this file" arg))
11671 ((nth (1- (prefix-numeric-value arg))
11672 org-todo-keywords-1))))
11673 ((null member) (or head (car org-todo-keywords-1)))
11674 ((equal this final-done-word) nil) ;; -> make empty
11675 ((null tail) nil) ;; -> first entry
11676 ((memq interpret '(type priority))
11677 (if (eq this-command last-command)
11678 (car tail)
11679 (if (> (length tail) 0)
11680 (or done-word (car org-done-keywords))
11681 nil)))
11683 (car tail))))
11684 (org-state (or
11685 (run-hook-with-args-until-success
11686 'org-todo-get-default-hook org-state org-last-state)
11687 org-state))
11688 (next (if org-state (concat " " org-state " ") " "))
11689 (change-plist (list :type 'todo-state-change :from this :to org-state
11690 :position startpos))
11691 dolog now-done-p)
11692 (when org-blocker-hook
11693 (setq org-last-todo-state-is-todo
11694 (not (member this org-done-keywords)))
11695 (unless (save-excursion
11696 (save-match-data
11697 (org-with-wide-buffer
11698 (run-hook-with-args-until-failure
11699 'org-blocker-hook change-plist))))
11700 (if (org-called-interactively-p 'interactive)
11701 (error "TODO state change from %s to %s blocked" this org-state)
11702 ;; fail silently
11703 (message "TODO state change from %s to %s blocked" this org-state)
11704 (throw 'exit nil))))
11705 (store-match-data match-data)
11706 (replace-match next t t)
11707 (unless (pos-visible-in-window-p hl-pos)
11708 (message "TODO state changed to %s" (org-trim next)))
11709 (unless head
11710 (setq head (org-get-todo-sequence-head org-state)
11711 ass (assoc head org-todo-kwd-alist)
11712 interpret (nth 1 ass)
11713 done-word (nth 3 ass)
11714 final-done-word (nth 4 ass)))
11715 (when (memq arg '(nextset previousset))
11716 (message "Keyword-Set %d/%d: %s"
11717 (- (length org-todo-sets) -1
11718 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11719 (length org-todo-sets)
11720 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11721 (setq org-last-todo-state-is-todo
11722 (not (member org-state org-done-keywords)))
11723 (setq now-done-p (and (member org-state org-done-keywords)
11724 (not (member this org-done-keywords))))
11725 (and logging (org-local-logging logging))
11726 (when (and (or org-todo-log-states org-log-done)
11727 (not (eq org-inhibit-logging t))
11728 (not (memq arg '(nextset previousset))))
11729 ;; we need to look at recording a time and note
11730 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11731 (nth 2 (assoc this org-todo-log-states))))
11732 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11733 (setq dolog 'time))
11734 (when (and org-state
11735 (member org-state org-not-done-keywords)
11736 (not (member this org-not-done-keywords)))
11737 ;; This is now a todo state and was not one before
11738 ;; If there was a CLOSED time stamp, get rid of it.
11739 (org-add-planning-info nil nil 'closed))
11740 (when (and now-done-p org-log-done)
11741 ;; It is now done, and it was not done before
11742 (org-add-planning-info 'closed (org-current-effective-time))
11743 (if (and (not dolog) (eq 'note org-log-done))
11744 (org-add-log-setup 'done org-state this 'findpos 'note)))
11745 (when (and org-state dolog)
11746 ;; This is a non-nil state, and we need to log it
11747 (org-add-log-setup 'state org-state this 'findpos dolog)))
11748 ;; Fixup tag positioning
11749 (org-todo-trigger-tag-changes org-state)
11750 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11751 (when org-provide-todo-statistics
11752 (org-update-parent-todo-statistics))
11753 (run-hooks 'org-after-todo-state-change-hook)
11754 (if (and arg (not (member org-state org-done-keywords)))
11755 (setq head (org-get-todo-sequence-head org-state)))
11756 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11757 ;; Do we need to trigger a repeat?
11758 (when now-done-p
11759 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11760 ;; This is for the agenda, take a snapshot of the headline.
11761 (save-match-data
11762 (setq org-agenda-headline-snapshot-before-repeat
11763 (org-get-heading))))
11764 (org-auto-repeat-maybe org-state))
11765 ;; Fixup cursor location if close to the keyword
11766 (if (and (outline-on-heading-p)
11767 (not (bolp))
11768 (save-excursion (beginning-of-line 1)
11769 (looking-at org-todo-line-regexp))
11770 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11771 (progn
11772 (goto-char (or (match-end 2) (match-end 1)))
11773 (and (looking-at " ") (just-one-space))))
11774 (when org-trigger-hook
11775 (save-excursion
11776 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11778 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11779 "Block turning an entry into a TODO, using the hierarchy.
11780 This checks whether the current task should be blocked from state
11781 changes. Such blocking occurs when:
11783 1. The task has children which are not all in a completed state.
11785 2. A task has a parent with the property :ORDERED:, and there
11786 are siblings prior to the current task with incomplete
11787 status.
11789 3. The parent of the task is blocked because it has siblings that should
11790 be done first, or is child of a block grandparent TODO entry."
11792 (if (not org-enforce-todo-dependencies)
11793 t ; if locally turned off don't block
11794 (catch 'dont-block
11795 ;; If this is not a todo state change, or if this entry is already DONE,
11796 ;; do not block
11797 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11798 (member (plist-get change-plist :from)
11799 (cons 'done org-done-keywords))
11800 (member (plist-get change-plist :to)
11801 (cons 'todo org-not-done-keywords))
11802 (not (plist-get change-plist :to)))
11803 (throw 'dont-block t))
11804 ;; If this task has children, and any are undone, it's blocked
11805 (save-excursion
11806 (org-back-to-heading t)
11807 (let ((this-level (funcall outline-level)))
11808 (outline-next-heading)
11809 (let ((child-level (funcall outline-level)))
11810 (while (and (not (eobp))
11811 (> child-level this-level))
11812 ;; this todo has children, check whether they are all
11813 ;; completed
11814 (if (and (not (org-entry-is-done-p))
11815 (org-entry-is-todo-p))
11816 (throw 'dont-block nil))
11817 (outline-next-heading)
11818 (setq child-level (funcall outline-level))))))
11819 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11820 ;; any previous siblings are undone, it's blocked
11821 (save-excursion
11822 (org-back-to-heading t)
11823 (let* ((pos (point))
11824 (parent-pos (and (org-up-heading-safe) (point))))
11825 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11826 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11827 (forward-line 1)
11828 (re-search-forward org-not-done-heading-regexp pos t))
11829 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11830 ;; Search further up the hierarchy, to see if an ancestor is blocked
11831 (while t
11832 (goto-char parent-pos)
11833 (if (not (looking-at org-not-done-heading-regexp))
11834 (throw 'dont-block t)) ; do not block, parent is not a TODO
11835 (setq pos (point))
11836 (setq parent-pos (and (org-up-heading-safe) (point)))
11837 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11838 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11839 (forward-line 1)
11840 (re-search-forward org-not-done-heading-regexp pos t))
11841 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11843 (defcustom org-track-ordered-property-with-tag nil
11844 "Should the ORDERED property also be shown as a tag?
11845 The ORDERED property decides if an entry should require subtasks to be
11846 completed in sequence. Since a property is not very visible, setting
11847 this option means that toggling the ORDERED property with the command
11848 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11849 not relevant for the behavior, but it makes things more visible.
11851 Note that toggling the tag with tags commands will not change the property
11852 and therefore not influence behavior!
11854 This can be t, meaning the tag ORDERED should be used, It can also be a
11855 string to select a different tag for this task."
11856 :group 'org-todo
11857 :type '(choice
11858 (const :tag "No tracking" nil)
11859 (const :tag "Track with ORDERED tag" t)
11860 (string :tag "Use other tag")))
11862 (defun org-toggle-ordered-property ()
11863 "Toggle the ORDERED property of the current entry.
11864 For better visibility, you can track the value of this property with a tag.
11865 See variable `org-track-ordered-property-with-tag'."
11866 (interactive)
11867 (let* ((t1 org-track-ordered-property-with-tag)
11868 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11869 (save-excursion
11870 (org-back-to-heading)
11871 (if (org-entry-get nil "ORDERED")
11872 (progn
11873 (org-delete-property "ORDERED")
11874 (and tag (org-toggle-tag tag 'off))
11875 (message "Subtasks can be completed in arbitrary order"))
11876 (org-entry-put nil "ORDERED" "t")
11877 (and tag (org-toggle-tag tag 'on))
11878 (message "Subtasks must be completed in sequence")))))
11880 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11881 (defun org-block-todo-from-checkboxes (change-plist)
11882 "Block turning an entry into a TODO, using checkboxes.
11883 This checks whether the current task should be blocked from state
11884 changes because there are unchecked boxes in this entry."
11885 (if (not org-enforce-todo-checkbox-dependencies)
11886 t ; if locally turned off don't block
11887 (catch 'dont-block
11888 ;; If this is not a todo state change, or if this entry is already DONE,
11889 ;; do not block
11890 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11891 (member (plist-get change-plist :from)
11892 (cons 'done org-done-keywords))
11893 (member (plist-get change-plist :to)
11894 (cons 'todo org-not-done-keywords))
11895 (not (plist-get change-plist :to)))
11896 (throw 'dont-block t))
11897 ;; If this task has checkboxes that are not checked, it's blocked
11898 (save-excursion
11899 (org-back-to-heading t)
11900 (let ((beg (point)) end)
11901 (outline-next-heading)
11902 (setq end (point))
11903 (goto-char beg)
11904 (if (org-list-search-forward
11905 (concat (org-item-beginning-re)
11906 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11907 "\\[[- ]\\]")
11908 end t)
11909 (progn
11910 (if (boundp 'org-blocked-by-checkboxes)
11911 (setq org-blocked-by-checkboxes t))
11912 (throw 'dont-block nil)))))
11913 t))) ; do not block
11915 (defun org-entry-blocked-p ()
11916 "Is the current entry blocked?"
11917 (if (org-entry-get nil "NOBLOCKING")
11918 nil ;; Never block this entry
11919 (not
11920 (run-hook-with-args-until-failure
11921 'org-blocker-hook
11922 (list :type 'todo-state-change
11923 :position (point)
11924 :from 'todo
11925 :to 'done)))))
11927 (defun org-update-statistics-cookies (all)
11928 "Update the statistics cookie, either from TODO or from checkboxes.
11929 This should be called with the cursor in a line with a statistics cookie."
11930 (interactive "P")
11931 (if all
11932 (progn
11933 (org-update-checkbox-count 'all)
11934 (org-map-entries 'org-update-parent-todo-statistics))
11935 (if (not (org-at-heading-p))
11936 (org-update-checkbox-count)
11937 (let ((pos (move-marker (make-marker) (point)))
11938 end l1 l2)
11939 (ignore-errors (org-back-to-heading t))
11940 (if (not (org-at-heading-p))
11941 (org-update-checkbox-count)
11942 (setq l1 (org-outline-level))
11943 (setq end (save-excursion
11944 (outline-next-heading)
11945 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11946 (point)))
11947 (if (and (save-excursion
11948 (re-search-forward
11949 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11950 (not (save-excursion (re-search-forward
11951 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11952 (org-update-checkbox-count)
11953 (if (and l2 (> l2 l1))
11954 (progn
11955 (goto-char end)
11956 (org-update-parent-todo-statistics))
11957 (goto-char pos)
11958 (beginning-of-line 1)
11959 (while (re-search-forward
11960 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11961 (point-at-eol) t)
11962 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11963 (goto-char pos)
11964 (move-marker pos nil)))))
11966 (defvar org-entry-property-inherited-from) ;; defined below
11967 (defun org-update-parent-todo-statistics ()
11968 "Update any statistics cookie in the parent of the current headline.
11969 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11970 the entire subtree and this will travel up the hierarchy and update
11971 statistics everywhere."
11972 (let* ((prop (save-excursion (org-up-heading-safe)
11973 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11974 (recursive (or (not org-hierarchical-todo-statistics)
11975 (and prop (string-match "\\<recursive\\>" prop))))
11976 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11978 (first t)
11979 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11980 level ltoggle l1 new ndel
11981 (cnt-all 0) (cnt-done 0) is-percent kwd
11982 checkbox-beg ov ovs ove cookie-present)
11983 (catch 'exit
11984 (save-excursion
11985 (beginning-of-line 1)
11986 (setq ltoggle (funcall outline-level))
11987 ;; Three situations are to consider:
11989 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11990 ;; to the top-level ancestor on the headline;
11992 ;; 2. If parent has "recursive" property, repeat up to the
11993 ;; headline setting that property, taking inheritance into
11994 ;; account;
11996 ;; 3. Else, move up to direct parent and proceed only once.
11997 (while (and (setq level (org-up-heading-safe))
11998 (or recursive first)
11999 (>= (point) lim))
12000 (setq first nil cookie-present nil)
12001 (unless (and level
12002 (not (string-match
12003 "\\<checkbox\\>"
12004 (downcase (or (org-entry-get nil "COOKIE_DATA")
12005 "")))))
12006 (throw 'exit nil))
12007 (while (re-search-forward box-re (point-at-eol) t)
12008 (setq cnt-all 0 cnt-done 0 cookie-present t)
12009 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12010 (save-match-data
12011 (unless (outline-next-heading) (throw 'exit nil))
12012 (while (and (looking-at org-complex-heading-regexp)
12013 (> (setq l1 (length (match-string 1))) level))
12014 (setq kwd (and (or recursive (= l1 ltoggle))
12015 (match-string 2)))
12016 (if (or (eq org-provide-todo-statistics 'all-headlines)
12017 (and (listp org-provide-todo-statistics)
12018 (or (member kwd org-provide-todo-statistics)
12019 (member kwd org-done-keywords))))
12020 (setq cnt-all (1+ cnt-all))
12021 (if (eq org-provide-todo-statistics t)
12022 (and kwd (setq cnt-all (1+ cnt-all)))))
12023 (and (member kwd org-done-keywords)
12024 (setq cnt-done (1+ cnt-done)))
12025 (outline-next-heading)))
12026 (setq new
12027 (if is-percent
12028 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12029 (format "[%d/%d]" cnt-done cnt-all))
12030 ndel (- (match-end 0) checkbox-beg))
12031 ;; handle overlays when updating cookie from column view
12032 (when (setq ov (car (overlays-at checkbox-beg)))
12033 (setq ovs (overlay-start ov) ove (overlay-end ov))
12034 (delete-overlay ov))
12035 (goto-char checkbox-beg)
12036 (insert new)
12037 (delete-region (point) (+ (point) ndel))
12038 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12039 (when ov (move-overlay ov ovs ove)))
12040 (when cookie-present
12041 (run-hook-with-args 'org-after-todo-statistics-hook
12042 cnt-done (- cnt-all cnt-done))))))
12043 (run-hooks 'org-todo-statistics-hook)))
12045 (defvar org-after-todo-statistics-hook nil
12046 "Hook that is called after a TODO statistics cookie has been updated.
12047 Each function is called with two arguments: the number of not-done entries
12048 and the number of done entries.
12050 For example, the following function, when added to this hook, will switch
12051 an entry to DONE when all children are done, and back to TODO when new
12052 entries are set to a TODO status. Note that this hook is only called
12053 when there is a statistics cookie in the headline!
12055 (defun org-summary-todo (n-done n-not-done)
12056 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12057 (let (org-log-done org-log-states) ; turn off logging
12058 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12061 (defvar org-todo-statistics-hook nil
12062 "Hook that is run whenever Org thinks TODO statistics should be updated.
12063 This hook runs even if there is no statistics cookie present, in which case
12064 `org-after-todo-statistics-hook' would not run.")
12066 (defun org-todo-trigger-tag-changes (state)
12067 "Apply the changes defined in `org-todo-state-tags-triggers'."
12068 (let ((l org-todo-state-tags-triggers)
12069 changes)
12070 (when (or (not state) (equal state ""))
12071 (setq changes (append changes (cdr (assoc "" l)))))
12072 (when (and (stringp state) (> (length state) 0))
12073 (setq changes (append changes (cdr (assoc state l)))))
12074 (when (member state org-not-done-keywords)
12075 (setq changes (append changes (cdr (assoc 'todo l)))))
12076 (when (member state org-done-keywords)
12077 (setq changes (append changes (cdr (assoc 'done l)))))
12078 (dolist (c changes)
12079 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12081 (defun org-local-logging (value)
12082 "Get logging settings from a property VALUE."
12083 (let* (words w a)
12084 ;; directly set the variables, they are already local.
12085 (setq org-log-done nil
12086 org-log-repeat nil
12087 org-todo-log-states nil)
12088 (setq words (org-split-string value))
12089 (while (setq w (pop words))
12090 (cond
12091 ((setq a (assoc w org-startup-options))
12092 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12093 (set (nth 1 a) (nth 2 a))))
12094 ((setq a (org-extract-log-state-settings w))
12095 (and (member (car a) org-todo-keywords-1)
12096 (push a org-todo-log-states)))))))
12098 (defun org-get-todo-sequence-head (kwd)
12099 "Return the head of the TODO sequence to which KWD belongs.
12100 If KWD is not set, check if there is a text property remembering the
12101 right sequence."
12102 (let (p)
12103 (cond
12104 ((not kwd)
12105 (or (get-text-property (point-at-bol) 'org-todo-head)
12106 (progn
12107 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12108 nil (point-at-eol)))
12109 (get-text-property p 'org-todo-head))))
12110 ((not (member kwd org-todo-keywords-1))
12111 (car org-todo-keywords-1))
12112 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12114 (defun org-fast-todo-selection ()
12115 "Fast TODO keyword selection with single keys.
12116 Returns the new TODO keyword, or nil if no state change should occur."
12117 (let* ((fulltable org-todo-key-alist)
12118 (done-keywords org-done-keywords) ;; needed for the faces.
12119 (maxlen (apply 'max (mapcar
12120 (lambda (x)
12121 (if (stringp (car x)) (string-width (car x)) 0))
12122 fulltable)))
12123 (expert nil)
12124 (fwidth (+ maxlen 3 1 3))
12125 (ncol (/ (- (window-width) 4) fwidth))
12126 tg cnt e c tbl
12127 groups ingroup)
12128 (save-excursion
12129 (save-window-excursion
12130 (if expert
12131 (set-buffer (get-buffer-create " *Org todo*"))
12132 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12133 (erase-buffer)
12134 (org-set-local 'org-done-keywords done-keywords)
12135 (setq tbl fulltable cnt 0)
12136 (while (setq e (pop tbl))
12137 (cond
12138 ((equal e '(:startgroup))
12139 (push '() groups) (setq ingroup t)
12140 (when (not (= cnt 0))
12141 (setq cnt 0)
12142 (insert "\n"))
12143 (insert "{ "))
12144 ((equal e '(:endgroup))
12145 (setq ingroup nil cnt 0)
12146 (insert "}\n"))
12147 ((equal e '(:newline))
12148 (when (not (= cnt 0))
12149 (setq cnt 0)
12150 (insert "\n")
12151 (setq e (car tbl))
12152 (while (equal (car tbl) '(:newline))
12153 (insert "\n")
12154 (setq tbl (cdr tbl)))))
12156 (setq tg (car e) c (cdr e))
12157 (if ingroup (push tg (car groups)))
12158 (setq tg (org-add-props tg nil 'face
12159 (org-get-todo-face tg)))
12160 (if (and (= cnt 0) (not ingroup)) (insert " "))
12161 (insert "[" c "] " tg (make-string
12162 (- fwidth 4 (length tg)) ?\ ))
12163 (when (= (setq cnt (1+ cnt)) ncol)
12164 (insert "\n")
12165 (if ingroup (insert " "))
12166 (setq cnt 0)))))
12167 (insert "\n")
12168 (goto-char (point-min))
12169 (if (not expert) (org-fit-window-to-buffer))
12170 (message "[a-z..]:Set [SPC]:clear")
12171 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12172 (cond
12173 ((or (= c ?\C-g)
12174 (and (= c ?q) (not (rassoc c fulltable))))
12175 (setq quit-flag t))
12176 ((= c ?\ ) nil)
12177 ((setq e (rassoc c fulltable) tg (car e))
12179 (t (setq quit-flag t)))))))
12181 (defun org-entry-is-todo-p ()
12182 (member (org-get-todo-state) org-not-done-keywords))
12184 (defun org-entry-is-done-p ()
12185 (member (org-get-todo-state) org-done-keywords))
12187 (defun org-get-todo-state ()
12188 (save-excursion
12189 (org-back-to-heading t)
12190 (and (looking-at org-todo-line-regexp)
12191 (match-end 2)
12192 (match-string 2))))
12194 (defun org-at-date-range-p (&optional inactive-ok)
12195 "Is the cursor inside a date range?"
12196 (interactive)
12197 (save-excursion
12198 (catch 'exit
12199 (let ((pos (point)))
12200 (skip-chars-backward "^[<\r\n")
12201 (skip-chars-backward "<[")
12202 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12203 (>= (match-end 0) pos)
12204 (throw 'exit t))
12205 (skip-chars-backward "^<[\r\n")
12206 (skip-chars-backward "<[")
12207 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12208 (>= (match-end 0) pos)
12209 (throw 'exit t)))
12210 nil)))
12212 (defun org-get-repeat (&optional tagline)
12213 "Check if there is a deadline/schedule with repeater in this entry."
12214 (save-match-data
12215 (save-excursion
12216 (org-back-to-heading t)
12217 (and (re-search-forward (if tagline
12218 (concat tagline "\\s-*" org-repeat-re)
12219 org-repeat-re)
12220 (org-entry-end-position) t)
12221 (match-string-no-properties 1)))))
12223 (defvar org-last-changed-timestamp)
12224 (defvar org-last-inserted-timestamp)
12225 (defvar org-log-post-message)
12226 (defvar org-log-note-purpose)
12227 (defvar org-log-note-how)
12228 (defvar org-log-note-extra)
12229 (defun org-auto-repeat-maybe (done-word)
12230 "Check if the current headline contains a repeated deadline/schedule.
12231 If yes, set TODO state back to what it was and change the base date
12232 of repeating deadline/scheduled time stamps to new date.
12233 This function is run automatically after each state change to a DONE state."
12234 ;; last-state is dynamically scoped into this function
12235 (let* ((repeat (org-get-repeat))
12236 (aa (assoc org-last-state org-todo-kwd-alist))
12237 (interpret (nth 1 aa))
12238 (head (nth 2 aa))
12239 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12240 (msg "Entry repeats: ")
12241 (org-log-done nil)
12242 (org-todo-log-states nil)
12243 re type n what ts time to-state)
12244 (when repeat
12245 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12246 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12247 org-todo-repeat-to-state))
12248 (unless (and to-state (member to-state org-todo-keywords-1))
12249 (setq to-state (if (eq interpret 'type) org-last-state head)))
12250 (org-todo to-state)
12251 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12252 (org-entry-put nil "LAST_REPEAT" (format-time-string
12253 (org-time-stamp-format t t))))
12254 (when org-log-repeat
12255 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12256 (memq 'org-add-log-note post-command-hook))
12257 ;; OK, we are already setup for some record
12258 (if (eq org-log-repeat 'note)
12259 ;; make sure we take a note, not only a time stamp
12260 (setq org-log-note-how 'note))
12261 ;; Set up for taking a record
12262 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12263 org-last-state
12264 'findpos org-log-repeat)))
12265 (org-back-to-heading t)
12266 (org-add-planning-info nil nil 'closed)
12267 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12268 org-deadline-time-regexp "\\)\\|\\("
12269 org-ts-regexp "\\)"))
12270 (while (re-search-forward
12271 re (save-excursion (outline-next-heading) (point)) t)
12272 (setq type (if (match-end 1) org-scheduled-string
12273 (if (match-end 3) org-deadline-string "Plain:"))
12274 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12275 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12276 (setq n (string-to-number (match-string 2 ts))
12277 what (match-string 3 ts))
12278 (if (equal what "w") (setq n (* n 7) what "d"))
12279 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12280 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12281 ;; Preparation, see if we need to modify the start date for the change
12282 (when (match-end 1)
12283 (setq time (save-match-data (org-time-string-to-time ts)))
12284 (cond
12285 ((equal (match-string 1 ts) ".")
12286 ;; Shift starting date to today
12287 (org-timestamp-change
12288 (- (org-today) (time-to-days time))
12289 'day))
12290 ((equal (match-string 1 ts) "+")
12291 (let ((nshiftmax 10) (nshift 0))
12292 (while (or (= nshift 0)
12293 (<= (time-to-days time)
12294 (time-to-days (current-time))))
12295 (when (= (incf nshift) nshiftmax)
12296 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12297 (error "Abort")))
12298 (org-timestamp-change n (cdr (assoc what whata)))
12299 (org-at-timestamp-p t)
12300 (setq ts (match-string 1))
12301 (setq time (save-match-data (org-time-string-to-time ts)))))
12302 (org-timestamp-change (- n) (cdr (assoc what whata)))
12303 ;; rematch, so that we have everything in place for the real shift
12304 (org-at-timestamp-p t)
12305 (setq ts (match-string 1))
12306 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12307 (org-timestamp-change n (cdr (assoc what whata)))
12308 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12309 (setq org-log-post-message msg)
12310 (message "%s" msg))))
12312 (defun org-show-todo-tree (arg)
12313 "Make a compact tree which shows all headlines marked with TODO.
12314 The tree will show the lines where the regexp matches, and all higher
12315 headlines above the match.
12316 With a \\[universal-argument] prefix, prompt for a regexp to match.
12317 With a numeric prefix N, construct a sparse tree for the Nth element
12318 of `org-todo-keywords-1'."
12319 (interactive "P")
12320 (let ((case-fold-search nil)
12321 (kwd-re
12322 (cond ((null arg) org-not-done-regexp)
12323 ((equal arg '(4))
12324 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12325 (mapcar 'list org-todo-keywords-1))))
12326 (concat "\\("
12327 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12328 "\\)\\>")))
12329 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12330 (regexp-quote (nth (1- (prefix-numeric-value arg))
12331 org-todo-keywords-1)))
12332 (t (error "Invalid prefix argument: %s" arg)))))
12333 (message "%d TODO entries found"
12334 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12336 (defun org-deadline (&optional remove time)
12337 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12338 With argument REMOVE, remove any deadline from the item.
12339 With argument TIME, set the deadline at the corresponding date. TIME
12340 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12341 (interactive "P")
12342 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12343 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12344 'region-start-level 'region))
12345 org-loop-over-headlines-in-active-region)
12346 (org-map-entries
12347 `(org-deadline ',remove ,time)
12348 org-loop-over-headlines-in-active-region
12349 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12350 (let* ((old-date (org-entry-get nil "DEADLINE"))
12351 (repeater (and old-date
12352 (string-match
12353 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12354 old-date)
12355 (match-string 1 old-date))))
12356 (if remove
12357 (progn
12358 (when (and old-date org-log-redeadline)
12359 (org-add-log-setup 'deldeadline nil old-date 'findpos
12360 org-log-redeadline))
12361 (org-remove-timestamp-with-keyword org-deadline-string)
12362 (message "Item no longer has a deadline."))
12363 (org-add-planning-info 'deadline time 'closed)
12364 (when (and old-date org-log-redeadline
12365 (not (equal old-date
12366 (substring org-last-inserted-timestamp 1 -1))))
12367 (org-add-log-setup 'redeadline nil old-date 'findpos
12368 org-log-redeadline))
12369 (when repeater
12370 (save-excursion
12371 (org-back-to-heading t)
12372 (when (re-search-forward (concat org-deadline-string " "
12373 org-last-inserted-timestamp)
12374 (save-excursion
12375 (outline-next-heading) (point)) t)
12376 (goto-char (1- (match-end 0)))
12377 (insert " " repeater)
12378 (setq org-last-inserted-timestamp
12379 (concat (substring org-last-inserted-timestamp 0 -1)
12380 " " repeater
12381 (substring org-last-inserted-timestamp -1))))))
12382 (message "Deadline on %s" org-last-inserted-timestamp)))))
12384 (defun org-schedule (&optional remove time)
12385 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12386 With argument REMOVE, remove any scheduling date from the item.
12387 With argument TIME, scheduled at the corresponding date. TIME can
12388 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12389 (interactive "P")
12390 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12391 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12392 'region-start-level 'region))
12393 org-loop-over-headlines-in-active-region)
12394 (org-map-entries
12395 `(org-schedule ',remove ,time)
12396 org-loop-over-headlines-in-active-region
12397 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12398 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12399 (repeater (and old-date
12400 (string-match
12401 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12402 old-date)
12403 (match-string 1 old-date))))
12404 (if remove
12405 (progn
12406 (when (and old-date org-log-reschedule)
12407 (org-add-log-setup 'delschedule nil old-date 'findpos
12408 org-log-reschedule))
12409 (org-remove-timestamp-with-keyword org-scheduled-string)
12410 (message "Item is no longer scheduled."))
12411 (org-add-planning-info 'scheduled time 'closed)
12412 (when (and old-date org-log-reschedule
12413 (not (equal old-date
12414 (substring org-last-inserted-timestamp 1 -1))))
12415 (org-add-log-setup 'reschedule nil old-date 'findpos
12416 org-log-reschedule))
12417 (when repeater
12418 (save-excursion
12419 (org-back-to-heading t)
12420 (when (re-search-forward (concat org-scheduled-string " "
12421 org-last-inserted-timestamp)
12422 (save-excursion
12423 (outline-next-heading) (point)) t)
12424 (goto-char (1- (match-end 0)))
12425 (insert " " repeater)
12426 (setq org-last-inserted-timestamp
12427 (concat (substring org-last-inserted-timestamp 0 -1)
12428 " " repeater
12429 (substring org-last-inserted-timestamp -1))))))
12430 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12432 (defun org-get-scheduled-time (pom &optional inherit)
12433 "Get the scheduled time as a time tuple, of a format suitable
12434 for calling org-schedule with, or if there is no scheduling,
12435 returns nil."
12436 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12437 (when time
12438 (apply 'encode-time (org-parse-time-string time)))))
12440 (defun org-get-deadline-time (pom &optional inherit)
12441 "Get the deadline as a time tuple, of a format suitable for
12442 calling org-deadline with, or if there is no scheduling, returns
12443 nil."
12444 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12445 (when time
12446 (apply 'encode-time (org-parse-time-string time)))))
12448 (defun org-remove-timestamp-with-keyword (keyword)
12449 "Remove all time stamps with KEYWORD in the current entry."
12450 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12451 beg)
12452 (save-excursion
12453 (org-back-to-heading t)
12454 (setq beg (point))
12455 (outline-next-heading)
12456 (while (re-search-backward re beg t)
12457 (replace-match "")
12458 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12459 (equal (char-before) ?\ ))
12460 (backward-delete-char 1)
12461 (if (string-match "^[ \t]*$" (buffer-substring
12462 (point-at-bol) (point-at-eol)))
12463 (delete-region (point-at-bol)
12464 (min (point-max) (1+ (point-at-eol))))))))))
12466 (defun org-add-planning-info (what &optional time &rest remove)
12467 "Insert new timestamp with keyword in the line directly after the headline.
12468 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12469 If non is given, the user is prompted for a date.
12470 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12471 be removed."
12472 (interactive)
12473 (let (org-time-was-given org-end-time-was-given ts
12474 end default-time default-input)
12476 (catch 'exit
12477 (when (and (memq what '(scheduled deadline))
12478 (or (not time)
12479 (and (stringp time)
12480 (string-match "^[-+]+[0-9]" time))))
12481 ;; Try to get a default date/time from existing timestamp
12482 (save-excursion
12483 (org-back-to-heading t)
12484 (setq end (save-excursion (outline-next-heading) (point)))
12485 (when (re-search-forward (if (eq what 'scheduled)
12486 org-scheduled-time-regexp
12487 org-deadline-time-regexp)
12488 end t)
12489 (setq ts (match-string 1)
12490 default-time
12491 (apply 'encode-time (org-parse-time-string ts))
12492 default-input (and ts (org-get-compact-tod ts))))))
12493 (when what
12494 (setq time
12495 (if (stringp time)
12496 ;; This is a string (relative or absolute), set proper date
12497 (apply 'encode-time
12498 (org-read-date-analyze
12499 time default-time (decode-time default-time)))
12500 ;; If necessary, get the time from the user
12501 (or time (org-read-date nil 'to-time nil nil
12502 default-time default-input)))))
12504 (when (and org-insert-labeled-timestamps-at-point
12505 (member what '(scheduled deadline)))
12506 (insert
12507 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12508 (org-insert-time-stamp time org-time-was-given
12509 nil nil nil (list org-end-time-was-given))
12510 (setq what nil))
12511 (save-excursion
12512 (save-restriction
12513 (let (col list elt ts buffer-invisibility-spec)
12514 (org-back-to-heading t)
12515 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12516 (goto-char (match-end 1))
12517 (setq col (current-column))
12518 (goto-char (match-end 0))
12519 (if (eobp) (insert "\n") (forward-char 1))
12520 (when (and (not what)
12521 (not (looking-at
12522 (concat "[ \t]*"
12523 org-keyword-time-not-clock-regexp))))
12524 ;; Nothing to add, nothing to remove...... :-)
12525 (throw 'exit nil))
12526 (if (and (not (looking-at org-outline-regexp))
12527 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12528 "[^\r\n]*"))
12529 (not (equal (match-string 1) org-clock-string)))
12530 (narrow-to-region (match-beginning 0) (match-end 0))
12531 (insert-before-markers "\n")
12532 (backward-char 1)
12533 (narrow-to-region (point) (point))
12534 (and org-adapt-indentation (org-indent-to-column col)))
12535 ;; Check if we have to remove something.
12536 (setq list (cons what remove))
12537 (while list
12538 (setq elt (pop list))
12539 (when (or (and (eq elt 'scheduled)
12540 (re-search-forward org-scheduled-time-regexp nil t))
12541 (and (eq elt 'deadline)
12542 (re-search-forward org-deadline-time-regexp nil t))
12543 (and (eq elt 'closed)
12544 (re-search-forward org-closed-time-regexp nil t)))
12545 (replace-match "")
12546 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12547 (and (looking-at "[ \t]+") (replace-match ""))
12548 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12549 (when what
12550 (insert
12551 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12552 (cond ((eq what 'scheduled) org-scheduled-string)
12553 ((eq what 'deadline) org-deadline-string)
12554 ((eq what 'closed) org-closed-string))
12555 " ")
12556 (setq ts (org-insert-time-stamp
12557 time
12558 (or org-time-was-given
12559 (and (eq what 'closed) org-log-done-with-time))
12560 (eq what 'closed)
12561 nil nil (list org-end-time-was-given)))
12562 (insert
12563 (if (not (or (bolp) (eq (char-before) ?\ )
12564 (memq (char-after) '(32 10))
12565 (eobp))) " " ""))
12566 (end-of-line 1))
12567 (goto-char (point-min))
12568 (widen)
12569 (if (and (looking-at "[ \t]*\n")
12570 (equal (char-before) ?\n))
12571 (delete-region (1- (point)) (point-at-eol)))
12572 ts))))))
12574 (defvar org-log-note-marker (make-marker))
12575 (defvar org-log-note-purpose nil)
12576 (defvar org-log-note-state nil)
12577 (defvar org-log-note-previous-state nil)
12578 (defvar org-log-note-how nil)
12579 (defvar org-log-note-extra nil)
12580 (defvar org-log-note-window-configuration nil)
12581 (defvar org-log-note-return-to (make-marker))
12582 (defvar org-log-note-effective-time nil
12583 "Remembered current time so that dynamically scoped
12584 `org-extend-today-until' affects tha timestamps in state change
12585 log")
12587 (defvar org-log-post-message nil
12588 "Message to be displayed after a log note has been stored.
12589 The auto-repeater uses this.")
12591 (defun org-add-note ()
12592 "Add a note to the current entry.
12593 This is done in the same way as adding a state change note."
12594 (interactive)
12595 (org-add-log-setup 'note nil nil 'findpos nil))
12597 (defvar org-property-end-re)
12598 (defun org-add-log-setup (&optional purpose state prev-state
12599 findpos how extra)
12600 "Set up the post command hook to take a note.
12601 If this is about to TODO state change, the new state is expected in STATE.
12602 When FINDPOS is non-nil, find the correct position for the note in
12603 the current entry. If not, assume that it can be inserted at point.
12604 HOW is an indicator what kind of note should be created.
12605 EXTRA is additional text that will be inserted into the notes buffer."
12606 (let* ((org-log-into-drawer (org-log-into-drawer))
12607 (drawer (cond ((stringp org-log-into-drawer)
12608 org-log-into-drawer)
12609 (org-log-into-drawer "LOGBOOK"))))
12610 (save-restriction
12611 (save-excursion
12612 (when findpos
12613 (org-back-to-heading t)
12614 (narrow-to-region (point) (save-excursion
12615 (outline-next-heading) (point)))
12616 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12617 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12618 "[^\r\n]*\\)?"))
12619 (goto-char (match-end 0))
12620 (cond
12621 (drawer
12622 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12623 nil t)
12624 (progn
12625 (goto-char (match-end 0))
12626 (or org-log-states-order-reversed
12627 (and (re-search-forward org-property-end-re nil t)
12628 (goto-char (1- (match-beginning 0))))))
12629 (insert "\n:" drawer ":\n:END:")
12630 (beginning-of-line 0)
12631 (org-indent-line)
12632 (beginning-of-line 2)
12633 (org-indent-line)
12634 (end-of-line 0)))
12635 ((and org-log-state-notes-insert-after-drawers
12636 (save-excursion
12637 (forward-line) (looking-at org-drawer-regexp)))
12638 (forward-line)
12639 (while (looking-at org-drawer-regexp)
12640 (goto-char (match-end 0))
12641 (re-search-forward org-property-end-re (point-max) t)
12642 (forward-line))
12643 (forward-line -1)))
12644 (unless org-log-states-order-reversed
12645 (and (= (char-after) ?\n) (forward-char 1))
12646 (org-skip-over-state-notes)
12647 (skip-chars-backward " \t\n\r")))
12648 (move-marker org-log-note-marker (point))
12649 (setq org-log-note-purpose purpose
12650 org-log-note-state state
12651 org-log-note-previous-state prev-state
12652 org-log-note-how how
12653 org-log-note-extra extra
12654 org-log-note-effective-time (org-current-effective-time))
12655 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12657 (defun org-skip-over-state-notes ()
12658 "Skip past the list of State notes in an entry."
12659 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12660 (when (ignore-errors (goto-char (org-in-item-p)))
12661 (let* ((struct (org-list-struct))
12662 (prevs (org-list-prevs-alist struct)))
12663 (while (looking-at "[ \t]*- State")
12664 (goto-char (or (org-list-get-next-item (point) struct prevs)
12665 (org-list-get-item-end (point) struct)))))))
12667 (defun org-add-log-note (&optional purpose)
12668 "Pop up a window for taking a note, and add this note later at point."
12669 (remove-hook 'post-command-hook 'org-add-log-note)
12670 (setq org-log-note-window-configuration (current-window-configuration))
12671 (delete-other-windows)
12672 (move-marker org-log-note-return-to (point))
12673 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12674 (goto-char org-log-note-marker)
12675 (org-switch-to-buffer-other-window "*Org Note*")
12676 (erase-buffer)
12677 (if (memq org-log-note-how '(time state))
12678 (let (current-prefix-arg) (org-store-log-note))
12679 (let ((org-inhibit-startup t)) (org-mode))
12680 (insert (format "# Insert note for %s.
12681 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12682 (cond
12683 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12684 ((eq org-log-note-purpose 'done) "closed todo item")
12685 ((eq org-log-note-purpose 'state)
12686 (format "state change from \"%s\" to \"%s\""
12687 (or org-log-note-previous-state "")
12688 (or org-log-note-state "")))
12689 ((eq org-log-note-purpose 'reschedule)
12690 "rescheduling")
12691 ((eq org-log-note-purpose 'delschedule)
12692 "no longer scheduled")
12693 ((eq org-log-note-purpose 'redeadline)
12694 "changing deadline")
12695 ((eq org-log-note-purpose 'deldeadline)
12696 "removing deadline")
12697 ((eq org-log-note-purpose 'refile)
12698 "refiling")
12699 ((eq org-log-note-purpose 'note)
12700 "this entry")
12701 (t (error "This should not happen")))))
12702 (if org-log-note-extra (insert org-log-note-extra))
12703 (org-set-local 'org-finish-function 'org-store-log-note)
12704 (run-hooks 'org-log-buffer-setup-hook)))
12706 (defvar org-note-abort nil) ; dynamically scoped
12707 (defun org-store-log-note ()
12708 "Finish taking a log note, and insert it to where it belongs."
12709 (let ((txt (buffer-string))
12710 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12711 lines ind bul)
12712 (kill-buffer (current-buffer))
12713 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12714 (setq txt (replace-match "" t t txt)))
12715 (if (string-match "\\s-+\\'" txt)
12716 (setq txt (replace-match "" t t txt)))
12717 (setq lines (org-split-string txt "\n"))
12718 (when (and note (string-match "\\S-" note))
12719 (setq note
12720 (org-replace-escapes
12721 note
12722 (list (cons "%u" (user-login-name))
12723 (cons "%U" user-full-name)
12724 (cons "%t" (format-time-string
12725 (org-time-stamp-format 'long 'inactive)
12726 org-log-note-effective-time))
12727 (cons "%T" (format-time-string
12728 (org-time-stamp-format 'long nil)
12729 org-log-note-effective-time))
12730 (cons "%d" (format-time-string
12731 (org-time-stamp-format nil 'inactive)
12732 org-log-note-effective-time))
12733 (cons "%D" (format-time-string
12734 (org-time-stamp-format nil nil)
12735 org-log-note-effective-time))
12736 (cons "%s" (if org-log-note-state
12737 (concat "\"" org-log-note-state "\"")
12738 ""))
12739 (cons "%S" (if org-log-note-previous-state
12740 (concat "\"" org-log-note-previous-state "\"")
12741 "\"\"")))))
12742 (if lines (setq note (concat note " \\\\")))
12743 (push note lines))
12744 (when (or current-prefix-arg org-note-abort)
12745 (when org-log-into-drawer
12746 (org-remove-empty-drawer-at
12747 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12748 org-log-note-marker))
12749 (setq lines nil))
12750 (when lines
12751 (with-current-buffer (marker-buffer org-log-note-marker)
12752 (save-excursion
12753 (goto-char org-log-note-marker)
12754 (move-marker org-log-note-marker nil)
12755 (end-of-line 1)
12756 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12757 (setq ind (save-excursion
12758 (if (ignore-errors (goto-char (org-in-item-p)))
12759 (let ((struct (org-list-struct)))
12760 (org-list-get-ind
12761 (org-list-get-top-point struct) struct))
12762 (skip-chars-backward " \r\t\n")
12763 (cond
12764 ((and (org-at-heading-p)
12765 org-adapt-indentation)
12766 (1+ (org-current-level)))
12767 ((org-at-heading-p) 0)
12768 (t (org-get-indentation))))))
12769 (setq bul (org-list-bullet-string "-"))
12770 (org-indent-line-to ind)
12771 (insert bul (pop lines))
12772 (let ((ind-body (+ (length bul) ind)))
12773 (while lines
12774 (insert "\n")
12775 (org-indent-line-to ind-body)
12776 (insert (pop lines))))
12777 (message "Note stored")
12778 (org-back-to-heading t)
12779 (org-cycle-hide-drawers 'children)))))
12780 (set-window-configuration org-log-note-window-configuration)
12781 (with-current-buffer (marker-buffer org-log-note-return-to)
12782 (goto-char org-log-note-return-to))
12783 (move-marker org-log-note-return-to nil)
12784 (and org-log-post-message (message "%s" org-log-post-message)))
12786 (defun org-remove-empty-drawer-at (drawer pos)
12787 "Remove an empty drawer DRAWER at position POS.
12788 POS may also be a marker."
12789 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12790 (save-excursion
12791 (save-restriction
12792 (widen)
12793 (goto-char pos)
12794 (if (org-in-regexp
12795 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12796 (replace-match ""))))))
12798 (defvar org-ts-type nil)
12799 (defun org-sparse-tree (&optional arg type)
12800 "Create a sparse tree, prompt for the details.
12801 This command can create sparse trees. You first need to select the type
12802 of match used to create the tree:
12804 t Show all TODO entries.
12805 T Show entries with a specific TODO keyword.
12806 m Show entries selected by a tags/property match.
12807 p Enter a property name and its value (both with completion on existing
12808 names/values) and show entries with that property.
12809 r Show entries matching a regular expression (`/' can be used as well).
12810 b Show deadlines and scheduled items before a date.
12811 a Show deadlines and scheduled items after a date.
12812 d Show deadlines due within `org-deadline-warning-days'.
12813 D Show deadlines and scheduled items between a date range."
12814 (interactive "P")
12815 (let (ans kwd value ts-type)
12816 (setq type (or type org-sparse-tree-default-date-type))
12817 (setq org-ts-type type)
12818 (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"
12819 (cond ((eq type 'all) "all timestamps")
12820 ((eq type 'scheduled) "only scheduled")
12821 ((eq type 'deadline) "only deadline")
12822 ((eq type 'active) "only active timestamps")
12823 ((eq type 'inactive) "only inactive timestamps")
12824 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12825 (t "scheduled/deadline")))
12826 (setq ans (read-char-exclusive))
12827 (cond
12828 ((equal ans ?c)
12829 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12830 ((equal ans ?d)
12831 (call-interactively 'org-check-deadlines))
12832 ((equal ans ?b)
12833 (call-interactively 'org-check-before-date))
12834 ((equal ans ?a)
12835 (call-interactively 'org-check-after-date))
12836 ((equal ans ?D)
12837 (call-interactively 'org-check-dates-range))
12838 ((equal ans ?t)
12839 (org-show-todo-tree nil))
12840 ((equal ans ?T)
12841 (org-show-todo-tree '(4)))
12842 ((member ans '(?T ?m))
12843 (call-interactively 'org-match-sparse-tree))
12844 ((member ans '(?p ?P))
12845 (setq kwd (org-icompleting-read "Property: "
12846 (mapcar 'list (org-buffer-property-keys))))
12847 (setq value (org-icompleting-read "Value: "
12848 (mapcar 'list (org-property-values kwd))))
12849 (unless (string-match "\\`{.*}\\'" value)
12850 (setq value (concat "\"" value "\"")))
12851 (org-match-sparse-tree arg (concat kwd "=" value)))
12852 ((member ans '(?r ?R ?/))
12853 (call-interactively 'org-occur))
12854 (t (error "No such sparse tree command \"%c\"" ans)))))
12856 (defvar org-occur-highlights nil
12857 "List of overlays used for occur matches.")
12858 (make-variable-buffer-local 'org-occur-highlights)
12859 (defvar org-occur-parameters nil
12860 "Parameters of the active org-occur calls.
12861 This is a list, each call to org-occur pushes as cons cell,
12862 containing the regular expression and the callback, onto the list.
12863 The list can contain several entries if `org-occur' has been called
12864 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12865 will only contain one set of parameters. When the highlights are
12866 removed (for example with `C-c C-c', or with the next edit (depending
12867 on `org-remove-highlights-with-change'), this variable is emptied
12868 as well.")
12869 (make-variable-buffer-local 'org-occur-parameters)
12871 (defun org-occur (regexp &optional keep-previous callback)
12872 "Make a compact tree which shows all matches of REGEXP.
12873 The tree will show the lines where the regexp matches, and all higher
12874 headlines above the match. It will also show the heading after the match,
12875 to make sure editing the matching entry is easy.
12876 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12877 call to `org-occur' will be kept, to allow stacking of calls to this
12878 command.
12879 If CALLBACK is non-nil, it is a function which is called to confirm
12880 that the match should indeed be shown."
12881 (interactive "sRegexp: \nP")
12882 (when (equal regexp "")
12883 (error "Regexp cannot be empty"))
12884 (unless keep-previous
12885 (org-remove-occur-highlights nil nil t))
12886 (push (cons regexp callback) org-occur-parameters)
12887 (let ((cnt 0))
12888 (save-excursion
12889 (goto-char (point-min))
12890 (if (or (not keep-previous) ; do not want to keep
12891 (not org-occur-highlights)) ; no previous matches
12892 ;; hide everything
12893 (org-overview))
12894 (while (re-search-forward regexp nil t)
12895 (when (or (not callback)
12896 (save-match-data (funcall callback)))
12897 (setq cnt (1+ cnt))
12898 (when org-highlight-sparse-tree-matches
12899 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12900 (org-show-context 'occur-tree))))
12901 (when org-remove-highlights-with-change
12902 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12903 nil 'local))
12904 (unless org-sparse-tree-open-archived-trees
12905 (org-hide-archived-subtrees (point-min) (point-max)))
12906 (run-hooks 'org-occur-hook)
12907 (if (org-called-interactively-p 'interactive)
12908 (message "%d match(es) for regexp %s" cnt regexp))
12909 cnt))
12911 (defun org-occur-next-match (&optional n reset)
12912 "Function for `next-error-function' to find sparse tree matches.
12913 N is the number of matches to move, when negative move backwards.
12914 RESET is entirely ignored - this function always goes back to the
12915 starting point when no match is found."
12916 (let* ((limit (if (< n 0) (point-min) (point-max)))
12917 (search-func (if (< n 0)
12918 'previous-single-char-property-change
12919 'next-single-char-property-change))
12920 (n (abs n))
12921 (pos (point))
12923 (catch 'exit
12924 (while (setq p1 (funcall search-func (point) 'org-type))
12925 (when (equal p1 limit)
12926 (goto-char pos)
12927 (error "No more matches"))
12928 (when (equal (get-char-property p1 'org-type) 'org-occur)
12929 (setq n (1- n))
12930 (when (= n 0)
12931 (goto-char p1)
12932 (throw 'exit (point))))
12933 (goto-char p1))
12934 (goto-char p1)
12935 (error "No more matches"))))
12937 (defun org-show-context (&optional key)
12938 "Make sure point and context are visible.
12939 How much context is shown depends upon the variables
12940 `org-show-hierarchy-above', `org-show-following-heading',
12941 `org-show-entry-below' and `org-show-siblings'."
12942 (let ((heading-p (org-at-heading-p t))
12943 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12944 (following-p (org-get-alist-option org-show-following-heading key))
12945 (entry-p (org-get-alist-option org-show-entry-below key))
12946 (siblings-p (org-get-alist-option org-show-siblings key)))
12947 (catch 'exit
12948 ;; Show heading or entry text
12949 (if (and heading-p (not entry-p))
12950 (org-flag-heading nil) ; only show the heading
12951 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12952 (org-show-hidden-entry))) ; show entire entry
12953 (when following-p
12954 ;; Show next sibling, or heading below text
12955 (save-excursion
12956 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12957 (org-flag-heading nil))))
12958 (when siblings-p (org-show-siblings))
12959 (when hierarchy-p
12960 ;; show all higher headings, possibly with siblings
12961 (save-excursion
12962 (while (and (condition-case nil
12963 (progn (org-up-heading-all 1) t)
12964 (error nil))
12965 (not (bobp)))
12966 (org-flag-heading nil)
12967 (when siblings-p (org-show-siblings))))))))
12969 (defvar org-reveal-start-hook nil
12970 "Hook run before revealing a location.")
12972 (defun org-reveal (&optional siblings)
12973 "Show current entry, hierarchy above it, and the following headline.
12974 This can be used to show a consistent set of context around locations
12975 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12976 not t for the search context.
12978 With optional argument SIBLINGS, on each level of the hierarchy all
12979 siblings are shown. This repairs the tree structure to what it would
12980 look like when opened with hierarchical calls to `org-cycle'.
12981 With double optional argument \\[universal-argument] \\[universal-argument], \
12982 go to the parent and show the
12983 entire tree."
12984 (interactive "P")
12985 (run-hooks 'org-reveal-start-hook)
12986 (let ((org-show-hierarchy-above t)
12987 (org-show-following-heading t)
12988 (org-show-siblings (if siblings t org-show-siblings)))
12989 (org-show-context nil))
12990 (when (equal siblings '(16))
12991 (save-excursion
12992 (when (org-up-heading-safe)
12993 (org-show-subtree)
12994 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12996 (defun org-highlight-new-match (beg end)
12997 "Highlight from BEG to END and mark the highlight is an occur headline."
12998 (let ((ov (make-overlay beg end)))
12999 (overlay-put ov 'face 'secondary-selection)
13000 (overlay-put ov 'org-type 'org-occur)
13001 (push ov org-occur-highlights)))
13003 (defun org-remove-occur-highlights (&optional beg end noremove)
13004 "Remove the occur highlights from the buffer.
13005 BEG and END are ignored. If NOREMOVE is nil, remove this function
13006 from the `before-change-functions' in the current buffer."
13007 (interactive)
13008 (unless org-inhibit-highlight-removal
13009 (mapc 'delete-overlay org-occur-highlights)
13010 (setq org-occur-highlights nil)
13011 (setq org-occur-parameters nil)
13012 (unless noremove
13013 (remove-hook 'before-change-functions
13014 'org-remove-occur-highlights 'local))))
13016 ;;;; Priorities
13018 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13019 "Regular expression matching the priority indicator.")
13021 (defvar org-remove-priority-next-time nil)
13023 (defun org-priority-up ()
13024 "Increase the priority of the current item."
13025 (interactive)
13026 (org-priority 'up))
13028 (defun org-priority-down ()
13029 "Decrease the priority of the current item."
13030 (interactive)
13031 (org-priority 'down))
13033 (defun org-priority (&optional action)
13034 "Change the priority of an item.
13035 ACTION can be `set', `up', `down', or a character."
13036 (interactive)
13037 (unless org-enable-priority-commands
13038 (error "Priority commands are disabled"))
13039 (setq action (or action 'set))
13040 (let (current new news have remove)
13041 (save-excursion
13042 (org-back-to-heading t)
13043 (if (looking-at org-priority-regexp)
13044 (setq current (string-to-char (match-string 2))
13045 have t))
13046 (cond
13047 ((eq action 'remove)
13048 (setq remove t new ?\ ))
13049 ((or (eq action 'set)
13050 (if (featurep 'xemacs) (characterp action) (integerp action)))
13051 (if (not (eq action 'set))
13052 (setq new action)
13053 (message "Priority %c-%c, SPC to remove: "
13054 org-highest-priority org-lowest-priority)
13055 (save-match-data
13056 (setq new (read-char-exclusive))))
13057 (if (and (= (upcase org-highest-priority) org-highest-priority)
13058 (= (upcase org-lowest-priority) org-lowest-priority))
13059 (setq new (upcase new)))
13060 (cond ((equal new ?\ ) (setq remove t))
13061 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13062 (error "Priority must be between `%c' and `%c'"
13063 org-highest-priority org-lowest-priority))))
13064 ((eq action 'up)
13065 (setq new (if have
13066 (1- current) ; normal cycling
13067 ;; last priority was empty
13068 (if (eq last-command this-command)
13069 org-lowest-priority ; wrap around empty to lowest
13070 ;; default
13071 (if org-priority-start-cycle-with-default
13072 org-default-priority
13073 (1- org-default-priority))))))
13074 ((eq action 'down)
13075 (setq new (if have
13076 (1+ current) ; normal cycling
13077 ;; last priority was empty
13078 (if (eq last-command this-command)
13079 org-highest-priority ; wrap around empty to highest
13080 ;; default
13081 (if org-priority-start-cycle-with-default
13082 org-default-priority
13083 (1+ org-default-priority))))))
13084 (t (error "Invalid action")))
13085 (if (or (< (upcase new) org-highest-priority)
13086 (> (upcase new) org-lowest-priority))
13087 (if (and (memq action '(up down))
13088 (not have) (not (eq last-command this-command)))
13089 ;; `new' is from default priority
13090 (error
13091 "The default can not be set, see `org-default-priority' why")
13092 ;; normal cycling: `new' is beyond highest/lowest priority
13093 ;; and is wrapped around to the empty priority
13094 (setq remove t)))
13095 (setq news (format "%c" new))
13096 (if have
13097 (if remove
13098 (replace-match "" t t nil 1)
13099 (replace-match news t t nil 2))
13100 (if remove
13101 (error "No priority cookie found in line")
13102 (let ((case-fold-search nil))
13103 (looking-at org-todo-line-regexp))
13104 (if (match-end 2)
13105 (progn
13106 (goto-char (match-end 2))
13107 (insert " [#" news "]"))
13108 (goto-char (match-beginning 3))
13109 (insert "[#" news "] "))))
13110 (org-preserve-lc (org-set-tags nil 'align)))
13111 (if remove
13112 (message "Priority removed")
13113 (message "Priority of current item set to %s" news))))
13115 (defun org-get-priority (s)
13116 "Find priority cookie and return priority."
13117 (if (functionp org-get-priority-function)
13118 (funcall org-get-priority-function)
13119 (save-match-data
13120 (if (not (string-match org-priority-regexp s))
13121 (* 1000 (- org-lowest-priority org-default-priority))
13122 (* 1000 (- org-lowest-priority
13123 (string-to-char (match-string 2 s))))))))
13125 ;;;; Tags
13127 (defvar org-agenda-archives-mode)
13128 (defvar org-map-continue-from nil
13129 "Position from where mapping should continue.
13130 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13132 (defvar org-scanner-tags nil
13133 "The current tag list while the tags scanner is running.")
13134 (defvar org-trust-scanner-tags nil
13135 "Should `org-get-tags-at' use the tags for the scanner.
13136 This is for internal dynamical scoping only.
13137 When this is non-nil, the function `org-get-tags-at' will return the value
13138 of `org-scanner-tags' instead of building the list by itself. This
13139 can lead to large speed-ups when the tags scanner is used in a file with
13140 many entries, and when the list of tags is retrieved, for example to
13141 obtain a list of properties. Building the tags list for each entry in such
13142 a file becomes an N^2 operation - but with this variable set, it scales
13143 as N.")
13145 (defun org-scan-tags (action matcher todo-only &optional start-level)
13146 "Scan headline tags with inheritance and produce output ACTION.
13148 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13149 or `agenda' to produce an entry list for an agenda view. It can also be
13150 a Lisp form or a function that should be called at each matched headline, in
13151 this case the return value is a list of all return values from these calls.
13153 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13154 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13155 only lines with a not-done TODO keyword are included in the output.
13156 This should be the same variable that was scoped into
13157 and set by `org-make-tags-matcher' when it constructed MATCHER.
13159 START-LEVEL can be a string with asterisks, reducing the scope to
13160 headlines matching this string."
13161 (require 'org-agenda)
13162 (let* ((re (concat "^"
13163 (if start-level
13164 ;; Get the correct level to match
13165 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13166 org-outline-regexp)
13167 " *\\(\\<\\("
13168 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13169 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13170 (props (list 'face 'default
13171 'done-face 'org-agenda-done
13172 'undone-face 'default
13173 'mouse-face 'highlight
13174 'org-not-done-regexp org-not-done-regexp
13175 'org-todo-regexp org-todo-regexp
13176 'org-complex-heading-regexp org-complex-heading-regexp
13177 'help-echo
13178 (format "mouse-2 or RET jump to org file %s"
13179 (abbreviate-file-name
13180 (or (buffer-file-name (buffer-base-buffer))
13181 (buffer-name (buffer-base-buffer)))))))
13182 (case-fold-search nil)
13183 (org-map-continue-from nil)
13184 lspos tags tags-list
13185 (tags-alist (list (cons 0 org-file-tags)))
13186 (llast 0) rtn rtn1 level category i txt
13187 todo marker entry priority)
13188 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13189 (setq action (list 'lambda nil action)))
13190 (save-excursion
13191 (goto-char (point-min))
13192 (when (eq action 'sparse-tree)
13193 (org-overview)
13194 (org-remove-occur-highlights))
13195 (while (re-search-forward re nil t)
13196 (setq org-map-continue-from nil)
13197 (catch :skip
13198 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13199 tags (if (match-end 4) (org-match-string-no-properties 4)))
13200 (goto-char (setq lspos (match-beginning 0)))
13201 (setq level (org-reduced-level (funcall outline-level))
13202 category (org-get-category))
13203 (setq i llast llast level)
13204 ;; remove tag lists from same and sublevels
13205 (while (>= i level)
13206 (when (setq entry (assoc i tags-alist))
13207 (setq tags-alist (delete entry tags-alist)))
13208 (setq i (1- i)))
13209 ;; add the next tags
13210 (when tags
13211 (setq tags (org-split-string tags ":")
13212 tags-alist
13213 (cons (cons level tags) tags-alist)))
13214 ;; compile tags for current headline
13215 (setq tags-list
13216 (if org-use-tag-inheritance
13217 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13218 tags)
13219 org-scanner-tags tags-list)
13220 (when org-use-tag-inheritance
13221 (setcdr (car tags-alist)
13222 (mapcar (lambda (x)
13223 (setq x (copy-sequence x))
13224 (org-add-prop-inherited x))
13225 (cdar tags-alist))))
13226 (when (and tags org-use-tag-inheritance
13227 (or (not (eq t org-use-tag-inheritance))
13228 org-tags-exclude-from-inheritance))
13229 ;; selective inheritance, remove uninherited ones
13230 (setcdr (car tags-alist)
13231 (org-remove-uninherited-tags (cdar tags-alist))))
13232 (when (and
13234 ;; eval matcher only when the todo condition is OK
13235 (and (or (not todo-only) (member todo org-not-done-keywords))
13236 (let ((case-fold-search t) (org-trust-scanner-tags t))
13237 (eval matcher)))
13239 ;; Call the skipper, but return t if it does not skip,
13240 ;; so that the `and' form continues evaluating
13241 (progn
13242 (unless (eq action 'sparse-tree) (org-agenda-skip))
13245 ;; Check if timestamps are deselecting this entry
13246 (or (not todo-only)
13247 (and (member todo org-not-done-keywords)
13248 (or (not org-agenda-tags-todo-honor-ignore-options)
13249 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13251 ;; Extra check for the archive tag
13252 ;; FIXME: Does the skipper already do this????
13254 (not (member org-archive-tag tags-list))
13255 ;; we have an archive tag, should we use this anyway?
13256 (or (not org-agenda-skip-archived-trees)
13257 (and (eq action 'agenda) org-agenda-archives-mode))))
13259 ;; select this headline
13261 (cond
13262 ((eq action 'sparse-tree)
13263 (and org-highlight-sparse-tree-matches
13264 (org-get-heading) (match-end 0)
13265 (org-highlight-new-match
13266 (match-beginning 1) (match-end 1)))
13267 (org-show-context 'tags-tree))
13268 ((eq action 'agenda)
13269 (setq txt (org-agenda-format-item
13271 (concat
13272 (if (eq org-tags-match-list-sublevels 'indented)
13273 (make-string (1- level) ?.) "")
13274 (org-get-heading))
13275 category
13276 tags-list)
13277 priority (org-get-priority txt))
13278 (goto-char lspos)
13279 (setq marker (org-agenda-new-marker))
13280 (org-add-props txt props
13281 'org-marker marker 'org-hd-marker marker 'org-category category
13282 'todo-state todo
13283 'priority priority 'type "tagsmatch")
13284 (push txt rtn))
13285 ((functionp action)
13286 (setq org-map-continue-from nil)
13287 (save-excursion
13288 (setq rtn1 (funcall action))
13289 (push rtn1 rtn)))
13290 (t (error "Invalid action")))
13292 ;; if we are to skip sublevels, jump to end of subtree
13293 (unless org-tags-match-list-sublevels
13294 (org-end-of-subtree t)
13295 (backward-char 1))))
13296 ;; Get the correct position from where to continue
13297 (if org-map-continue-from
13298 (goto-char org-map-continue-from)
13299 (and (= (point) lspos) (end-of-line 1)))))
13300 (when (and (eq action 'sparse-tree)
13301 (not org-sparse-tree-open-archived-trees))
13302 (org-hide-archived-subtrees (point-min) (point-max)))
13303 (nreverse rtn)))
13305 (defun org-remove-uninherited-tags (tags)
13306 "Remove all tags that are not inherited from the list TAGS."
13307 (cond
13308 ((eq org-use-tag-inheritance t)
13309 (if org-tags-exclude-from-inheritance
13310 (org-delete-all org-tags-exclude-from-inheritance tags)
13311 tags))
13312 ((not org-use-tag-inheritance) nil)
13313 ((stringp org-use-tag-inheritance)
13314 (delq nil (mapcar
13315 (lambda (x)
13316 (if (and (string-match org-use-tag-inheritance x)
13317 (not (member x org-tags-exclude-from-inheritance)))
13318 x nil))
13319 tags)))
13320 ((listp org-use-tag-inheritance)
13321 (delq nil (mapcar
13322 (lambda (x)
13323 (if (member x org-use-tag-inheritance) x nil))
13324 tags)))))
13326 (defun org-match-sparse-tree (&optional todo-only match)
13327 "Create a sparse tree according to tags string MATCH.
13328 MATCH can contain positive and negative selection of tags, like
13329 \"+WORK+URGENT-WITHBOSS\".
13330 If optional argument TODO-ONLY is non-nil, only select lines that are
13331 also TODO lines."
13332 (interactive "P")
13333 (org-agenda-prepare-buffers (list (current-buffer)))
13334 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13336 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13338 (defvar org-cached-props nil)
13339 (defun org-cached-entry-get (pom property)
13340 (if (or (eq t org-use-property-inheritance)
13341 (and (stringp org-use-property-inheritance)
13342 (string-match org-use-property-inheritance property))
13343 (and (listp org-use-property-inheritance)
13344 (member property org-use-property-inheritance)))
13345 ;; Caching is not possible, check it directly
13346 (org-entry-get pom property 'inherit)
13347 ;; Get all properties, so that we can do complicated checks easily
13348 (cdr (assoc property (or org-cached-props
13349 (setq org-cached-props
13350 (org-entry-properties pom)))))))
13352 (defun org-global-tags-completion-table (&optional files)
13353 "Return the list of all tags in all agenda buffer/files.
13354 Optional FILES argument is a list of files which can be used
13355 instead of the agenda files."
13356 (save-excursion
13357 (org-uniquify
13358 (delq nil
13359 (apply 'append
13360 (mapcar
13361 (lambda (file)
13362 (set-buffer (find-file-noselect file))
13363 (append (org-get-buffer-tags)
13364 (mapcar (lambda (x) (if (stringp (car-safe x))
13365 (list (car-safe x)) nil))
13366 org-tag-alist)))
13367 (if (and files (car files))
13368 files
13369 (org-agenda-files))))))))
13371 (defun org-make-tags-matcher (match)
13372 "Create the TAGS/TODO matcher form for the selection string MATCH.
13374 The variable `todo-only' is scoped dynamically into this function.
13375 It will be set to t if the matcher restricts matching to TODO entries,
13376 otherwise will not be touched.
13378 Returns a cons of the selection string MATCH and the constructed
13379 lisp form implementing the matcher. The matcher is to be evaluated
13380 at an Org entry, with point on the headline, and returns t if the
13381 entry matches the selection string MATCH. The returned lisp form
13382 references two variables with information about the entry, which
13383 must be bound around the form's evaluation: todo, the TODO keyword
13384 at the entry (or nil of none); and tags-list, the list of all tags
13385 at the entry including inherited ones. Additionally, the category
13386 of the entry (if any) must be specified as the text property
13387 'org-category on the headline.
13389 See also `org-scan-tags'.
13391 (declare (special todo-only))
13392 (unless (boundp 'todo-only)
13393 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13394 (unless match
13395 ;; Get a new match request, with completion
13396 (let ((org-last-tags-completion-table
13397 (org-global-tags-completion-table)))
13398 (setq match (org-completing-read-no-i
13399 "Match: " 'org-tags-completion-function nil nil nil
13400 'org-tags-history))))
13402 ;; Parse the string and create a lisp form
13403 (let ((match0 match)
13404 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13405 minus tag mm
13406 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13407 orterms term orlist re-p str-p level-p level-op time-p
13408 prop-p pn pv po gv rest)
13409 (if (string-match "/+" match)
13410 ;; match contains also a todo-matching request
13411 (progn
13412 (setq tagsmatch (substring match 0 (match-beginning 0))
13413 todomatch (substring match (match-end 0)))
13414 (if (string-match "^!" todomatch)
13415 (setq todo-only t todomatch (substring todomatch 1)))
13416 (if (string-match "^\\s-*$" todomatch)
13417 (setq todomatch nil)))
13418 ;; only matching tags
13419 (setq tagsmatch match todomatch nil))
13421 ;; Make the tags matcher
13422 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13423 (setq tagsmatcher t)
13424 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13425 (while (setq term (pop orterms))
13426 (while (and (equal (substring term -1) "\\") orterms)
13427 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13428 (while (string-match re term)
13429 (setq rest (substring term (match-end 0))
13430 minus (and (match-end 1)
13431 (equal (match-string 1 term) "-"))
13432 tag (save-match-data (replace-regexp-in-string
13433 "\\\\-" "-"
13434 (match-string 2 term)))
13435 re-p (equal (string-to-char tag) ?{)
13436 level-p (match-end 4)
13437 prop-p (match-end 5)
13438 mm (cond
13439 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13440 (level-p
13441 (setq level-op (org-op-to-function (match-string 3 term)))
13442 `(,level-op level ,(string-to-number
13443 (match-string 4 term))))
13444 (prop-p
13445 (setq pn (match-string 5 term)
13446 po (match-string 6 term)
13447 pv (match-string 7 term)
13448 re-p (equal (string-to-char pv) ?{)
13449 str-p (equal (string-to-char pv) ?\")
13450 time-p (save-match-data
13451 (string-match "^\"[[<].*[]>]\"$" pv))
13452 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13453 (if time-p (setq pv (org-matcher-time pv)))
13454 (setq po (org-op-to-function po (if time-p 'time str-p)))
13455 (cond
13456 ((equal pn "CATEGORY")
13457 (setq gv '(get-text-property (point) 'org-category)))
13458 ((equal pn "TODO")
13459 (setq gv 'todo))
13461 (setq gv `(org-cached-entry-get nil ,pn))))
13462 (if re-p
13463 (if (eq po 'org<>)
13464 `(not (string-match ,pv (or ,gv "")))
13465 `(string-match ,pv (or ,gv "")))
13466 (if str-p
13467 `(,po (or ,gv "") ,pv)
13468 `(,po (string-to-number (or ,gv ""))
13469 ,(string-to-number pv) ))))
13470 (t `(member ,tag tags-list)))
13471 mm (if minus (list 'not mm) mm)
13472 term rest)
13473 (push mm tagsmatcher))
13474 (push (if (> (length tagsmatcher) 1)
13475 (cons 'and tagsmatcher)
13476 (car tagsmatcher))
13477 orlist)
13478 (setq tagsmatcher nil))
13479 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13480 (setq tagsmatcher
13481 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13482 ;; Make the todo matcher
13483 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13484 (setq todomatcher t)
13485 (setq orterms (org-split-string todomatch "|") orlist nil)
13486 (while (setq term (pop orterms))
13487 (while (string-match re term)
13488 (setq minus (and (match-end 1)
13489 (equal (match-string 1 term) "-"))
13490 kwd (match-string 2 term)
13491 re-p (equal (string-to-char kwd) ?{)
13492 term (substring term (match-end 0))
13493 mm (if re-p
13494 `(string-match ,(substring kwd 1 -1) todo)
13495 (list 'equal 'todo kwd))
13496 mm (if minus (list 'not mm) mm))
13497 (push mm todomatcher))
13498 (push (if (> (length todomatcher) 1)
13499 (cons 'and todomatcher)
13500 (car todomatcher))
13501 orlist)
13502 (setq todomatcher nil))
13503 (setq todomatcher (if (> (length orlist) 1)
13504 (cons 'or orlist) (car orlist))))
13506 ;; Return the string and lisp forms of the matcher
13507 (setq matcher (if todomatcher
13508 (list 'and tagsmatcher todomatcher)
13509 tagsmatcher))
13510 (when todo-only
13511 (setq matcher (list 'and '(member todo org-not-done-keywords)
13512 matcher)))
13513 (cons match0 matcher)))
13515 (defun org-op-to-function (op &optional stringp)
13516 "Turn an operator into the appropriate function."
13517 (setq op
13518 (cond
13519 ((equal op "<" ) '(< string< org-time<))
13520 ((equal op ">" ) '(> org-string> org-time>))
13521 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13522 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13523 ((member op '("=" "==")) '(= string= org-time=))
13524 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13525 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13527 (defun org<> (a b) (not (= a b)))
13528 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13529 (defun org-string>= (a b) (not (string< a b)))
13530 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13531 (defun org-string<> (a b) (not (string= a b)))
13532 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13533 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13534 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13535 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13536 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13537 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13538 (defun org-2ft (s)
13539 "Convert S to a floating point time.
13540 If S is already a number, just return it. If it is a string, parse
13541 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13542 (cond
13543 ((numberp s) s)
13544 ((stringp s)
13545 (condition-case nil
13546 (float-time (apply 'encode-time (org-parse-time-string s)))
13547 (error 0.)))
13548 (t 0.)))
13550 (defun org-time-today ()
13551 "Time in seconds today at 0:00.
13552 Returns the float number of seconds since the beginning of the
13553 epoch to the beginning of today (00:00)."
13554 (float-time (apply 'encode-time
13555 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13557 (defun org-matcher-time (s)
13558 "Interpret a time comparison value."
13559 (save-match-data
13560 (cond
13561 ((string= s "<now>") (float-time))
13562 ((string= s "<today>") (org-time-today))
13563 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13564 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13565 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13566 (+ (org-time-today)
13567 (* (string-to-number (match-string 1 s))
13568 (cdr (assoc (match-string 2 s)
13569 '(("d" . 86400.0) ("w" . 604800.0)
13570 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13571 (t (org-2ft s)))))
13573 (defun org-match-any-p (re list)
13574 "Does re match any element of list?"
13575 (setq list (mapcar (lambda (x) (string-match re x)) list))
13576 (delq nil list))
13578 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13579 (defvar org-tags-overlay (make-overlay 1 1))
13580 (org-detach-overlay org-tags-overlay)
13582 (defun org-get-local-tags-at (&optional pos)
13583 "Get a list of tags defined in the current headline."
13584 (org-get-tags-at pos 'local))
13586 (defun org-get-local-tags ()
13587 "Get a list of tags defined in the current headline."
13588 (org-get-tags-at nil 'local))
13590 (defun org-get-tags-at (&optional pos local)
13591 "Get a list of all headline tags applicable at POS.
13592 POS defaults to point. If tags are inherited, the list contains
13593 the targets in the same sequence as the headlines appear, i.e.
13594 the tags of the current headline come last.
13595 When LOCAL is non-nil, only return tags from the current headline,
13596 ignore inherited ones."
13597 (interactive)
13598 (if (and org-trust-scanner-tags
13599 (or (not pos) (equal pos (point)))
13600 (not local))
13601 org-scanner-tags
13602 (let (tags ltags lastpos parent)
13603 (save-excursion
13604 (save-restriction
13605 (widen)
13606 (goto-char (or pos (point)))
13607 (save-match-data
13608 (catch 'done
13609 (condition-case nil
13610 (progn
13611 (org-back-to-heading t)
13612 (while (not (equal lastpos (point)))
13613 (setq lastpos (point))
13614 (when (looking-at
13615 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13616 (setq ltags (org-split-string
13617 (org-match-string-no-properties 1) ":"))
13618 (when parent
13619 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13620 (setq tags (append
13621 (if parent
13622 (org-remove-uninherited-tags ltags)
13623 ltags)
13624 tags)))
13625 (or org-use-tag-inheritance (throw 'done t))
13626 (if local (throw 'done t))
13627 (or (org-up-heading-safe) (error nil))
13628 (setq parent t)))
13629 (error nil)))))
13630 (if local
13631 tags
13632 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13634 (defun org-add-prop-inherited (s)
13635 (add-text-properties 0 (length s) '(inherited t) s)
13638 (defun org-toggle-tag (tag &optional onoff)
13639 "Toggle the tag TAG for the current line.
13640 If ONOFF is `on' or `off', don't toggle but set to this state."
13641 (let (res current)
13642 (save-excursion
13643 (org-back-to-heading t)
13644 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13645 (point-at-eol) t)
13646 (progn
13647 (setq current (match-string 1))
13648 (replace-match ""))
13649 (setq current ""))
13650 (setq current (nreverse (org-split-string current ":")))
13651 (cond
13652 ((eq onoff 'on)
13653 (setq res t)
13654 (or (member tag current) (push tag current)))
13655 ((eq onoff 'off)
13656 (or (not (member tag current)) (setq current (delete tag current))))
13657 (t (if (member tag current)
13658 (setq current (delete tag current))
13659 (setq res t)
13660 (push tag current))))
13661 (end-of-line 1)
13662 (if current
13663 (progn
13664 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13665 (org-set-tags nil t))
13666 (delete-horizontal-space))
13667 (run-hooks 'org-after-tags-change-hook))
13668 res))
13670 (defun org-align-tags-here (to-col)
13671 ;; Assumes that this is a headline
13672 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13673 (beginning-of-line 1)
13674 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13675 (< pos (match-beginning 2)))
13676 (progn
13677 (setq tags-l (- (match-end 2) (match-beginning 2)))
13678 (goto-char (match-beginning 1))
13679 (insert " ")
13680 (delete-region (point) (1+ (match-beginning 2)))
13681 (setq ncol (max (current-column)
13682 (1+ col)
13683 (if (> to-col 0)
13684 to-col
13685 (- (abs to-col) tags-l))))
13686 (setq p (point))
13687 (insert (make-string (- ncol (current-column)) ?\ ))
13688 (setq ncol (current-column))
13689 (when indent-tabs-mode (tabify p (point-at-eol)))
13690 (org-move-to-column (min ncol col) t))
13691 (goto-char pos))))
13693 (defun org-set-tags-command (&optional arg just-align)
13694 "Call the set-tags command for the current entry."
13695 (interactive "P")
13696 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13697 (org-set-tags arg just-align)
13698 (save-excursion
13699 (org-back-to-heading t)
13700 (org-set-tags arg just-align))))
13702 (defun org-set-tags-to (data)
13703 "Set the tags of the current entry to DATA, replacing the current tags.
13704 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13705 If DATA is nil or the empty string, any tags will be removed."
13706 (interactive "sTags: ")
13707 (setq data
13708 (cond
13709 ((eq data nil) "")
13710 ((equal data "") "")
13711 ((stringp data)
13712 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13713 ":"))
13714 ((listp data)
13715 (concat ":" (mapconcat 'identity data ":") ":"))))
13716 (when data
13717 (save-excursion
13718 (org-back-to-heading t)
13719 (when (looking-at org-complex-heading-regexp)
13720 (if (match-end 5)
13721 (progn
13722 (goto-char (match-beginning 5))
13723 (insert data)
13724 (delete-region (point) (point-at-eol))
13725 (org-set-tags nil 'align))
13726 (goto-char (point-at-eol))
13727 (insert " " data)
13728 (org-set-tags nil 'align)))
13729 (beginning-of-line 1)
13730 (if (looking-at ".*?\\([ \t]+\\)$")
13731 (delete-region (match-beginning 1) (match-end 1))))))
13733 (defun org-align-all-tags ()
13734 "Align the tags i all headings."
13735 (interactive)
13736 (save-excursion
13737 (or (ignore-errors (org-back-to-heading t))
13738 (outline-next-heading))
13739 (if (org-at-heading-p)
13740 (org-set-tags t)
13741 (message "No headings"))))
13743 (defvar org-indent-indentation-per-level)
13744 (defun org-set-tags (&optional arg just-align)
13745 "Set the tags for the current headline.
13746 With prefix ARG, realign all tags in headings in the current buffer."
13747 (interactive "P")
13748 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13749 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13750 'region-start-level 'region))
13751 org-loop-over-headlines-in-active-region)
13752 (org-map-entries
13753 ;; We don't use ARG and JUST-ALIGN here these args are not
13754 ;; useful when looping over headlines
13755 `(org-set-tags)
13756 org-loop-over-headlines-in-active-region
13757 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13758 (let* ((re org-outline-regexp-bol)
13759 (current (unless arg (org-get-tags-string)))
13760 (col (current-column))
13761 (org-setting-tags t)
13762 table current-tags inherited-tags ; computed below when needed
13763 tags p0 c0 c1 rpl di tc level)
13764 (if arg
13765 (save-excursion
13766 (goto-char (point-min))
13767 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13768 (while (re-search-forward re nil t)
13769 (org-set-tags nil t)
13770 (end-of-line 1)))
13771 (message "All tags realigned to column %d" org-tags-column))
13772 (if just-align
13773 (setq tags current)
13774 ;; Get a new set of tags from the user
13775 (save-excursion
13776 (setq table (append org-tag-persistent-alist
13777 (or org-tag-alist (org-get-buffer-tags))
13778 (and
13779 org-complete-tags-always-offer-all-agenda-tags
13780 (org-global-tags-completion-table
13781 (org-agenda-files))))
13782 org-last-tags-completion-table table
13783 current-tags (org-split-string current ":")
13784 inherited-tags (nreverse
13785 (nthcdr (length current-tags)
13786 (nreverse (org-get-tags-at))))
13787 tags
13788 (if (or (eq t org-use-fast-tag-selection)
13789 (and org-use-fast-tag-selection
13790 (delq nil (mapcar 'cdr table))))
13791 (org-fast-tag-selection
13792 current-tags inherited-tags table
13793 (if org-fast-tag-selection-include-todo
13794 org-todo-key-alist))
13795 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13796 (org-trim
13797 (org-icompleting-read "Tags: "
13798 'org-tags-completion-function
13799 nil nil current 'org-tags-history))))))
13800 (while (string-match "[-+&]+" tags)
13801 ;; No boolean logic, just a list
13802 (setq tags (replace-match ":" t t tags))))
13804 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13806 (if org-tags-sort-function
13807 (setq tags (mapconcat 'identity
13808 (sort (org-split-string
13809 tags (org-re "[^[:alnum:]_@#%]+"))
13810 org-tags-sort-function) ":")))
13812 (if (string-match "\\`[\t ]*\\'" tags)
13813 (setq tags "")
13814 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13815 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13817 ;; Insert new tags at the correct column
13818 (beginning-of-line 1)
13819 (setq level (or (and (looking-at org-outline-regexp)
13820 (- (match-end 0) (point) 1))
13822 (cond
13823 ((and (equal current "") (equal tags "")))
13824 ((re-search-forward
13825 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13826 (point-at-eol) t)
13827 (if (equal tags "")
13828 (setq rpl "")
13829 (goto-char (match-beginning 0))
13830 (setq c0 (current-column)
13831 ;; compute offset for the case of org-indent-mode active
13832 di (if org-indent-mode
13833 (* (1- org-indent-indentation-per-level) (1- level))
13835 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13836 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13837 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13838 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13839 (replace-match rpl t t)
13840 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13841 tags)
13842 (t (error "Tags alignment failed")))
13843 (org-move-to-column col)
13844 (unless just-align
13845 (run-hooks 'org-after-tags-change-hook))))))
13847 (defun org-change-tag-in-region (beg end tag off)
13848 "Add or remove TAG for each entry in the region.
13849 This works in the agenda, and also in an org-mode buffer."
13850 (interactive
13851 (list (region-beginning) (region-end)
13852 (let ((org-last-tags-completion-table
13853 (if (derived-mode-p 'org-mode)
13854 (org-get-buffer-tags)
13855 (org-global-tags-completion-table))))
13856 (org-icompleting-read
13857 "Tag: " 'org-tags-completion-function nil nil nil
13858 'org-tags-history))
13859 (progn
13860 (message "[s]et or [r]emove? ")
13861 (equal (read-char-exclusive) ?r))))
13862 (if (fboundp 'deactivate-mark) (deactivate-mark))
13863 (let ((agendap (equal major-mode 'org-agenda-mode))
13864 l1 l2 m buf pos newhead (cnt 0))
13865 (goto-char end)
13866 (setq l2 (1- (org-current-line)))
13867 (goto-char beg)
13868 (setq l1 (org-current-line))
13869 (loop for l from l1 to l2 do
13870 (org-goto-line l)
13871 (setq m (get-text-property (point) 'org-hd-marker))
13872 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13873 (and agendap m))
13874 (setq buf (if agendap (marker-buffer m) (current-buffer))
13875 pos (if agendap m (point)))
13876 (with-current-buffer buf
13877 (save-excursion
13878 (save-restriction
13879 (goto-char pos)
13880 (setq cnt (1+ cnt))
13881 (org-toggle-tag tag (if off 'off 'on))
13882 (setq newhead (org-get-heading)))))
13883 (and agendap (org-agenda-change-all-lines newhead m))))
13884 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13886 (defun org-tags-completion-function (string predicate &optional flag)
13887 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13888 (confirm (lambda (x) (stringp (car x)))))
13889 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13890 (setq s1 (match-string 1 string)
13891 s2 (match-string 2 string))
13892 (setq s1 "" s2 string))
13893 (cond
13894 ((eq flag nil)
13895 ;; try completion
13896 (setq rtn (try-completion s2 ctable confirm))
13897 (if (stringp rtn)
13898 (setq rtn
13899 (concat s1 s2 (substring rtn (length s2))
13900 (if (and org-add-colon-after-tag-completion
13901 (assoc rtn ctable))
13902 ":" ""))))
13903 rtn)
13904 ((eq flag t)
13905 ;; all-completions
13906 (all-completions s2 ctable confirm)
13908 ((eq flag 'lambda)
13909 ;; exact match?
13910 (assoc s2 ctable)))
13913 (defun org-fast-tag-insert (kwd tags face &optional end)
13914 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13915 (insert (format "%-12s" (concat kwd ":"))
13916 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13917 (or end "")))
13919 (defun org-fast-tag-show-exit (flag)
13920 (save-excursion
13921 (org-goto-line 3)
13922 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13923 (replace-match ""))
13924 (when flag
13925 (end-of-line 1)
13926 (org-move-to-column (- (window-width) 19) t)
13927 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13929 (defun org-set-current-tags-overlay (current prefix)
13930 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13931 (if (featurep 'xemacs)
13932 (org-overlay-display org-tags-overlay (concat prefix s)
13933 'secondary-selection)
13934 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13935 (org-overlay-display org-tags-overlay (concat prefix s)))))
13937 (defvar org-last-tag-selection-key nil)
13938 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13939 "Fast tag selection with single keys.
13940 CURRENT is the current list of tags in the headline, INHERITED is the
13941 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13942 possibly with grouping information. TODO-TABLE is a similar table with
13943 TODO keywords, should these have keys assigned to them.
13944 If the keys are nil, a-z are automatically assigned.
13945 Returns the new tags string, or nil to not change the current settings."
13946 (let* ((fulltable (append table todo-table))
13947 (maxlen (apply 'max (mapcar
13948 (lambda (x)
13949 (if (stringp (car x)) (string-width (car x)) 0))
13950 fulltable)))
13951 (buf (current-buffer))
13952 (expert (eq org-fast-tag-selection-single-key 'expert))
13953 (buffer-tags nil)
13954 (fwidth (+ maxlen 3 1 3))
13955 (ncol (/ (- (window-width) 4) fwidth))
13956 (i-face 'org-done)
13957 (c-face 'org-todo)
13958 tg cnt e c char c1 c2 ntable tbl rtn
13959 ov-start ov-end ov-prefix
13960 (exit-after-next org-fast-tag-selection-single-key)
13961 (done-keywords org-done-keywords)
13962 groups ingroup)
13963 (save-excursion
13964 (beginning-of-line 1)
13965 (if (looking-at
13966 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13967 (setq ov-start (match-beginning 1)
13968 ov-end (match-end 1)
13969 ov-prefix "")
13970 (setq ov-start (1- (point-at-eol))
13971 ov-end (1+ ov-start))
13972 (skip-chars-forward "^\n\r")
13973 (setq ov-prefix
13974 (concat
13975 (buffer-substring (1- (point)) (point))
13976 (if (> (current-column) org-tags-column)
13978 (make-string (- org-tags-column (current-column)) ?\ ))))))
13979 (move-overlay org-tags-overlay ov-start ov-end)
13980 (save-window-excursion
13981 (if expert
13982 (set-buffer (get-buffer-create " *Org tags*"))
13983 (delete-other-windows)
13984 (split-window-vertically)
13985 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13986 (erase-buffer)
13987 (org-set-local 'org-done-keywords done-keywords)
13988 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13989 (org-fast-tag-insert "Current" current c-face "\n\n")
13990 (org-fast-tag-show-exit exit-after-next)
13991 (org-set-current-tags-overlay current ov-prefix)
13992 (setq tbl fulltable char ?a cnt 0)
13993 (while (setq e (pop tbl))
13994 (cond
13995 ((equal (car e) :startgroup)
13996 (push '() groups) (setq ingroup t)
13997 (when (not (= cnt 0))
13998 (setq cnt 0)
13999 (insert "\n"))
14000 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14001 ((equal (car e) :endgroup)
14002 (setq ingroup nil cnt 0)
14003 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14004 ((equal e '(:newline))
14005 (when (not (= cnt 0))
14006 (setq cnt 0)
14007 (insert "\n")
14008 (setq e (car tbl))
14009 (while (equal (car tbl) '(:newline))
14010 (insert "\n")
14011 (setq tbl (cdr tbl)))))
14013 (setq tg (copy-sequence (car e)) c2 nil)
14014 (if (cdr e)
14015 (setq c (cdr e))
14016 ;; automatically assign a character.
14017 (setq c1 (string-to-char
14018 (downcase (substring
14019 tg (if (= (string-to-char tg) ?@) 1 0)))))
14020 (if (or (rassoc c1 ntable) (rassoc c1 table))
14021 (while (or (rassoc char ntable) (rassoc char table))
14022 (setq char (1+ char)))
14023 (setq c2 c1))
14024 (setq c (or c2 char)))
14025 (if ingroup (push tg (car groups)))
14026 (setq tg (org-add-props tg nil 'face
14027 (cond
14028 ((not (assoc tg table))
14029 (org-get-todo-face tg))
14030 ((member tg current) c-face)
14031 ((member tg inherited) i-face))))
14032 (if (and (= cnt 0) (not ingroup)) (insert " "))
14033 (insert "[" c "] " tg (make-string
14034 (- fwidth 4 (length tg)) ?\ ))
14035 (push (cons tg c) ntable)
14036 (when (= (setq cnt (1+ cnt)) ncol)
14037 (insert "\n")
14038 (if ingroup (insert " "))
14039 (setq cnt 0)))))
14040 (setq ntable (nreverse ntable))
14041 (insert "\n")
14042 (goto-char (point-min))
14043 (if (not expert) (org-fit-window-to-buffer))
14044 (setq rtn
14045 (catch 'exit
14046 (while t
14047 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14048 (if (not groups) "no " "")
14049 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14050 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14051 (setq org-last-tag-selection-key c)
14052 (cond
14053 ((= c ?\r) (throw 'exit t))
14054 ((= c ?!)
14055 (setq groups (not groups))
14056 (goto-char (point-min))
14057 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14058 ((= c ?\C-c)
14059 (if (not expert)
14060 (org-fast-tag-show-exit
14061 (setq exit-after-next (not exit-after-next)))
14062 (setq expert nil)
14063 (delete-other-windows)
14064 (set-window-buffer (split-window-vertically) " *Org tags*")
14065 (org-switch-to-buffer-other-window " *Org tags*")
14066 (org-fit-window-to-buffer)))
14067 ((or (= c ?\C-g)
14068 (and (= c ?q) (not (rassoc c ntable))))
14069 (org-detach-overlay org-tags-overlay)
14070 (setq quit-flag t))
14071 ((= c ?\ )
14072 (setq current nil)
14073 (if exit-after-next (setq exit-after-next 'now)))
14074 ((= c ?\t)
14075 (condition-case nil
14076 (setq tg (org-icompleting-read
14077 "Tag: "
14078 (or buffer-tags
14079 (with-current-buffer buf
14080 (org-get-buffer-tags)))))
14081 (quit (setq tg "")))
14082 (when (string-match "\\S-" tg)
14083 (add-to-list 'buffer-tags (list tg))
14084 (if (member tg current)
14085 (setq current (delete tg current))
14086 (push tg current)))
14087 (if exit-after-next (setq exit-after-next 'now)))
14088 ((setq e (rassoc c todo-table) tg (car e))
14089 (with-current-buffer buf
14090 (save-excursion (org-todo tg)))
14091 (if exit-after-next (setq exit-after-next 'now)))
14092 ((setq e (rassoc c ntable) tg (car e))
14093 (if (member tg current)
14094 (setq current (delete tg current))
14095 (loop for g in groups do
14096 (if (member tg g)
14097 (mapc (lambda (x)
14098 (setq current (delete x current)))
14099 g)))
14100 (push tg current))
14101 (if exit-after-next (setq exit-after-next 'now))))
14103 ;; Create a sorted list
14104 (setq current
14105 (sort current
14106 (lambda (a b)
14107 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14108 (if (eq exit-after-next 'now) (throw 'exit t))
14109 (goto-char (point-min))
14110 (beginning-of-line 2)
14111 (delete-region (point) (point-at-eol))
14112 (org-fast-tag-insert "Current" current c-face)
14113 (org-set-current-tags-overlay current ov-prefix)
14114 (while (re-search-forward
14115 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14116 (setq tg (match-string 1))
14117 (add-text-properties
14118 (match-beginning 1) (match-end 1)
14119 (list 'face
14120 (cond
14121 ((member tg current) c-face)
14122 ((member tg inherited) i-face)
14123 (t (get-text-property (match-beginning 1) 'face))))))
14124 (goto-char (point-min)))))
14125 (org-detach-overlay org-tags-overlay)
14126 (if rtn
14127 (mapconcat 'identity current ":")
14128 nil))))
14130 (defun org-get-tags-string ()
14131 "Get the TAGS string in the current headline."
14132 (unless (org-at-heading-p t)
14133 (error "Not on a heading"))
14134 (save-excursion
14135 (beginning-of-line 1)
14136 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14137 (org-match-string-no-properties 1)
14138 "")))
14140 (defun org-get-tags ()
14141 "Get the list of tags specified in the current headline."
14142 (org-split-string (org-get-tags-string) ":"))
14144 (defun org-get-buffer-tags ()
14145 "Get a table of all tags used in the buffer, for completion."
14146 (let (tags)
14147 (save-excursion
14148 (goto-char (point-min))
14149 (while (re-search-forward
14150 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14151 (when (equal (char-after (point-at-bol 0)) ?*)
14152 (mapc (lambda (x) (add-to-list 'tags x))
14153 (org-split-string (org-match-string-no-properties 1) ":")))))
14154 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14155 (mapcar 'list tags)))
14157 ;;;; The mapping API
14159 ;;;###autoload
14160 (defun org-map-entries (func &optional match scope &rest skip)
14161 "Call FUNC at each headline selected by MATCH in SCOPE.
14163 FUNC is a function or a lisp form. The function will be called without
14164 arguments, with the cursor positioned at the beginning of the headline.
14165 The return values of all calls to the function will be collected and
14166 returned as a list.
14168 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14169 does not need to preserve point. After evaluation, the cursor will be
14170 moved to the end of the line (presumably of the headline of the
14171 processed entry) and search continues from there. Under some
14172 circumstances, this may not produce the wanted results. For example,
14173 if you have removed (e.g. archived) the current (sub)tree it could
14174 mean that the next entry will be skipped entirely. In such cases, you
14175 can specify the position from where search should continue by making
14176 FUNC set the variable `org-map-continue-from' to the desired buffer
14177 position.
14179 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14180 Only headlines that are matched by this query will be considered during
14181 the iteration. When MATCH is nil or t, all headlines will be
14182 visited by the iteration.
14184 SCOPE determines the scope of this command. It can be any of:
14186 nil The current buffer, respecting the restriction if any
14187 tree The subtree started with the entry at point
14188 region The entries within the active region, if any
14189 region-start-level
14190 The entries within the active region, but only those at
14191 the same level than the first one.
14192 file The current buffer, without restriction
14193 file-with-archives
14194 The current buffer, and any archives associated with it
14195 agenda All agenda files
14196 agenda-with-archives
14197 All agenda files with any archive files associated with them
14198 \(file1 file2 ...)
14199 If this is a list, all files in the list will be scanned
14201 The remaining args are treated as settings for the skipping facilities of
14202 the scanner. The following items can be given here:
14204 archive skip trees with the archive tag.
14205 comment skip trees with the COMMENT keyword
14206 function or Emacs Lisp form:
14207 will be used as value for `org-agenda-skip-function', so whenever
14208 the function returns t, FUNC will not be called for that
14209 entry and search will continue from the point where the
14210 function leaves it.
14212 If your function needs to retrieve the tags including inherited tags
14213 at the *current* entry, you can use the value of the variable
14214 `org-scanner-tags' which will be much faster than getting the value
14215 with `org-get-tags-at'. If your function gets properties with
14216 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14217 to t around the call to `org-entry-properties' to get the same speedup.
14218 Note that if your function moves around to retrieve tags and properties at
14219 a *different* entry, you cannot use these techniques."
14220 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14221 (not (org-region-active-p)))
14222 (let* ((org-agenda-archives-mode nil) ; just to make sure
14223 (org-agenda-skip-archived-trees (memq 'archive skip))
14224 (org-agenda-skip-comment-trees (memq 'comment skip))
14225 (org-agenda-skip-function
14226 (car (org-delete-all '(comment archive) skip)))
14227 (org-tags-match-list-sublevels t)
14228 (start-level (eq scope 'region-start-level))
14229 matcher file res
14230 org-todo-keywords-for-agenda
14231 org-done-keywords-for-agenda
14232 org-todo-keyword-alist-for-agenda
14233 org-drawers-for-agenda
14234 org-tag-alist-for-agenda
14235 todo-only)
14237 (cond
14238 ((eq match t) (setq matcher t))
14239 ((eq match nil) (setq matcher t))
14240 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14242 (save-excursion
14243 (save-restriction
14244 (cond ((eq scope 'tree)
14245 (org-back-to-heading t)
14246 (org-narrow-to-subtree)
14247 (setq scope nil))
14248 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14249 (org-region-active-p))
14250 ;; If needed, set start-level to a string like "2"
14251 (when start-level
14252 (save-excursion
14253 (goto-char (region-beginning))
14254 (unless (org-at-heading-p) (outline-next-heading))
14255 (setq start-level (org-current-level))))
14256 (narrow-to-region (region-beginning)
14257 (save-excursion
14258 (goto-char (region-end))
14259 (unless (and (bolp) (org-at-heading-p))
14260 (outline-next-heading))
14261 (point)))
14262 (setq scope nil)))
14264 (if (not scope)
14265 (progn
14266 (org-agenda-prepare-buffers
14267 (list (buffer-file-name (current-buffer))))
14268 (setq res (org-scan-tags func matcher todo-only start-level)))
14269 ;; Get the right scope
14270 (cond
14271 ((and scope (listp scope) (symbolp (car scope)))
14272 (setq scope (eval scope)))
14273 ((eq scope 'agenda)
14274 (setq scope (org-agenda-files t)))
14275 ((eq scope 'agenda-with-archives)
14276 (setq scope (org-agenda-files t))
14277 (setq scope (org-add-archive-files scope)))
14278 ((eq scope 'file)
14279 (setq scope (list (buffer-file-name))))
14280 ((eq scope 'file-with-archives)
14281 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14282 (org-agenda-prepare-buffers scope)
14283 (while (setq file (pop scope))
14284 (with-current-buffer (org-find-base-buffer-visiting file)
14285 (save-excursion
14286 (save-restriction
14287 (widen)
14288 (goto-char (point-min))
14289 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14290 res)))
14292 ;;;; Properties
14294 ;;; Setting and retrieving properties
14296 (defconst org-special-properties
14297 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14298 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14299 "The special properties valid in Org-mode.
14301 These are properties that are not defined in the property drawer,
14302 but in some other way.")
14304 (defconst org-default-properties
14305 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14306 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14307 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14308 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14309 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14310 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14311 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14312 "Some properties that are used by Org-mode for various purposes.
14313 Being in this list makes sure that they are offered for completion.")
14315 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14316 "Regular expression matching the first line of a property drawer.")
14318 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14319 "Regular expression matching the last line of a property drawer.")
14321 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14322 "Regular expression matching the first line of a property drawer.")
14324 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14325 "Regular expression matching the first line of a property drawer.")
14327 (defconst org-property-drawer-re
14328 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14329 org-property-end-re "\\)\n?")
14330 "Matches an entire property drawer.")
14332 (defconst org-clock-drawer-re
14333 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14334 org-property-end-re "\\)\n?")
14335 "Matches an entire clock drawer.")
14337 (defsubst org-re-property (property)
14338 "Return a regexp matching a PROPERTY line.
14339 Match group 1 will be set to the value."
14340 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14342 (defsubst org-re-property-keyword (property)
14343 "Return a regexp matching a PROPERTY line, possibly with no
14344 value for the property."
14345 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14347 (defun org-property-action ()
14348 "Do an action on properties."
14349 (interactive)
14350 (let (c)
14351 (org-at-property-p)
14352 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14353 (setq c (read-char-exclusive))
14354 (cond
14355 ((equal c ?s)
14356 (call-interactively 'org-set-property))
14357 ((equal c ?d)
14358 (call-interactively 'org-delete-property))
14359 ((equal c ?D)
14360 (call-interactively 'org-delete-property-globally))
14361 ((equal c ?c)
14362 (call-interactively 'org-compute-property-at-point))
14363 (t (error "No such property action %c" c)))))
14365 (defun org-inc-effort ()
14366 "Increment the value of the effort property in the current entry."
14367 (interactive)
14368 (org-set-effort nil t))
14370 (defun org-set-effort (&optional value increment)
14371 "Set the effort property of the current entry.
14372 With numerical prefix arg, use the nth allowed value, 0 stands for the
14373 10th allowed value.
14375 When INCREMENT is non-nil, set the property to the next allowed value."
14376 (interactive "P")
14377 (if (equal value 0) (setq value 10))
14378 (let* ((completion-ignore-case t)
14379 (prop org-effort-property)
14380 (cur (org-entry-get nil prop))
14381 (allowed (org-property-get-allowed-values nil prop 'table))
14382 (existing (mapcar 'list (org-property-values prop)))
14384 (val (cond
14385 ((stringp value) value)
14386 ((and allowed (integerp value))
14387 (or (car (nth (1- value) allowed))
14388 (car (org-last allowed))))
14389 ((and allowed increment)
14390 (or (caadr (member (list cur) allowed))
14391 (error "Allowed effort values are not set")))
14392 (allowed
14393 (message "Select 1-9,0, [RET%s]: %s"
14394 (if cur (concat "=" cur) "")
14395 (mapconcat 'car allowed " "))
14396 (setq rpl (read-char-exclusive))
14397 (if (equal rpl ?\r)
14399 (setq rpl (- rpl ?0))
14400 (if (equal rpl 0) (setq rpl 10))
14401 (if (and (> rpl 0) (<= rpl (length allowed)))
14402 (car (nth (1- rpl) allowed))
14403 (org-completing-read "Effort: " allowed nil))))
14405 (let (org-completion-use-ido org-completion-use-iswitchb)
14406 (org-completing-read
14407 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14408 (concat "[" cur "]") "")
14409 ": ")
14410 existing nil nil "" nil cur))))))
14411 (unless (equal (org-entry-get nil prop) val)
14412 (org-entry-put nil prop val))
14413 (message "%s is now %s" prop val)))
14415 (defun org-at-property-p ()
14416 "Is cursor inside a property drawer?"
14417 (save-excursion
14418 (beginning-of-line 1)
14419 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14420 (save-match-data ;; Used by calling procedures
14421 (let ((p (point))
14422 (range (unless (org-before-first-heading-p)
14423 (org-get-property-block))))
14424 (and range (<= (car range) p) (< p (cdr range))))))))
14426 (defun org-get-property-block (&optional beg end force)
14427 "Return the (beg . end) range of the body of the property drawer.
14428 BEG and END are the beginning and end of the current subtree, or of
14429 the part before the first headline. If they are not given, they will
14430 be found. If the drawer does not exist and FORCE is non-nil, create
14431 the drawer."
14432 (catch 'exit
14433 (save-excursion
14434 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14435 (progn (org-back-to-heading t) (point))))
14436 (end (or end (and (not (outline-next-heading)) (point-max))
14437 (point))))
14438 (goto-char beg)
14439 (if (re-search-forward org-property-start-re end t)
14440 (setq beg (1+ (match-end 0)))
14441 (if force
14442 (save-excursion
14443 (org-insert-property-drawer)
14444 (setq end (progn (outline-next-heading) (point))))
14445 (throw 'exit nil))
14446 (goto-char beg)
14447 (if (re-search-forward org-property-start-re end t)
14448 (setq beg (1+ (match-end 0)))))
14449 (if (re-search-forward org-property-end-re end t)
14450 (setq end (match-beginning 0))
14451 (or force (throw 'exit nil))
14452 (goto-char beg)
14453 (setq end beg)
14454 (org-indent-line)
14455 (insert ":END:\n"))
14456 (cons beg end)))))
14458 (defun org-entry-properties (&optional pom which specific)
14459 "Get all properties of the entry at point-or-marker POM.
14460 This includes the TODO keyword, the tags, time strings for deadline,
14461 scheduled, and clocking, and any additional properties defined in the
14462 entry. The return value is an alist, keys may occur multiple times
14463 if the property key was used several times.
14464 POM may also be nil, in which case the current entry is used.
14465 If WHICH is nil or `all', get all properties. If WHICH is
14466 `special' or `standard', only get that subclass. If WHICH
14467 is a string only get exactly this property. SPECIFIC can be a string, the
14468 specific property we are interested in. Specifying it can speed
14469 things up because then unnecessary parsing is avoided."
14470 (setq which (or which 'all))
14471 (org-with-point-at pom
14472 (let ((clockstr (substring org-clock-string 0 -1))
14473 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14474 (case-fold-search nil)
14475 beg end range props sum-props key key1 value string clocksum clocksumt)
14476 (save-excursion
14477 (when (condition-case nil
14478 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14479 (error nil))
14480 (setq beg (point))
14481 (setq sum-props (get-text-property (point) 'org-summaries))
14482 (setq clocksum (get-text-property (point) :org-clock-minutes)
14483 clocksumt (get-text-property (point) :org-clock-minutes-today))
14484 (outline-next-heading)
14485 (setq end (point))
14486 (when (memq which '(all special))
14487 ;; Get the special properties, like TODO and tags
14488 (goto-char beg)
14489 (when (and (or (not specific) (string= specific "TODO"))
14490 (looking-at org-todo-line-regexp) (match-end 2))
14491 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14492 (when (and (or (not specific) (string= specific "PRIORITY"))
14493 (looking-at org-priority-regexp))
14494 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14495 (when (or (not specific) (string= specific "FILE"))
14496 (push (cons "FILE" buffer-file-name) props))
14497 (when (and (or (not specific) (string= specific "TAGS"))
14498 (setq value (org-get-tags-string))
14499 (string-match "\\S-" value))
14500 (push (cons "TAGS" value) props))
14501 (when (and (or (not specific) (string= specific "ALLTAGS"))
14502 (setq value (org-get-tags-at)))
14503 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14504 ":"))
14505 props))
14506 (when (or (not specific) (string= specific "BLOCKED"))
14507 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14508 (when (or (not specific)
14509 (member specific
14510 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14511 "TIMESTAMP" "TIMESTAMP_IA")))
14512 (catch 'match
14513 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14514 (setq key (if (match-end 1)
14515 (substring (org-match-string-no-properties 1)
14516 0 -1))
14517 string (if (equal key clockstr)
14518 (org-trim
14519 (buffer-substring-no-properties
14520 (match-beginning 3) (goto-char
14521 (point-at-eol))))
14522 (substring (org-match-string-no-properties 3)
14523 1 -1)))
14524 ;; Get the correct property name from the key. This is
14525 ;; necessary if the user has configured time keywords.
14526 (setq key1 (concat key ":"))
14527 (cond
14528 ((not key)
14529 (setq key
14530 (if (= (char-after (match-beginning 3)) ?\[)
14531 "TIMESTAMP_IA" "TIMESTAMP")))
14532 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14533 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14534 ((equal key1 org-closed-string) (setq key "CLOSED"))
14535 ((equal key1 org-clock-string) (setq key "CLOCK")))
14536 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14537 (progn
14538 (push (cons key string) props)
14539 ;; no need to search further if match is found
14540 (throw 'match t))
14541 (when (or (equal key "CLOCK") (not (assoc key props)))
14542 (push (cons key string) props)))))))
14544 (when (memq which '(all standard))
14545 ;; Get the standard properties, like :PROP: ...
14546 (setq range (org-get-property-block beg end))
14547 (when range
14548 (goto-char (car range))
14549 (while (re-search-forward
14550 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14551 (cdr range) t)
14552 (setq key (org-match-string-no-properties 1)
14553 value (org-trim (or (org-match-string-no-properties 2) "")))
14554 (unless (member key excluded)
14555 (push (cons key (or value "")) props)))))
14556 (if clocksum
14557 (push (cons "CLOCKSUM"
14558 (org-columns-number-to-string (/ (float clocksum) 60.)
14559 'add_times))
14560 props))
14561 (if clocksumt
14562 (push (cons "CLOCKSUM_T"
14563 (org-columns-number-to-string (/ (float clocksumt) 60.)
14564 'add_times))
14565 props))
14566 (unless (assoc "CATEGORY" props)
14567 (push (cons "CATEGORY" (org-get-category)) props))
14568 (append sum-props (nreverse props)))))))
14570 (defun org-entry-get (pom property &optional inherit literal-nil)
14571 "Get value of PROPERTY for entry or content at point-or-marker POM.
14572 If INHERIT is non-nil and the entry does not have the property,
14573 then also check higher levels of the hierarchy.
14574 If INHERIT is the symbol `selective', use inheritance only if the setting
14575 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14576 If the property is present but empty, the return value is the empty string.
14577 If the property is not present at all, nil is returned.
14579 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14580 do not interpret it as the list atom nil. This is used for inheritance
14581 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14582 (org-with-point-at pom
14583 (if (and inherit (if (eq inherit 'selective)
14584 (org-property-inherit-p property)
14586 (org-entry-get-with-inheritance property literal-nil)
14587 (if (member property org-special-properties)
14588 ;; We need a special property. Use `org-entry-properties' to
14589 ;; retrieve it, but specify the wanted property
14590 (cdr (assoc property (org-entry-properties nil 'special property)))
14591 (let* ((range (org-get-property-block))
14592 (props (list (or (assoc property org-file-properties)
14593 (assoc property org-global-properties)
14594 (assoc property org-global-properties-fixed))))
14595 (ap (lambda (key)
14596 (when (re-search-forward
14597 (org-re-property key) (cdr range) t)
14598 (setq props
14599 (org-update-property-plist
14601 (if (match-end 1)
14602 (org-match-string-no-properties 1) "")
14603 props)))))
14604 val)
14605 (when (and range (goto-char (car range)))
14606 (funcall ap property)
14607 (goto-char (car range))
14608 (while (funcall ap (concat property "+")))
14609 (setq val (cdr (assoc property props)))
14610 (when val (if literal-nil val (org-not-nil val)))))))))
14612 (defun org-property-or-variable-value (var &optional inherit)
14613 "Check if there is a property fixing the value of VAR.
14614 If yes, return this value. If not, return the current value of the variable."
14615 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14616 (if (and prop (stringp prop) (string-match "\\S-" prop))
14617 (read prop)
14618 (symbol-value var))))
14620 (defun org-entry-delete (pom property)
14621 "Delete the property PROPERTY from entry at point-or-marker POM."
14622 (org-with-point-at pom
14623 (if (member property org-special-properties)
14624 nil ; cannot delete these properties.
14625 (let ((range (org-get-property-block)))
14626 (if (and range
14627 (goto-char (car range))
14628 (re-search-forward
14629 (org-re-property property)
14630 (cdr range) t))
14631 (progn
14632 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14634 nil)))))
14636 ;; Multi-values properties are properties that contain multiple values
14637 ;; These values are assumed to be single words, separated by whitespace.
14638 (defun org-entry-add-to-multivalued-property (pom property value)
14639 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14640 (let* ((old (org-entry-get pom property))
14641 (values (and old (org-split-string old "[ \t]"))))
14642 (setq value (org-entry-protect-space value))
14643 (unless (member value values)
14644 (setq values (cons value values))
14645 (org-entry-put pom property
14646 (mapconcat 'identity values " ")))))
14648 (defun org-entry-remove-from-multivalued-property (pom property value)
14649 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14650 (let* ((old (org-entry-get pom property))
14651 (values (and old (org-split-string old "[ \t]"))))
14652 (setq value (org-entry-protect-space value))
14653 (when (member value values)
14654 (setq values (delete value values))
14655 (org-entry-put pom property
14656 (mapconcat 'identity values " ")))))
14658 (defun org-entry-member-in-multivalued-property (pom property value)
14659 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14660 (let* ((old (org-entry-get pom property))
14661 (values (and old (org-split-string old "[ \t]"))))
14662 (setq value (org-entry-protect-space value))
14663 (member value values)))
14665 (defun org-entry-get-multivalued-property (pom property)
14666 "Return a list of values in a multivalued property."
14667 (let* ((value (org-entry-get pom property))
14668 (values (and value (org-split-string value "[ \t]"))))
14669 (mapcar 'org-entry-restore-space values)))
14671 (defun org-entry-put-multivalued-property (pom property &rest values)
14672 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14673 VALUES should be a list of strings. Spaces will be protected."
14674 (org-entry-put pom property
14675 (mapconcat 'org-entry-protect-space values " "))
14676 (let* ((value (org-entry-get pom property))
14677 (values (and value (org-split-string value "[ \t]"))))
14678 (mapcar 'org-entry-restore-space values)))
14680 (defun org-entry-protect-space (s)
14681 "Protect spaces and newline in string S."
14682 (while (string-match " " s)
14683 (setq s (replace-match "%20" t t s)))
14684 (while (string-match "\n" s)
14685 (setq s (replace-match "%0A" t t s)))
14688 (defun org-entry-restore-space (s)
14689 "Restore spaces and newline in string S."
14690 (while (string-match "%20" s)
14691 (setq s (replace-match " " t t s)))
14692 (while (string-match "%0A" s)
14693 (setq s (replace-match "\n" t t s)))
14696 (defvar org-entry-property-inherited-from (make-marker)
14697 "Marker pointing to the entry from where a property was inherited.
14698 Each call to `org-entry-get-with-inheritance' will set this marker to the
14699 location of the entry where the inheritance search matched. If there was
14700 no match, the marker will point nowhere.
14701 Note that also `org-entry-get' calls this function, if the INHERIT flag
14702 is set.")
14704 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14705 "Get PROPERTY of entry or content at point, search higher levels if needed.
14706 The search will stop at the first ancestor which has the property defined.
14707 If the value found is \"nil\", return nil to show that the property
14708 should be considered as undefined (this is the meaning of nil here).
14709 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14710 (move-marker org-entry-property-inherited-from nil)
14711 (let (tmp)
14712 (save-excursion
14713 (save-restriction
14714 (widen)
14715 (catch 'ex
14716 (while t
14717 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14718 (or (ignore-errors (org-back-to-heading t))
14719 (goto-char (point-min)))
14720 (move-marker org-entry-property-inherited-from (point))
14721 (throw 'ex tmp))
14722 (or (ignore-errors (org-up-heading-safe))
14723 (throw 'ex nil))))))
14724 (setq tmp (or tmp
14725 (cdr (assoc property org-file-properties))
14726 (cdr (assoc property org-global-properties))
14727 (cdr (assoc property org-global-properties-fixed))))
14728 (if literal-nil tmp (org-not-nil tmp))))
14730 (defvar org-property-changed-functions nil
14731 "Hook called when the value of a property has changed.
14732 Each hook function should accept two arguments, the name of the property
14733 and the new value.")
14735 (defun org-entry-put (pom property value)
14736 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14737 (org-with-point-at pom
14738 (org-back-to-heading t)
14739 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14740 range)
14741 (cond
14742 ((equal property "TODO")
14743 (when (and (stringp value) (string-match "\\S-" value)
14744 (not (member value org-todo-keywords-1)))
14745 (error "\"%s\" is not a valid TODO state" value))
14746 (if (or (not value)
14747 (not (string-match "\\S-" value)))
14748 (setq value 'none))
14749 (org-todo value)
14750 (org-set-tags nil 'align))
14751 ((equal property "PRIORITY")
14752 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14753 (string-to-char value) ?\ ))
14754 (org-set-tags nil 'align))
14755 ((equal property "SCHEDULED")
14756 (if (re-search-forward org-scheduled-time-regexp end t)
14757 (cond
14758 ((eq value 'earlier) (org-timestamp-change -1 'day))
14759 ((eq value 'later) (org-timestamp-change 1 'day))
14760 (t (call-interactively 'org-schedule)))
14761 (call-interactively 'org-schedule)))
14762 ((equal property "DEADLINE")
14763 (if (re-search-forward org-deadline-time-regexp end t)
14764 (cond
14765 ((eq value 'earlier) (org-timestamp-change -1 'day))
14766 ((eq value 'later) (org-timestamp-change 1 'day))
14767 (t (call-interactively 'org-deadline)))
14768 (call-interactively 'org-deadline)))
14769 ((member property org-special-properties)
14770 (error "The %s property can not yet be set with `org-entry-put'"
14771 property))
14772 (t ; a non-special property
14773 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14774 (setq range (org-get-property-block beg end 'force))
14775 (goto-char (car range))
14776 (if (re-search-forward
14777 (org-re-property-keyword property) (cdr range) t)
14778 (progn
14779 (delete-region (match-beginning 0) (match-end 0))
14780 (goto-char (match-beginning 0)))
14781 (goto-char (cdr range))
14782 (insert "\n")
14783 (backward-char 1)
14784 (org-indent-line))
14785 (insert ":" property ":")
14786 (and value (insert " " value))
14787 (org-indent-line)))))
14788 (run-hook-with-args 'org-property-changed-functions property value)))
14790 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14791 "Get all property keys in the current buffer.
14792 With INCLUDE-SPECIALS, also list the special properties that reflect things
14793 like tags and TODO state.
14794 With INCLUDE-DEFAULTS, also include properties that has special meaning
14795 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14796 and others.
14797 With INCLUDE-COLUMNS, also include property names given in COLUMN
14798 formats in the current buffer."
14799 (let (rtn range cfmt s p)
14800 (save-excursion
14801 (save-restriction
14802 (widen)
14803 (goto-char (point-min))
14804 (while (re-search-forward org-property-start-re nil t)
14805 (setq range (org-get-property-block))
14806 (goto-char (car range))
14807 (while (re-search-forward
14808 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14809 (cdr range) t)
14810 (add-to-list 'rtn (org-match-string-no-properties 1)))
14811 (outline-next-heading))))
14813 (when include-specials
14814 (setq rtn (append org-special-properties rtn)))
14816 (when include-defaults
14817 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14818 (add-to-list 'rtn org-effort-property))
14820 (when include-columns
14821 (save-excursion
14822 (save-restriction
14823 (widen)
14824 (goto-char (point-min))
14825 (while (re-search-forward
14826 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14827 nil t)
14828 (setq cfmt (match-string 2) s 0)
14829 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14830 cfmt s)
14831 (setq s (match-end 0)
14832 p (match-string 1 cfmt))
14833 (unless (or (equal p "ITEM")
14834 (member p org-special-properties))
14835 (add-to-list 'rtn (match-string 1 cfmt))))))))
14837 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14839 (defun org-property-values (key)
14840 "Return a list of all values of property KEY in the current buffer."
14841 (save-excursion
14842 (save-restriction
14843 (widen)
14844 (goto-char (point-min))
14845 (let ((re (org-re-property key))
14846 values)
14847 (while (re-search-forward re nil t)
14848 (add-to-list 'values (org-trim (match-string 1))))
14849 (delete "" values)))))
14851 (defun org-insert-property-drawer ()
14852 "Insert a property drawer into the current entry."
14853 (org-back-to-heading t)
14854 (looking-at org-outline-regexp)
14855 (let ((indent (if org-adapt-indentation
14856 (- (match-end 0) (match-beginning 0))
14858 (beg (point))
14859 (re (concat "^[ \t]*" org-keyword-time-regexp))
14860 end hiddenp)
14861 (outline-next-heading)
14862 (setq end (point))
14863 (goto-char beg)
14864 (while (re-search-forward re end t))
14865 (setq hiddenp (outline-invisible-p))
14866 (end-of-line 1)
14867 (and (equal (char-after) ?\n) (forward-char 1))
14868 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14869 (if (member (match-string 1) '("CLOCK:" ":END:"))
14870 ;; just skip this line
14871 (beginning-of-line 2)
14872 ;; Drawer start, find the end
14873 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14874 (beginning-of-line 1)))
14875 (org-skip-over-state-notes)
14876 (skip-chars-backward " \t\n\r")
14877 (if (eq (char-before) ?*) (forward-char 1))
14878 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14879 (beginning-of-line 0)
14880 (org-indent-to-column indent)
14881 (beginning-of-line 2)
14882 (org-indent-to-column indent)
14883 (beginning-of-line 0)
14884 (if hiddenp
14885 (save-excursion
14886 (org-back-to-heading t)
14887 (hide-entry))
14888 (org-flag-drawer t))))
14890 (defun org-insert-drawer (&optional arg drawer)
14891 "Insert a drawer at point.
14893 Optional argument DRAWER, when non-nil, is a string representing
14894 drawer's name. Otherwise, the user is prompted for a name.
14896 If a region is active, insert the drawer around that region
14897 instead.
14899 Point is left between drawer's boundaries."
14900 (interactive "P")
14901 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14902 "LOGBOOK"))
14903 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14904 ;; internally by Org. They are meant to be inserted
14905 ;; automatically.
14906 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14907 ;; Remove system drawers from list. Note: For some reason,
14908 ;; `org-completing-read' ignores the predicate while
14909 ;; `completing-read' handles it fine.
14910 (drawer (if arg "PROPERTIES"
14911 (or drawer
14912 (completing-read
14913 "Drawer: " org-drawers
14914 (lambda (d) (not (member d system-drawers))))))))
14915 (cond
14916 ;; With C-u, fall back on `org-insert-property-drawer'
14917 (arg (org-insert-property-drawer))
14918 ;; With an active region, insert a drawer at point.
14919 ((not (org-region-active-p))
14920 (progn
14921 (unless (bolp) (insert "\n"))
14922 (insert (format ":%s:\n\n:END:\n" drawer))
14923 (forward-line -2)))
14924 ;; Otherwise, insert the drawer at point
14926 (let ((rbeg (region-beginning))
14927 (rend (copy-marker (region-end))))
14928 (unwind-protect
14929 (progn
14930 (goto-char rbeg)
14931 (beginning-of-line)
14932 (when (save-excursion
14933 (re-search-forward org-outline-regexp-bol rend t))
14934 (error "Drawers cannot contain headlines"))
14935 ;; Position point at the beginning of the first
14936 ;; non-blank line in region. Insert drawer's opening
14937 ;; there, then indent it.
14938 (org-skip-whitespace)
14939 (beginning-of-line)
14940 (insert ":" drawer ":\n")
14941 (forward-line -1)
14942 (indent-for-tab-command)
14943 ;; Move point to the beginning of the first blank line
14944 ;; after the last non-blank line in region. Insert
14945 ;; drawer's closing, then indent it.
14946 (goto-char rend)
14947 (skip-chars-backward " \r\t\n")
14948 (insert "\n:END:")
14949 (indent-for-tab-command)
14950 (unless (eolp) (insert "\n")))
14951 ;; Clear marker, whatever the outcome of insertion is.
14952 (set-marker rend nil)))))))
14954 (defvar org-property-set-functions-alist nil
14955 "Property set function alist.
14956 Each entry should have the following format:
14958 (PROPERTY . READ-FUNCTION)
14960 The read function will be called with the same argument as
14961 `org-completing-read'.")
14963 (defun org-set-property-function (property)
14964 "Get the function that should be used to set PROPERTY.
14965 This is computed according to `org-property-set-functions-alist'."
14966 (or (cdr (assoc property org-property-set-functions-alist))
14967 'org-completing-read))
14969 (defun org-read-property-value (property)
14970 "Read PROPERTY value from user."
14971 (let* ((completion-ignore-case t)
14972 (allowed (org-property-get-allowed-values nil property 'table))
14973 (cur (org-entry-get nil property))
14974 (prompt (concat property " value"
14975 (if (and cur (string-match "\\S-" cur))
14976 (concat " [" cur "]") "") ": "))
14977 (set-function (org-set-property-function property))
14978 (val (if allowed
14979 (funcall set-function prompt allowed nil
14980 (not (get-text-property 0 'org-unrestricted
14981 (caar allowed))))
14982 (let (org-completion-use-ido org-completion-use-iswitchb)
14983 (funcall set-function prompt
14984 (mapcar 'list (org-property-values property))
14985 nil nil "" nil cur)))))
14986 (if (equal val "")
14988 val)))
14990 (defvar org-last-set-property nil)
14991 (defun org-read-property-name ()
14992 "Read a property name."
14993 (let* ((completion-ignore-case t)
14994 (keys (org-buffer-property-keys nil t t))
14995 (default-prop (or (save-excursion
14996 (save-match-data
14997 (beginning-of-line)
14998 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14999 (null (string= (match-string 1) "END"))
15000 (match-string 1))))
15001 org-last-set-property))
15002 (property (org-icompleting-read
15003 (concat "Property"
15004 (if default-prop (concat " [" default-prop "]") "")
15005 ": ")
15006 (mapcar 'list keys)
15007 nil nil nil nil
15008 default-prop
15010 (if (member property keys)
15011 property
15012 (or (cdr (assoc (downcase property)
15013 (mapcar (lambda (x) (cons (downcase x) x))
15014 keys)))
15015 property))))
15017 (defun org-set-property (property value)
15018 "In the current entry, set PROPERTY to VALUE.
15019 When called interactively, this will prompt for a property name, offering
15020 completion on existing and default properties. And then it will prompt
15021 for a value, offering completion either on allowed values (via an inherited
15022 xxx_ALL property) or on existing values in other instances of this property
15023 in the current file."
15024 (interactive (list nil nil))
15025 (let* ((property (or property (org-read-property-name)))
15026 (value (or value (org-read-property-value property)))
15027 (fn (cdr (assoc property org-properties-postprocess-alist))))
15028 (setq org-last-set-property property)
15029 ;; Possibly postprocess the inserted value:
15030 (when fn (setq value (funcall fn value)))
15031 (unless (equal (org-entry-get nil property) value)
15032 (org-entry-put nil property value))))
15034 (defun org-delete-property (property)
15035 "In the current entry, delete PROPERTY."
15036 (interactive
15037 (let* ((completion-ignore-case t)
15038 (prop (org-icompleting-read "Property: "
15039 (org-entry-properties nil 'standard))))
15040 (list prop)))
15041 (message "Property %s %s" property
15042 (if (org-entry-delete nil property)
15043 "deleted"
15044 "was not present in the entry")))
15046 (defun org-delete-property-globally (property)
15047 "Remove PROPERTY globally, from all entries."
15048 (interactive
15049 (let* ((completion-ignore-case t)
15050 (prop (org-icompleting-read
15051 "Globally remove property: "
15052 (mapcar 'list (org-buffer-property-keys)))))
15053 (list prop)))
15054 (save-excursion
15055 (save-restriction
15056 (widen)
15057 (goto-char (point-min))
15058 (let ((cnt 0))
15059 (while (re-search-forward
15060 (org-re-property property)
15061 nil t)
15062 (setq cnt (1+ cnt))
15063 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15064 (message "Property \"%s\" removed from %d entries" property cnt)))))
15066 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15068 (defun org-compute-property-at-point ()
15069 "Compute the property at point.
15070 This looks for an enclosing column format, extracts the operator and
15071 then applies it to the property in the column format's scope."
15072 (interactive)
15073 (unless (org-at-property-p)
15074 (error "Not at a property"))
15075 (let ((prop (org-match-string-no-properties 2)))
15076 (org-columns-get-format-and-top-level)
15077 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15078 (error "No operator defined for property %s" prop))
15079 (org-columns-compute prop)))
15081 (defvar org-property-allowed-value-functions nil
15082 "Hook for functions supplying allowed values for a specific property.
15083 The functions must take a single argument, the name of the property, and
15084 return a flat list of allowed values. If \":ETC\" is one of
15085 the values, this means that these values are intended as defaults for
15086 completion, but that other values should be allowed too.
15087 The functions must return nil if they are not responsible for this
15088 property.")
15090 (defun org-property-get-allowed-values (pom property &optional table)
15091 "Get allowed values for the property PROPERTY.
15092 When TABLE is non-nil, return an alist that can directly be used for
15093 completion."
15094 (let (vals)
15095 (cond
15096 ((equal property "TODO")
15097 (setq vals (org-with-point-at pom
15098 (append org-todo-keywords-1 '("")))))
15099 ((equal property "PRIORITY")
15100 (let ((n org-lowest-priority))
15101 (while (>= n org-highest-priority)
15102 (push (char-to-string n) vals)
15103 (setq n (1- n)))))
15104 ((member property org-special-properties))
15105 ((setq vals (run-hook-with-args-until-success
15106 'org-property-allowed-value-functions property)))
15108 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15109 (when (and vals (string-match "\\S-" vals))
15110 (setq vals (car (read-from-string (concat "(" vals ")"))))
15111 (setq vals (mapcar (lambda (x)
15112 (cond ((stringp x) x)
15113 ((numberp x) (number-to-string x))
15114 ((symbolp x) (symbol-name x))
15115 (t "???")))
15116 vals)))))
15117 (when (member ":ETC" vals)
15118 (setq vals (remove ":ETC" vals))
15119 (org-add-props (car vals) '(org-unrestricted t)))
15120 (if table (mapcar 'list vals) vals)))
15122 (defun org-property-previous-allowed-value (&optional previous)
15123 "Switch to the next allowed value for this property."
15124 (interactive)
15125 (org-property-next-allowed-value t))
15127 (defun org-property-next-allowed-value (&optional previous)
15128 "Switch to the next allowed value for this property."
15129 (interactive)
15130 (unless (org-at-property-p)
15131 (error "Not at a property"))
15132 (let* ((key (match-string 2))
15133 (value (match-string 3))
15134 (allowed (or (org-property-get-allowed-values (point) key)
15135 (and (member value '("[ ]" "[-]" "[X]"))
15136 '("[ ]" "[X]"))))
15137 nval)
15138 (unless allowed
15139 (error "Allowed values for this property have not been defined"))
15140 (if previous (setq allowed (reverse allowed)))
15141 (if (member value allowed)
15142 (setq nval (car (cdr (member value allowed)))))
15143 (setq nval (or nval (car allowed)))
15144 (if (equal nval value)
15145 (error "Only one allowed value for this property"))
15146 (org-at-property-p)
15147 (replace-match (concat " :" key ": " nval) t t)
15148 (org-indent-line)
15149 (beginning-of-line 1)
15150 (skip-chars-forward " \t")
15151 (run-hook-with-args 'org-property-changed-functions key nval)))
15153 (defun org-find-olp (path &optional this-buffer)
15154 "Return a marker pointing to the entry at outline path OLP.
15155 If anything goes wrong, throw an error.
15156 You can wrap this call to catch the error like this:
15158 (condition-case msg
15159 (org-mobile-locate-entry (match-string 4))
15160 (error (nth 1 msg)))
15162 The return value will then be either a string with the error message,
15163 or a marker if everything is OK.
15165 If THIS-BUFFER is set, the outline path does not contain a file,
15166 only headings."
15167 (let* ((file (if this-buffer buffer-file-name (pop path)))
15168 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15169 (level 1)
15170 (lmin 1)
15171 (lmax 1)
15172 limit re end found pos heading cnt flevel)
15173 (unless buffer (error "File not found :%s" file))
15174 (with-current-buffer buffer
15175 (save-excursion
15176 (save-restriction
15177 (widen)
15178 (setq limit (point-max))
15179 (goto-char (point-min))
15180 (while (setq heading (pop path))
15181 (setq re (format org-complex-heading-regexp-format
15182 (regexp-quote heading)))
15183 (setq cnt 0 pos (point))
15184 (while (re-search-forward re end t)
15185 (setq level (- (match-end 1) (match-beginning 1)))
15186 (if (and (>= level lmin) (<= level lmax))
15187 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15188 (when (= cnt 0) (error "Heading not found on level %d: %s"
15189 lmax heading))
15190 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15191 lmax heading))
15192 (goto-char found)
15193 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15194 (setq end (save-excursion (org-end-of-subtree t t))))
15195 (when (org-at-heading-p)
15196 (move-marker (make-marker) (point))))))))
15198 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15199 "Find node HEADING in BUFFER.
15200 Return a marker to the heading if it was found, or nil if not.
15201 If POS-ONLY is set, return just the position instead of a marker.
15203 The heading text must match exact, but it may have a TODO keyword,
15204 a priority cookie and tags in the standard locations."
15205 (with-current-buffer (or buffer (current-buffer))
15206 (save-excursion
15207 (save-restriction
15208 (widen)
15209 (goto-char (point-min))
15210 (let (case-fold-search)
15211 (if (re-search-forward
15212 (format org-complex-heading-regexp-format
15213 (regexp-quote heading)) nil t)
15214 (if pos-only
15215 (match-beginning 0)
15216 (move-marker (make-marker) (match-beginning 0)))))))))
15218 (defun org-find-exact-heading-in-directory (heading &optional dir)
15219 "Find Org node headline HEADING in all .org files in directory DIR.
15220 When the target headline is found, return a marker to this location."
15221 (let ((files (directory-files (or dir default-directory)
15222 nil "\\`[^.#].*\\.org\\'"))
15223 file visiting m buffer)
15224 (catch 'found
15225 (while (setq file (pop files))
15226 (message "trying %s" file)
15227 (setq visiting (org-find-base-buffer-visiting file))
15228 (setq buffer (or visiting (find-file-noselect file)))
15229 (setq m (org-find-exact-headline-in-buffer
15230 heading buffer))
15231 (when (and (not m) (not visiting)) (kill-buffer buffer))
15232 (and m (throw 'found m))))))
15234 (defun org-find-entry-with-id (ident)
15235 "Locate the entry that contains the ID property with exact value IDENT.
15236 IDENT can be a string, a symbol or a number, this function will search for
15237 the string representation of it.
15238 Return the position where this entry starts, or nil if there is no such entry."
15239 (interactive "sID: ")
15240 (let ((id (cond
15241 ((stringp ident) ident)
15242 ((symbol-name ident) (symbol-name ident))
15243 ((numberp ident) (number-to-string ident))
15244 (t (error "IDENT %s must be a string, symbol or number" ident))))
15245 (case-fold-search nil))
15246 (save-excursion
15247 (save-restriction
15248 (widen)
15249 (goto-char (point-min))
15250 (when (re-search-forward
15251 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15252 nil t)
15253 (org-back-to-heading t)
15254 (point))))))
15256 ;;;; Timestamps
15258 (defvar org-last-changed-timestamp nil)
15259 (defvar org-last-inserted-timestamp nil
15260 "The last time stamp inserted with `org-insert-time-stamp'.")
15261 (defvar org-time-was-given) ; dynamically scoped parameter
15262 (defvar org-end-time-was-given) ; dynamically scoped parameter
15263 (defvar org-ts-what) ; dynamically scoped parameter
15265 (defun org-time-stamp (arg &optional inactive)
15266 "Prompt for a date/time and insert a time stamp.
15267 If the user specifies a time like HH:MM or if this command is
15268 called with at least one prefix argument, the time stamp contains
15269 the date and the time. Otherwise, only the date is be included.
15271 All parts of a date not specified by the user is filled in from
15272 the current date/time. So if you just press return without
15273 typing anything, the time stamp will represent the current
15274 date/time.
15276 If there is already a timestamp at the cursor, it will be
15277 modified.
15279 With two universal prefix arguments, insert an active timestamp
15280 with the current time without prompting the user."
15281 (interactive "P")
15282 (let* ((ts nil)
15283 (default-time
15284 ;; Default time is either today, or, when entering a range,
15285 ;; the range start.
15286 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15287 (save-excursion
15288 (re-search-backward
15289 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15290 (- (point) 20) t)))
15291 (apply 'encode-time (org-parse-time-string (match-string 1)))
15292 (current-time)))
15293 (default-input (and ts (org-get-compact-tod ts)))
15294 (repeater (save-excursion
15295 (save-match-data
15296 (beginning-of-line)
15297 (when (re-search-forward
15298 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15299 (save-excursion (progn (end-of-line) (point))) t)
15300 (match-string 0)))))
15301 org-time-was-given org-end-time-was-given time)
15302 (cond
15303 ((and (org-at-timestamp-p t)
15304 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15305 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15306 (insert "--")
15307 (setq time (let ((this-command this-command))
15308 (org-read-date arg 'totime nil nil
15309 default-time default-input inactive)))
15310 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15311 ((org-at-timestamp-p t)
15312 (setq time (let ((this-command this-command))
15313 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15314 (when (org-at-timestamp-p t) ; just to get the match data
15315 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15316 (replace-match "")
15317 (setq org-last-changed-timestamp
15318 (org-insert-time-stamp
15319 time (or org-time-was-given arg)
15320 inactive nil nil (list org-end-time-was-given)))
15321 (when repeater (goto-char (1- (point))) (insert " " repeater)
15322 (setq org-last-changed-timestamp
15323 (concat (substring org-last-inserted-timestamp 0 -1)
15324 " " repeater ">"))))
15325 (message "Timestamp updated"))
15326 ((equal arg '(16))
15327 (org-insert-time-stamp (current-time) t))
15329 (setq time (let ((this-command this-command))
15330 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15331 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15332 nil nil (list org-end-time-was-given))))))
15334 ;; FIXME: can we use this for something else, like computing time differences?
15335 (defun org-get-compact-tod (s)
15336 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15337 (let* ((t1 (match-string 1 s))
15338 (h1 (string-to-number (match-string 2 s)))
15339 (m1 (string-to-number (match-string 3 s)))
15340 (t2 (and (match-end 4) (match-string 5 s)))
15341 (h2 (and t2 (string-to-number (match-string 6 s))))
15342 (m2 (and t2 (string-to-number (match-string 7 s))))
15343 dh dm)
15344 (if (not t2)
15346 (setq dh (- h2 h1) dm (- m2 m1))
15347 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15348 (concat t1 "+" (number-to-string dh)
15349 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15351 (defun org-time-stamp-inactive (&optional arg)
15352 "Insert an inactive time stamp.
15353 An inactive time stamp is enclosed in square brackets instead of angle
15354 brackets. It is inactive in the sense that it does not trigger agenda entries,
15355 does not link to the calendar and cannot be changed with the S-cursor keys.
15356 So these are more for recording a certain time/date."
15357 (interactive "P")
15358 (org-time-stamp arg 'inactive))
15360 (defvar org-date-ovl (make-overlay 1 1))
15361 (overlay-put org-date-ovl 'face 'org-date-selected)
15362 (org-detach-overlay org-date-ovl)
15364 (defvar org-ans1) ; dynamically scoped parameter
15365 (defvar org-ans2) ; dynamically scoped parameter
15367 (defvar org-plain-time-of-day-regexp) ; defined below
15369 (defvar org-overriding-default-time nil) ; dynamically scoped
15370 (defvar org-read-date-overlay nil)
15371 (defvar org-dcst nil) ; dynamically scoped
15372 (defvar org-read-date-history nil)
15373 (defvar org-read-date-final-answer nil)
15374 (defvar org-read-date-analyze-futurep nil)
15375 (defvar org-read-date-analyze-forced-year nil)
15376 (defvar org-read-date-inactive)
15378 (defun org-read-date (&optional org-with-time to-time from-string prompt
15379 default-time default-input inactive)
15380 "Read a date, possibly a time, and make things smooth for the user.
15381 The prompt will suggest to enter an ISO date, but you can also enter anything
15382 which will at least partially be understood by `parse-time-string'.
15383 Unrecognized parts of the date will default to the current day, month, year,
15384 hour and minute. If this command is called to replace a timestamp at point,
15385 or to enter the second timestamp of a range, the default time is taken
15386 from the existing stamp. Furthermore, the command prefers the future,
15387 so if you are giving a date where the year is not given, and the day-month
15388 combination is already past in the current year, it will assume you
15389 mean next year. For details, see the manual. A few examples:
15391 3-2-5 --> 2003-02-05
15392 feb 15 --> currentyear-02-15
15393 2/15 --> currentyear-02-15
15394 sep 12 9 --> 2009-09-12
15395 12:45 --> today 12:45
15396 22 sept 0:34 --> currentyear-09-22 0:34
15397 12 --> currentyear-currentmonth-12
15398 Fri --> nearest Friday (today or later)
15399 etc.
15401 Furthermore you can specify a relative date by giving, as the *first* thing
15402 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15403 change in days weeks, months, years.
15404 With a single plus or minus, the date is relative to today. With a double
15405 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15406 +4d --> four days from today
15407 +4 --> same as above
15408 +2w --> two weeks from today
15409 ++5 --> five days from default date
15411 The function understands only English month and weekday abbreviations.
15413 While prompting, a calendar is popped up - you can also select the
15414 date with the mouse (button 1). The calendar shows a period of three
15415 months. To scroll it to other months, use the keys `>' and `<'.
15416 If you don't like the calendar, turn it off with
15417 \(setq org-read-date-popup-calendar nil)
15419 With optional argument TO-TIME, the date will immediately be converted
15420 to an internal time.
15421 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15422 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15423 still enter a time, and this function will inform the calling routine
15424 about this change. The calling routine may then choose to change the
15425 format used to insert the time stamp into the buffer to include the time.
15426 With optional argument FROM-STRING, read from this string instead from
15427 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15428 the time/date that is used for everything that is not specified by the
15429 user."
15430 (require 'parse-time)
15431 (let* ((org-time-stamp-rounding-minutes
15432 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15433 (org-dcst org-display-custom-times)
15434 (ct (org-current-time))
15435 (org-def (or org-overriding-default-time default-time ct))
15436 (org-defdecode (decode-time org-def))
15437 (dummy (progn
15438 (when (< (nth 2 org-defdecode) org-extend-today-until)
15439 (setcar (nthcdr 2 org-defdecode) -1)
15440 (setcar (nthcdr 1 org-defdecode) 59)
15441 (setq org-def (apply 'encode-time org-defdecode)
15442 org-defdecode (decode-time org-def)))))
15443 (calendar-frame-setup nil)
15444 (calendar-setup nil)
15445 (calendar-move-hook nil)
15446 (calendar-view-diary-initially-flag nil)
15447 (calendar-view-holidays-initially-flag nil)
15448 (timestr (format-time-string
15449 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15450 (prompt (concat (if prompt (concat prompt " ") "")
15451 (format "Date+time [%s]: " timestr)))
15452 ans (org-ans0 "") org-ans1 org-ans2 final)
15454 (cond
15455 (from-string (setq ans from-string))
15456 (org-read-date-popup-calendar
15457 (save-excursion
15458 (save-window-excursion
15459 (calendar)
15460 (org-eval-in-calendar '(setq cursor-type nil) t)
15461 (unwind-protect
15462 (progn
15463 (calendar-forward-day (- (time-to-days org-def)
15464 (calendar-absolute-from-gregorian
15465 (calendar-current-date))))
15466 (org-eval-in-calendar nil t)
15467 (let* ((old-map (current-local-map))
15468 (map (copy-keymap calendar-mode-map))
15469 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15470 (org-defkey map (kbd "RET") 'org-calendar-select)
15471 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15472 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15473 (org-defkey minibuffer-local-map [(meta shift left)]
15474 (lambda () (interactive)
15475 (org-eval-in-calendar '(calendar-backward-month 1))))
15476 (org-defkey minibuffer-local-map [(meta shift right)]
15477 (lambda () (interactive)
15478 (org-eval-in-calendar '(calendar-forward-month 1))))
15479 (org-defkey minibuffer-local-map [(meta shift up)]
15480 (lambda () (interactive)
15481 (org-eval-in-calendar '(calendar-backward-year 1))))
15482 (org-defkey minibuffer-local-map [(meta shift down)]
15483 (lambda () (interactive)
15484 (org-eval-in-calendar '(calendar-forward-year 1))))
15485 (org-defkey minibuffer-local-map [?\e (shift left)]
15486 (lambda () (interactive)
15487 (org-eval-in-calendar '(calendar-backward-month 1))))
15488 (org-defkey minibuffer-local-map [?\e (shift right)]
15489 (lambda () (interactive)
15490 (org-eval-in-calendar '(calendar-forward-month 1))))
15491 (org-defkey minibuffer-local-map [?\e (shift up)]
15492 (lambda () (interactive)
15493 (org-eval-in-calendar '(calendar-backward-year 1))))
15494 (org-defkey minibuffer-local-map [?\e (shift down)]
15495 (lambda () (interactive)
15496 (org-eval-in-calendar '(calendar-forward-year 1))))
15497 (org-defkey minibuffer-local-map [(shift up)]
15498 (lambda () (interactive)
15499 (org-eval-in-calendar '(calendar-backward-week 1))))
15500 (org-defkey minibuffer-local-map [(shift down)]
15501 (lambda () (interactive)
15502 (org-eval-in-calendar '(calendar-forward-week 1))))
15503 (org-defkey minibuffer-local-map [(shift left)]
15504 (lambda () (interactive)
15505 (org-eval-in-calendar '(calendar-backward-day 1))))
15506 (org-defkey minibuffer-local-map [(shift right)]
15507 (lambda () (interactive)
15508 (org-eval-in-calendar '(calendar-forward-day 1))))
15509 (org-defkey minibuffer-local-map ">"
15510 (lambda () (interactive)
15511 (org-eval-in-calendar '(scroll-calendar-left 1))))
15512 (org-defkey minibuffer-local-map "<"
15513 (lambda () (interactive)
15514 (org-eval-in-calendar '(scroll-calendar-right 1))))
15515 (org-defkey minibuffer-local-map "\C-v"
15516 (lambda () (interactive)
15517 (org-eval-in-calendar
15518 '(calendar-scroll-left-three-months 1))))
15519 (org-defkey minibuffer-local-map "\M-v"
15520 (lambda () (interactive)
15521 (org-eval-in-calendar
15522 '(calendar-scroll-right-three-months 1))))
15523 (run-hooks 'org-read-date-minibuffer-setup-hook)
15524 (unwind-protect
15525 (progn
15526 (use-local-map map)
15527 (setq org-read-date-inactive inactive)
15528 (add-hook 'post-command-hook 'org-read-date-display)
15529 (setq org-ans0 (read-string prompt default-input
15530 'org-read-date-history nil))
15531 ;; org-ans0: from prompt
15532 ;; org-ans1: from mouse click
15533 ;; org-ans2: from calendar motion
15534 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15535 (remove-hook 'post-command-hook 'org-read-date-display)
15536 (use-local-map old-map)
15537 (when org-read-date-overlay
15538 (delete-overlay org-read-date-overlay)
15539 (setq org-read-date-overlay nil)))))
15540 (bury-buffer "*Calendar*")))))
15542 (t ; Naked prompt only
15543 (unwind-protect
15544 (setq ans (read-string prompt default-input
15545 'org-read-date-history timestr))
15546 (when org-read-date-overlay
15547 (delete-overlay org-read-date-overlay)
15548 (setq org-read-date-overlay nil)))))
15550 (setq final (org-read-date-analyze ans org-def org-defdecode))
15552 (when org-read-date-analyze-forced-year
15553 (message "Year was forced into %s"
15554 (if org-read-date-force-compatible-dates
15555 "compatible range (1970-2037)"
15556 "range representable on this machine"))
15557 (ding))
15559 ;; One round trip to get rid of 34th of August and stuff like that....
15560 (setq final (decode-time (apply 'encode-time final)))
15562 (setq org-read-date-final-answer ans)
15564 (if to-time
15565 (apply 'encode-time final)
15566 (if (and (boundp 'org-time-was-given) org-time-was-given)
15567 (format "%04d-%02d-%02d %02d:%02d"
15568 (nth 5 final) (nth 4 final) (nth 3 final)
15569 (nth 2 final) (nth 1 final))
15570 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15572 (defvar org-def)
15573 (defvar org-defdecode)
15574 (defvar org-with-time)
15575 (defun org-read-date-display ()
15576 "Display the current date prompt interpretation in the minibuffer."
15577 (when org-read-date-display-live
15578 (when org-read-date-overlay
15579 (delete-overlay org-read-date-overlay))
15580 (when (minibufferp (current-buffer))
15581 (save-excursion
15582 (end-of-line 1)
15583 (while (not (equal (buffer-substring
15584 (max (point-min) (- (point) 4)) (point))
15585 " "))
15586 (insert " ")))
15587 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15588 " " (or org-ans1 org-ans2)))
15589 (org-end-time-was-given nil)
15590 (f (org-read-date-analyze ans org-def org-defdecode))
15591 (fmts (if org-dcst
15592 org-time-stamp-custom-formats
15593 org-time-stamp-formats))
15594 (fmt (if (or org-with-time
15595 (and (boundp 'org-time-was-given) org-time-was-given))
15596 (cdr fmts)
15597 (car fmts)))
15598 (txt (format-time-string fmt (apply 'encode-time f)))
15599 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15600 (txt (concat "=> " txt)))
15601 (when (and org-end-time-was-given
15602 (string-match org-plain-time-of-day-regexp txt))
15603 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15604 org-end-time-was-given
15605 (substring txt (match-end 0)))))
15606 (when org-read-date-analyze-futurep
15607 (setq txt (concat txt " (=>F)")))
15608 (setq org-read-date-overlay
15609 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15610 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15612 (defun org-read-date-analyze (ans org-def org-defdecode)
15613 "Analyze the combined answer of the date prompt."
15614 ;; FIXME: cleanup and comment
15615 (let ((nowdecode (decode-time (current-time)))
15616 delta deltan deltaw deltadef year month day
15617 hour minute second wday pm h2 m2 tl wday1
15618 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15619 (setq org-read-date-analyze-futurep nil
15620 org-read-date-analyze-forced-year nil)
15621 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15622 (setq ans "+0"))
15624 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15625 (setq ans (replace-match "" t t ans)
15626 deltan (car delta)
15627 deltaw (nth 1 delta)
15628 deltadef (nth 2 delta)))
15630 ;; Check if there is an iso week date in there. If yes, store the
15631 ;; info and postpone interpreting it until the rest of the parsing
15632 ;; is done.
15633 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15634 (setq iso-year (if (match-end 1)
15635 (org-small-year-to-year
15636 (string-to-number (match-string 1 ans))))
15637 iso-weekday (if (match-end 3)
15638 (string-to-number (match-string 3 ans)))
15639 iso-week (string-to-number (match-string 2 ans)))
15640 (setq ans (replace-match "" t t ans)))
15642 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15643 (when (string-match
15644 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15645 (setq year (if (match-end 2)
15646 (string-to-number (match-string 2 ans))
15647 (progn (setq kill-year t)
15648 (string-to-number (format-time-string "%Y"))))
15649 month (string-to-number (match-string 3 ans))
15650 day (string-to-number (match-string 4 ans)))
15651 (if (< year 100) (setq year (+ 2000 year)))
15652 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15653 t nil ans)))
15655 ;; Help matching dotted european dates
15656 (when (string-match
15657 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15658 (setq year (if (match-end 3)
15659 (string-to-number (match-string 3 ans))
15660 (progn (setq kill-year t)
15661 (string-to-number (format-time-string "%Y"))))
15662 day (string-to-number (match-string 1 ans))
15663 month (string-to-number (match-string 2 ans))
15664 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15665 t nil ans)))
15667 ;; Help matching american dates, like 5/30 or 5/30/7
15668 (when (string-match
15669 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15670 (setq year (if (match-end 4)
15671 (string-to-number (match-string 4 ans))
15672 (progn (setq kill-year t)
15673 (string-to-number (format-time-string "%Y"))))
15674 month (string-to-number (match-string 1 ans))
15675 day (string-to-number (match-string 2 ans)))
15676 (if (< year 100) (setq year (+ 2000 year)))
15677 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15678 t nil ans)))
15679 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15680 ;; If there is a time with am/pm, and *no* time without it, we convert
15681 ;; so that matching will be successful.
15682 (loop for i from 1 to 2 do ; twice, for end time as well
15683 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15684 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15685 (setq hour (string-to-number (match-string 1 ans))
15686 minute (if (match-end 3)
15687 (string-to-number (match-string 3 ans))
15689 pm (equal ?p
15690 (string-to-char (downcase (match-string 4 ans)))))
15691 (if (and (= hour 12) (not pm))
15692 (setq hour 0)
15693 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15694 (setq ans (replace-match (format "%02d:%02d" hour minute)
15695 t t ans))))
15697 ;; Check if a time range is given as a duration
15698 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15699 (setq hour (string-to-number (match-string 1 ans))
15700 h2 (+ hour (string-to-number (match-string 3 ans)))
15701 minute (string-to-number (match-string 2 ans))
15702 m2 (+ minute (if (match-end 5) (string-to-number
15703 (match-string 5 ans))0)))
15704 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15705 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15706 t t ans)))
15708 ;; Check if there is a time range
15709 (when (boundp 'org-end-time-was-given)
15710 (setq org-time-was-given nil)
15711 (when (and (string-match org-plain-time-of-day-regexp ans)
15712 (match-end 8))
15713 (setq org-end-time-was-given (match-string 8 ans))
15714 (setq ans (concat (substring ans 0 (match-beginning 7))
15715 (substring ans (match-end 7))))))
15717 (setq tl (parse-time-string ans)
15718 day (or (nth 3 tl) (nth 3 org-defdecode))
15719 month (or (nth 4 tl)
15720 (if (and org-read-date-prefer-future
15721 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15722 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15723 (nth 4 org-defdecode)))
15724 year (or (and (not kill-year) (nth 5 tl))
15725 (if (and org-read-date-prefer-future
15726 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15727 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15728 (nth 5 org-defdecode)))
15729 hour (or (nth 2 tl) (nth 2 org-defdecode))
15730 minute (or (nth 1 tl) (nth 1 org-defdecode))
15731 second (or (nth 0 tl) 0)
15732 wday (nth 6 tl))
15734 (when (and (eq org-read-date-prefer-future 'time)
15735 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15736 (equal day (nth 3 nowdecode))
15737 (equal month (nth 4 nowdecode))
15738 (equal year (nth 5 nowdecode))
15739 (nth 2 tl)
15740 (or (< (nth 2 tl) (nth 2 nowdecode))
15741 (and (= (nth 2 tl) (nth 2 nowdecode))
15742 (nth 1 tl)
15743 (< (nth 1 tl) (nth 1 nowdecode)))))
15744 (setq day (1+ day)
15745 futurep t))
15747 ;; Special date definitions below
15748 (cond
15749 (iso-week
15750 ;; There was an iso week
15751 (require 'cal-iso)
15752 (setq futurep nil)
15753 (setq year (or iso-year year)
15754 day (or iso-weekday wday 1)
15755 wday nil ; to make sure that the trigger below does not match
15756 iso-date (calendar-gregorian-from-absolute
15757 (calendar-absolute-from-iso
15758 (list iso-week day year))))
15759 ; FIXME: Should we also push ISO weeks into the future?
15760 ; (when (and org-read-date-prefer-future
15761 ; (not iso-year)
15762 ; (< (calendar-absolute-from-gregorian iso-date)
15763 ; (time-to-days (current-time))))
15764 ; (setq year (1+ year)
15765 ; iso-date (calendar-gregorian-from-absolute
15766 ; (calendar-absolute-from-iso
15767 ; (list iso-week day year)))))
15768 (setq month (car iso-date)
15769 year (nth 2 iso-date)
15770 day (nth 1 iso-date)))
15771 (deltan
15772 (setq futurep nil)
15773 (unless deltadef
15774 (let ((now (decode-time (current-time))))
15775 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15776 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15777 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15778 ((equal deltaw "m") (setq month (+ month deltan)))
15779 ((equal deltaw "y") (setq year (+ year deltan)))))
15780 ((and wday (not (nth 3 tl)))
15781 ;; Weekday was given, but no day, so pick that day in the week
15782 ;; on or after the derived date.
15783 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15784 (unless (equal wday wday1)
15785 (setq day (+ day (% (- wday wday1 -7) 7))))))
15786 (if (and (boundp 'org-time-was-given)
15787 (nth 2 tl))
15788 (setq org-time-was-given t))
15789 (if (< year 100) (setq year (+ 2000 year)))
15790 ;; Check of the date is representable
15791 (if org-read-date-force-compatible-dates
15792 (progn
15793 (if (< year 1970)
15794 (setq year 1970 org-read-date-analyze-forced-year t))
15795 (if (> year 2037)
15796 (setq year 2037 org-read-date-analyze-forced-year t)))
15797 (condition-case nil
15798 (ignore (encode-time second minute hour day month year))
15799 (error
15800 (setq year (nth 5 org-defdecode))
15801 (setq org-read-date-analyze-forced-year t))))
15802 (setq org-read-date-analyze-futurep futurep)
15803 (list second minute hour day month year)))
15805 (defvar parse-time-weekdays)
15806 (defun org-read-date-get-relative (s today default)
15807 "Check string S for special relative date string.
15808 TODAY and DEFAULT are internal times, for today and for a default.
15809 Return shift list (N what def-flag)
15810 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15811 N is the number of WHATs to shift.
15812 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15813 the DEFAULT date rather than TODAY."
15814 (require 'parse-time)
15815 (when (and
15816 (string-match
15817 (concat
15818 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15819 "\\([0-9]+\\)?"
15820 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15821 "\\([ \t]\\|$\\)") s)
15822 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15823 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15824 (string-to-char (substring (match-string 1 s) -1))
15825 ?+))
15826 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15827 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15828 (what (if (match-end 3) (match-string 3 s) "d"))
15829 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15830 (date (if rel default today))
15831 (wday (nth 6 (decode-time date)))
15832 delta)
15833 (if wday1
15834 (progn
15835 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15836 (if (= dir ?-) (setq delta (- delta 7)))
15837 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15838 (list delta "d" rel))
15839 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15841 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15842 "Turn a user-specified date into the internal representation.
15843 The internal representation needed by the calendar is (month day year).
15844 This is a wrapper to handle the brain-dead convention in calendar that
15845 user function argument order change dependent on argument order."
15846 (if (boundp 'calendar-date-style)
15847 (cond
15848 ((eq calendar-date-style 'american)
15849 (list arg1 arg2 arg3))
15850 ((eq calendar-date-style 'european)
15851 (list arg2 arg1 arg3))
15852 ((eq calendar-date-style 'iso)
15853 (list arg2 arg3 arg1)))
15854 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15855 (if (org-bound-and-true-p european-calendar-style)
15856 (list arg2 arg1 arg3)
15857 (list arg1 arg2 arg3)))))
15859 (defun org-eval-in-calendar (form &optional keepdate)
15860 "Eval FORM in the calendar window and return to current window.
15861 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15862 otherwise stick to the current value of `org-ans2'."
15863 (let ((sf (selected-frame))
15864 (sw (selected-window)))
15865 (select-window (get-buffer-window "*Calendar*" t))
15866 (eval form)
15867 (when (and (not keepdate) (calendar-cursor-to-date))
15868 (let* ((date (calendar-cursor-to-date))
15869 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15870 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15871 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15872 (select-window sw)
15873 (org-select-frame-set-input-focus sf)))
15875 (defun org-calendar-select ()
15876 "Return to `org-read-date' with the date currently selected.
15877 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15878 (interactive)
15879 (when (calendar-cursor-to-date)
15880 (let* ((date (calendar-cursor-to-date))
15881 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15882 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15883 (if (active-minibuffer-window) (exit-minibuffer))))
15885 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15886 "Insert a date stamp for the date given by the internal TIME.
15887 WITH-HM means use the stamp format that includes the time of the day.
15888 INACTIVE means use square brackets instead of angular ones, so that the
15889 stamp will not contribute to the agenda.
15890 PRE and POST are optional strings to be inserted before and after the
15891 stamp.
15892 The command returns the inserted time stamp."
15893 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15894 stamp)
15895 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15896 (insert-before-markers (or pre ""))
15897 (when (listp extra)
15898 (setq extra (car extra))
15899 (if (and (stringp extra)
15900 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15901 (setq extra (format "-%02d:%02d"
15902 (string-to-number (match-string 1 extra))
15903 (string-to-number (match-string 2 extra))))
15904 (setq extra nil)))
15905 (when extra
15906 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15907 (insert-before-markers (setq stamp (format-time-string fmt time)))
15908 (insert-before-markers (or post ""))
15909 (setq org-last-inserted-timestamp stamp)))
15911 (defun org-toggle-time-stamp-overlays ()
15912 "Toggle the use of custom time stamp formats."
15913 (interactive)
15914 (setq org-display-custom-times (not org-display-custom-times))
15915 (unless org-display-custom-times
15916 (let ((p (point-min)) (bmp (buffer-modified-p)))
15917 (while (setq p (next-single-property-change p 'display))
15918 (if (and (get-text-property p 'display)
15919 (eq (get-text-property p 'face) 'org-date))
15920 (remove-text-properties
15921 p (setq p (next-single-property-change p 'display))
15922 '(display t))))
15923 (set-buffer-modified-p bmp)))
15924 (if (featurep 'xemacs)
15925 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15926 (org-restart-font-lock)
15927 (setq org-table-may-need-update t)
15928 (if org-display-custom-times
15929 (message "Time stamps are overlaid with custom format")
15930 (message "Time stamp overlays removed")))
15932 (defun org-display-custom-time (beg end)
15933 "Overlay modified time stamp format over timestamp between BEG and END."
15934 (let* ((ts (buffer-substring beg end))
15935 t1 w1 with-hm tf time str w2 (off 0))
15936 (save-match-data
15937 (setq t1 (org-parse-time-string ts t))
15938 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15939 (setq off (- (match-end 0) (match-beginning 0)))))
15940 (setq end (- end off))
15941 (setq w1 (- end beg)
15942 with-hm (and (nth 1 t1) (nth 2 t1))
15943 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15944 time (org-fix-decoded-time t1)
15945 str (org-add-props
15946 (format-time-string
15947 (substring tf 1 -1) (apply 'encode-time time))
15948 nil 'mouse-face 'highlight)
15949 w2 (length str))
15950 (if (not (= w2 w1))
15951 (add-text-properties (1+ beg) (+ 2 beg)
15952 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15953 (if (featurep 'xemacs)
15954 (progn
15955 (put-text-property beg end 'invisible t)
15956 (put-text-property beg end 'end-glyph (make-glyph str)))
15957 (put-text-property beg end 'display str))))
15959 (defun org-translate-time (string)
15960 "Translate all timestamps in STRING to custom format.
15961 But do this only if the variable `org-display-custom-times' is set."
15962 (when org-display-custom-times
15963 (save-match-data
15964 (let* ((start 0)
15965 (re org-ts-regexp-both)
15966 t1 with-hm inactive tf time str beg end)
15967 (while (setq start (string-match re string start))
15968 (setq beg (match-beginning 0)
15969 end (match-end 0)
15970 t1 (save-match-data
15971 (org-parse-time-string (substring string beg end) t))
15972 with-hm (and (nth 1 t1) (nth 2 t1))
15973 inactive (equal (substring string beg (1+ beg)) "[")
15974 tf (funcall (if with-hm 'cdr 'car)
15975 org-time-stamp-custom-formats)
15976 time (org-fix-decoded-time t1)
15977 str (format-time-string
15978 (concat
15979 (if inactive "[" "<") (substring tf 1 -1)
15980 (if inactive "]" ">"))
15981 (apply 'encode-time time))
15982 string (replace-match str t t string)
15983 start (+ start (length str)))))))
15984 string)
15986 (defun org-fix-decoded-time (time)
15987 "Set 0 instead of nil for the first 6 elements of time.
15988 Don't touch the rest."
15989 (let ((n 0))
15990 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15992 (defun org-days-to-time (timestamp-string)
15993 "Difference between TIMESTAMP-STRING and now in days."
15994 (- (time-to-days (org-time-string-to-time timestamp-string))
15995 (time-to-days (current-time))))
15997 (defun org-deadline-close (timestamp-string &optional ndays)
15998 "Is the time in TIMESTAMP-STRING close to the current date?"
15999 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16000 (and (< (org-days-to-time timestamp-string) ndays)
16001 (not (org-entry-is-done-p))))
16003 (defun org-get-wdays (ts)
16004 "Get the deadline lead time appropriate for timestring TS."
16005 (cond
16006 ((<= org-deadline-warning-days 0)
16007 ;; 0 or negative, enforce this value no matter what
16008 (- org-deadline-warning-days))
16009 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16010 ;; lead time is specified.
16011 (floor (* (string-to-number (match-string 1 ts))
16012 (cdr (assoc (match-string 2 ts)
16013 '(("d" . 1) ("w" . 7)
16014 ("m" . 30.4) ("y" . 365.25)))))))
16015 ;; go for the default.
16016 (t org-deadline-warning-days)))
16018 (defun org-calendar-select-mouse (ev)
16019 "Return to `org-read-date' with the date currently selected.
16020 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16021 (interactive "e")
16022 (mouse-set-point ev)
16023 (when (calendar-cursor-to-date)
16024 (let* ((date (calendar-cursor-to-date))
16025 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16026 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16027 (if (active-minibuffer-window) (exit-minibuffer))))
16029 (defun org-check-deadlines (ndays)
16030 "Check if there are any deadlines due or past due.
16031 A deadline is considered due if it happens within `org-deadline-warning-days'
16032 days from today's date. If the deadline appears in an entry marked DONE,
16033 it is not shown. The prefix arg NDAYS can be used to test that many
16034 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16035 (interactive "P")
16036 (let* ((org-warn-days
16037 (cond
16038 ((equal ndays '(4)) 100000)
16039 (ndays (prefix-numeric-value ndays))
16040 (t (abs org-deadline-warning-days))))
16041 (case-fold-search nil)
16042 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16043 (callback
16044 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16046 (message "%d deadlines past-due or due within %d days"
16047 (org-occur regexp nil callback)
16048 org-warn-days)))
16050 (defsubst org-re-timestamp (type)
16051 "Return a regexp for timestamp TYPE.
16052 Allowed values for TYPE are:
16054 all: all timestamps
16055 active: only active timestamps (<...>)
16056 inactive: only inactive timestamps ([...])
16057 scheduled: only scheduled timestamps
16058 deadline: only deadline timestamps
16060 When TYPE is nil, fall back on returning a regexp that matches
16061 both scheduled and deadline timestamps."
16062 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16063 ((eq type 'active) org-ts-regexp)
16064 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16065 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16066 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16067 ((eq type 'scheduled-or-deadline)
16068 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16070 (defun org-check-before-date (date)
16071 "Check if there are deadlines or scheduled entries before DATE."
16072 (interactive (list (org-read-date)))
16073 (let ((case-fold-search nil)
16074 (regexp (org-re-timestamp org-ts-type))
16075 (callback
16076 (lambda () (time-less-p
16077 (org-time-string-to-time (match-string 1))
16078 (org-time-string-to-time date)))))
16079 (message "%d entries before %s"
16080 (org-occur regexp nil callback) date)))
16082 (defun org-check-after-date (date)
16083 "Check if there are deadlines or scheduled entries after DATE."
16084 (interactive (list (org-read-date)))
16085 (let ((case-fold-search nil)
16086 (regexp (org-re-timestamp org-ts-type))
16087 (callback
16088 (lambda () (not
16089 (time-less-p
16090 (org-time-string-to-time (match-string 1))
16091 (org-time-string-to-time date))))))
16092 (message "%d entries after %s"
16093 (org-occur regexp nil callback) date)))
16095 (defun org-check-dates-range (start-date end-date)
16096 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16097 (interactive (list (org-read-date nil nil nil "Range starts")
16098 (org-read-date nil nil nil "Range end")))
16099 (let ((case-fold-search nil)
16100 (regexp (org-re-timestamp org-ts-type))
16101 (callback
16102 (lambda ()
16103 (let ((match (match-string 1)))
16104 (and
16105 (not (time-less-p
16106 (org-time-string-to-time match)
16107 (org-time-string-to-time start-date)))
16108 (time-less-p
16109 (org-time-string-to-time match)
16110 (org-time-string-to-time end-date)))))))
16111 (message "%d entries between %s and %s"
16112 (org-occur regexp nil callback) start-date end-date)))
16114 (defun org-evaluate-time-range (&optional to-buffer)
16115 "Evaluate a time range by computing the difference between start and end.
16116 Normally the result is just printed in the echo area, but with prefix arg
16117 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16118 If the time range is actually in a table, the result is inserted into the
16119 next column.
16120 For time difference computation, a year is assumed to be exactly 365
16121 days in order to avoid rounding problems."
16122 (interactive "P")
16124 (org-clock-update-time-maybe)
16125 (save-excursion
16126 (unless (org-at-date-range-p t)
16127 (goto-char (point-at-bol))
16128 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16129 (if (not (org-at-date-range-p t))
16130 (error "Not at a time-stamp range, and none found in current line")))
16131 (let* ((ts1 (match-string 1))
16132 (ts2 (match-string 2))
16133 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16134 (match-end (match-end 0))
16135 (time1 (org-time-string-to-time ts1))
16136 (time2 (org-time-string-to-time ts2))
16137 (t1 (org-float-time time1))
16138 (t2 (org-float-time time2))
16139 (diff (abs (- t2 t1)))
16140 (negative (< (- t2 t1) 0))
16141 ;; (ys (floor (* 365 24 60 60)))
16142 (ds (* 24 60 60))
16143 (hs (* 60 60))
16144 (fy "%dy %dd %02d:%02d")
16145 (fy1 "%dy %dd")
16146 (fd "%dd %02d:%02d")
16147 (fd1 "%dd")
16148 (fh "%02d:%02d")
16149 y d h m align)
16150 (if havetime
16151 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16153 d (floor (/ diff ds)) diff (mod diff ds)
16154 h (floor (/ diff hs)) diff (mod diff hs)
16155 m (floor (/ diff 60)))
16156 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16158 d (floor (+ (/ diff ds) 0.5))
16159 h 0 m 0))
16160 (if (not to-buffer)
16161 (message "%s" (org-make-tdiff-string y d h m))
16162 (if (org-at-table-p)
16163 (progn
16164 (goto-char match-end)
16165 (setq align t)
16166 (and (looking-at " *|") (goto-char (match-end 0))))
16167 (goto-char match-end))
16168 (if (looking-at
16169 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16170 (replace-match ""))
16171 (if negative (insert " -"))
16172 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16173 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16174 (insert " " (format fh h m))))
16175 (if align (org-table-align))
16176 (message "Time difference inserted")))))
16178 (defun org-make-tdiff-string (y d h m)
16179 (let ((fmt "")
16180 (l nil))
16181 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16182 l (push y l)))
16183 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16184 l (push d l)))
16185 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16186 l (push h l)))
16187 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16188 l (push m l)))
16189 (apply 'format fmt (nreverse l))))
16191 (defun org-time-string-to-time (s &optional buffer pos)
16192 (condition-case errdata
16193 (apply 'encode-time (org-parse-time-string s))
16194 (error (error "Bad timestamp `%s'%s\nError was: %s"
16195 s (if (not (and buffer pos))
16197 (format " at %d in buffer `%s'" pos buffer))
16198 (cdr errdata)))))
16200 (defun org-time-string-to-seconds (s)
16201 (org-float-time (org-time-string-to-time s)))
16203 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16204 "Convert a time stamp to an absolute day number.
16205 If there is a specifier for a cyclic time stamp, get the closest date to
16206 DAYNR.
16207 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16208 The variable date is bound by the calendar when this is called."
16209 (cond
16210 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16211 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16212 daynr
16213 (+ daynr 1000)))
16214 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16215 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16216 (time-to-days (current-time))) (match-string 0 s)
16217 prefer show-all))
16218 (t (time-to-days
16219 (condition-case errdata
16220 (apply 'encode-time (org-parse-time-string s))
16221 (error (error "Bad timestamp `%s'%s\nError was: %s"
16222 s (if (not (and buffer pos))
16224 (format " at %d in buffer `%s'" pos buffer))
16225 (cdr errdata))))))))
16227 (defun org-days-to-iso-week (days)
16228 "Return the iso week number."
16229 (require 'cal-iso)
16230 (car (calendar-iso-from-absolute days)))
16232 (defun org-small-year-to-year (year)
16233 "Convert 2-digit years into 4-digit years.
16234 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16235 The year 2000 cannot be abbreviated. Any year larger than 99
16236 is returned unchanged."
16237 (if (< year 38)
16238 (setq year (+ 2000 year))
16239 (if (< year 100)
16240 (setq year (+ 1900 year))))
16241 year)
16243 (defun org-time-from-absolute (d)
16244 "Return the time corresponding to date D.
16245 D may be an absolute day number, or a calendar-type list (month day year)."
16246 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16247 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16249 (defun org-calendar-holiday ()
16250 "List of holidays, for Diary display in Org-mode."
16251 (require 'holidays)
16252 (let ((hl (funcall
16253 (if (fboundp 'calendar-check-holidays)
16254 'calendar-check-holidays 'check-calendar-holidays) date)))
16255 (if hl (mapconcat 'identity hl "; "))))
16257 (defun org-diary-sexp-entry (sexp entry date)
16258 "Process a SEXP diary ENTRY for DATE."
16259 (require 'diary-lib)
16260 (let ((result (if calendar-debug-sexp
16261 (let ((stack-trace-on-error t))
16262 (eval (car (read-from-string sexp))))
16263 (condition-case nil
16264 (eval (car (read-from-string sexp)))
16265 (error
16266 (beep)
16267 (message "Bad sexp at line %d in %s: %s"
16268 (org-current-line)
16269 (buffer-file-name) sexp)
16270 (sleep-for 2))))))
16271 (cond ((stringp result) (split-string result "; "))
16272 ((and (consp result)
16273 (not (consp (cdr result)))
16274 (stringp (cdr result))) (cdr result))
16275 ((and (consp result)
16276 (stringp (car result))) result)
16277 (result entry))))
16279 (defun org-diary-to-ical-string (frombuf)
16280 "Get iCalendar entries from diary entries in buffer FROMBUF.
16281 This uses the icalendar.el library."
16282 (let* ((tmpdir (if (featurep 'xemacs)
16283 (temp-directory)
16284 temporary-file-directory))
16285 (tmpfile (make-temp-name
16286 (expand-file-name "orgics" tmpdir)))
16287 buf rtn b e)
16288 (with-current-buffer frombuf
16289 (icalendar-export-region (point-min) (point-max) tmpfile)
16290 (setq buf (find-buffer-visiting tmpfile))
16291 (set-buffer buf)
16292 (goto-char (point-min))
16293 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16294 (setq b (match-beginning 0)))
16295 (goto-char (point-max))
16296 (if (re-search-backward "^END:VEVENT" nil t)
16297 (setq e (match-end 0)))
16298 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16299 (kill-buffer buf)
16300 (delete-file tmpfile)
16301 rtn))
16303 (defun org-closest-date (start current change prefer show-all)
16304 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16305 When PREFER is `past', return a date that is either CURRENT or past.
16306 When PREFER is `future', return a date that is either CURRENT or future.
16307 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16308 ;; Make the proper lists from the dates
16309 (catch 'exit
16310 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16311 dn dw sday cday n1 n2 n0
16312 d m y y1 y2 date1 date2 nmonths nm ny m2)
16314 (setq start (org-date-to-gregorian start)
16315 current (org-date-to-gregorian
16316 (if show-all
16317 current
16318 (time-to-days (current-time))))
16319 sday (calendar-absolute-from-gregorian start)
16320 cday (calendar-absolute-from-gregorian current))
16322 (if (<= cday sday) (throw 'exit sday))
16324 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16325 (setq dn (string-to-number (match-string 1 change))
16326 dw (cdr (assoc (match-string 2 change) a1)))
16327 (error "Invalid change specifier: %s" change))
16328 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16329 (cond
16330 ((eq dw 'day)
16331 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16332 n2 (+ n1 dn)))
16333 ((eq dw 'year)
16334 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16335 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16336 (setq date1 (list m d y1)
16337 n1 (calendar-absolute-from-gregorian date1)
16338 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16339 n2 (calendar-absolute-from-gregorian date2)))
16340 ((eq dw 'month)
16341 ;; approx number of month between the two dates
16342 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16343 ;; How often does dn fit in there?
16344 (setq d (nth 1 start) m (car start) y (nth 2 start)
16345 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16346 m (+ m nm)
16347 ny (floor (/ m 12))
16348 y (+ y ny)
16349 m (- m (* ny 12)))
16350 (while (> m 12) (setq m (- m 12) y (1+ y)))
16351 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16352 (setq m2 (+ m dn) y2 y)
16353 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16354 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16355 (while (<= n2 cday)
16356 (setq n1 n2 m m2 y y2)
16357 (setq m2 (+ m dn) y2 y)
16358 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16359 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16360 ;; Make sure n1 is the earlier date
16361 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16362 (if show-all
16363 (cond
16364 ((eq prefer 'past) (if (= cday n2) n2 n1))
16365 ((eq prefer 'future) (if (= cday n1) n1 n2))
16366 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16367 (cond
16368 ((eq prefer 'past) (if (= cday n2) n2 n1))
16369 ((eq prefer 'future) (if (= cday n1) n1 n2))
16370 (t (if (= cday n1) n1 n2)))))))
16372 (defun org-date-to-gregorian (date)
16373 "Turn any specification of DATE into a Gregorian date for the calendar."
16374 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16375 ((and (listp date) (= (length date) 3)) date)
16376 ((stringp date)
16377 (setq date (org-parse-time-string date))
16378 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16379 ((listp date)
16380 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16382 (defun org-parse-time-string (s &optional nodefault)
16383 "Parse the standard Org-mode time string.
16384 This should be a lot faster than the normal `parse-time-string'.
16385 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16386 hour and minute fields will be nil if not given."
16387 (if (string-match org-ts-regexp0 s)
16388 (list 0
16389 (if (or (match-beginning 8) (not nodefault))
16390 (string-to-number (or (match-string 8 s) "0")))
16391 (if (or (match-beginning 7) (not nodefault))
16392 (string-to-number (or (match-string 7 s) "0")))
16393 (string-to-number (match-string 4 s))
16394 (string-to-number (match-string 3 s))
16395 (string-to-number (match-string 2 s))
16396 nil nil nil)
16397 (error "Not a standard Org-mode time string: %s" s)))
16399 (defun org-timestamp-up (&optional arg)
16400 "Increase the date item at the cursor by one.
16401 If the cursor is on the year, change the year. If it is on the month,
16402 the day or the time, change that.
16403 With prefix ARG, change by that many units."
16404 (interactive "p")
16405 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16407 (defun org-timestamp-down (&optional arg)
16408 "Decrease the date item at the cursor by one.
16409 If the cursor is on the year, change the year. If it is on the month,
16410 the day or the time, change that.
16411 With prefix ARG, change by that many units."
16412 (interactive "p")
16413 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16415 (defun org-timestamp-up-day (&optional arg)
16416 "Increase the date in the time stamp by one day.
16417 With prefix ARG, change that many days."
16418 (interactive "p")
16419 (if (and (not (org-at-timestamp-p t))
16420 (org-at-heading-p))
16421 (org-todo 'up)
16422 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16424 (defun org-timestamp-down-day (&optional arg)
16425 "Decrease the date in the time stamp by one day.
16426 With prefix ARG, change that many days."
16427 (interactive "p")
16428 (if (and (not (org-at-timestamp-p t))
16429 (org-at-heading-p))
16430 (org-todo 'down)
16431 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16433 (defun org-at-timestamp-p (&optional inactive-ok)
16434 "Determine if the cursor is in or at a timestamp."
16435 (interactive)
16436 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16437 (pos (point))
16438 (ans (or (looking-at tsr)
16439 (save-excursion
16440 (skip-chars-backward "^[<\n\r\t")
16441 (if (> (point) (point-min)) (backward-char 1))
16442 (and (looking-at tsr)
16443 (> (- (match-end 0) pos) -1))))))
16444 (and ans
16445 (boundp 'org-ts-what)
16446 (setq org-ts-what
16447 (cond
16448 ((= pos (match-beginning 0)) 'bracket)
16449 ;; Point is considered to be "on the bracket" whether
16450 ;; it's really on it or right after it.
16451 ((= pos (1- (match-end 0))) 'bracket)
16452 ((= pos (match-end 0)) 'after)
16453 ((org-pos-in-match-range pos 2) 'year)
16454 ((org-pos-in-match-range pos 3) 'month)
16455 ((org-pos-in-match-range pos 7) 'hour)
16456 ((org-pos-in-match-range pos 8) 'minute)
16457 ((or (org-pos-in-match-range pos 4)
16458 (org-pos-in-match-range pos 5)) 'day)
16459 ((and (> pos (or (match-end 8) (match-end 5)))
16460 (< pos (match-end 0)))
16461 (- pos (or (match-end 8) (match-end 5))))
16462 (t 'day))))
16463 ans))
16465 (defun org-toggle-timestamp-type ()
16466 "Toggle the type (<active> or [inactive]) of a time stamp."
16467 (interactive)
16468 (when (org-at-timestamp-p t)
16469 (let ((beg (match-beginning 0)) (end (match-end 0))
16470 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16471 (save-excursion
16472 (goto-char beg)
16473 (while (re-search-forward "[][<>]" end t)
16474 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16475 t t)))
16476 (message "Timestamp is now %sactive"
16477 (if (equal (char-after beg) ?<) "" "in")))))
16479 (defvar org-clock-history) ; defined in org-clock.el
16480 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16481 (defun org-timestamp-change (n &optional what updown)
16482 "Change the date in the time stamp at point.
16483 The date will be changed by N times WHAT. WHAT can be `day', `month',
16484 `year', `minute', `second'. If WHAT is not given, the cursor position
16485 in the timestamp determines what will be changed."
16486 (let ((origin (point)) origin-cat
16487 with-hm inactive
16488 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16489 org-ts-what
16490 extra rem
16491 ts time time0 fixnext clrgx)
16492 (if (not (org-at-timestamp-p t))
16493 (error "Not at a timestamp"))
16494 (if (and (not what) (eq org-ts-what 'bracket))
16495 (org-toggle-timestamp-type)
16496 ;; Point isn't on brackets. Remember the part of the time-stamp
16497 ;; the point was in. Indeed, size of time-stamps may change,
16498 ;; but point must be kept in the same category nonetheless.
16499 (setq origin-cat org-ts-what)
16500 (if (and (not what) (not (eq org-ts-what 'day))
16501 org-display-custom-times
16502 (get-text-property (point) 'display)
16503 (not (get-text-property (1- (point)) 'display)))
16504 (setq org-ts-what 'day))
16505 (setq org-ts-what (or what org-ts-what)
16506 inactive (= (char-after (match-beginning 0)) ?\[)
16507 ts (match-string 0))
16508 (replace-match "")
16509 (if (string-match
16510 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16512 (setq extra (match-string 1 ts)))
16513 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16514 (setq with-hm t))
16515 (setq time0 (org-parse-time-string ts))
16516 (when (and updown
16517 (eq org-ts-what 'minute)
16518 (not current-prefix-arg))
16519 ;; This looks like s-up and s-down. Change by one rounding step.
16520 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16521 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16522 (setcar (cdr time0) (+ (nth 1 time0)
16523 (if (> n 0) (- rem) (- dm rem))))))
16524 (setq time
16525 (encode-time (or (car time0) 0)
16526 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16527 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16528 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16529 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16530 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16531 (nthcdr 6 time0)))
16532 (when (and (member org-ts-what '(hour minute))
16533 extra
16534 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16535 (setq extra (org-modify-ts-extra
16536 extra
16537 (if (eq org-ts-what 'hour) 2 5)
16538 n dm)))
16539 (when (integerp org-ts-what)
16540 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16541 (if (eq what 'calendar)
16542 (let ((cal-date (org-get-date-from-calendar)))
16543 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16544 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16545 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16546 (setcar time0 (or (car time0) 0))
16547 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16548 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16549 (setq time (apply 'encode-time time0))))
16550 ;; Insert the new time-stamp, and ensure point stays in the same
16551 ;; category as before (i.e. not after the last position in that
16552 ;; category).
16553 (let ((pos (point)))
16554 ;; Stay before inserted string. `save-excursion' is of no use.
16555 (setq org-last-changed-timestamp
16556 (org-insert-time-stamp time with-hm inactive nil nil extra))
16557 (goto-char pos))
16558 (save-match-data
16559 (looking-at org-ts-regexp3)
16560 (goto-char (cond
16561 ;; `day' category ends before `hour' if any, or at
16562 ;; the end of the day name.
16563 ((eq origin-cat 'day)
16564 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16565 ((eq origin-cat 'hour) (min (match-end 7) origin))
16566 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16567 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16568 ;; `year' and `month' have both fixed size: point
16569 ;; couldn't have moved into another part.
16570 (t origin))))
16571 ;; Update clock if on a CLOCK line.
16572 (org-clock-update-time-maybe)
16573 ;; Maybe adjust the closest clock in `org-clock-history'
16574 (when org-clock-adjust-closest
16575 (if (not (and (org-at-clock-log-p)
16576 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16577 org-clock-history))))))
16578 (message "No clock to adjust")
16579 (cond ((save-excursion ; fix previous clock?
16580 (re-search-backward org-ts-regexp0 nil t)
16581 (org-looking-back (concat org-clock-string " \\[")))
16582 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16583 ((save-excursion ; fix next clock?
16584 (re-search-backward org-ts-regexp0 nil t)
16585 (looking-at (concat org-ts-regexp0 "\\] =>")))
16586 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16587 (save-window-excursion
16588 ;; Find closest clock to point, adjust the previous/next one in history
16589 (let* ((p (save-excursion (org-back-to-heading t)))
16590 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16591 (clfixnth
16592 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16593 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16594 (if (not clfixpos)
16595 (message "No clock to adjust")
16596 (save-excursion
16597 (org-goto-marker-or-bmk clfixpos)
16598 (org-show-subtree)
16599 (when (re-search-forward clrgx nil t)
16600 (goto-char (match-beginning 1))
16601 (let (org-clock-adjust-closest)
16602 (org-timestamp-change n org-ts-what updown))
16603 (message "Clock adjusted in %s for heading: %s"
16604 (file-name-nondirectory (buffer-file-name))
16605 (org-get-heading t t)))))))))
16606 ;; Try to recenter the calendar window, if any.
16607 (if (and org-calendar-follow-timestamp-change
16608 (get-buffer-window "*Calendar*" t)
16609 (memq org-ts-what '(day month year)))
16610 (org-recenter-calendar (time-to-days time))))))
16612 (defun org-modify-ts-extra (s pos n dm)
16613 "Change the different parts of the lead-time and repeat fields in timestamp."
16614 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16615 ng h m new rem)
16616 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16617 (cond
16618 ((or (org-pos-in-match-range pos 2)
16619 (org-pos-in-match-range pos 3))
16620 (setq m (string-to-number (match-string 3 s))
16621 h (string-to-number (match-string 2 s)))
16622 (if (org-pos-in-match-range pos 2)
16623 (setq h (+ h n))
16624 (setq n (* dm (org-no-warnings (signum n))))
16625 (when (not (= 0 (setq rem (% m dm))))
16626 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16627 (setq m (+ m n)))
16628 (if (< m 0) (setq m (+ m 60) h (1- h)))
16629 (if (> m 59) (setq m (- m 60) h (1+ h)))
16630 (setq h (min 24 (max 0 h)))
16631 (setq ng 1 new (format "-%02d:%02d" h m)))
16632 ((org-pos-in-match-range pos 6)
16633 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16634 ((org-pos-in-match-range pos 5)
16635 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16637 ((org-pos-in-match-range pos 9)
16638 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16639 ((org-pos-in-match-range pos 8)
16640 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16642 (when ng
16643 (setq s (concat
16644 (substring s 0 (match-beginning ng))
16646 (substring s (match-end ng))))))
16649 (defun org-recenter-calendar (date)
16650 "If the calendar is visible, recenter it to DATE."
16651 (let ((cwin (get-buffer-window "*Calendar*" t)))
16652 (when cwin
16653 (let ((calendar-move-hook nil))
16654 (with-selected-window cwin
16655 (calendar-goto-date (if (listp date) date
16656 (calendar-gregorian-from-absolute date))))))))
16658 (defun org-goto-calendar (&optional arg)
16659 "Go to the Emacs calendar at the current date.
16660 If there is a time stamp in the current line, go to that date.
16661 A prefix ARG can be used to force the current date."
16662 (interactive "P")
16663 (let ((tsr org-ts-regexp) diff
16664 (calendar-move-hook nil)
16665 (calendar-view-holidays-initially-flag nil)
16666 (calendar-view-diary-initially-flag nil))
16667 (if (or (org-at-timestamp-p)
16668 (save-excursion
16669 (beginning-of-line 1)
16670 (looking-at (concat ".*" tsr))))
16671 (let ((d1 (time-to-days (current-time)))
16672 (d2 (time-to-days
16673 (org-time-string-to-time (match-string 1)))))
16674 (setq diff (- d2 d1))))
16675 (calendar)
16676 (calendar-goto-today)
16677 (if (and diff (not arg)) (calendar-forward-day diff))))
16679 (defun org-get-date-from-calendar ()
16680 "Return a list (month day year) of date at point in calendar."
16681 (with-current-buffer "*Calendar*"
16682 (save-match-data
16683 (calendar-cursor-to-date))))
16685 (defun org-date-from-calendar ()
16686 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16687 If there is already a time stamp at the cursor position, update it."
16688 (interactive)
16689 (if (org-at-timestamp-p t)
16690 (org-timestamp-change 0 'calendar)
16691 (let ((cal-date (org-get-date-from-calendar)))
16692 (org-insert-time-stamp
16693 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16695 (defun org-minutes-to-hh:mm-string (m)
16696 "Compute H:MM from a number of minutes."
16697 (let ((h (/ m 60)))
16698 (setq m (- m (* 60 h)))
16699 (format org-time-clocksum-format h m)))
16701 (defun org-hh:mm-string-to-minutes (s)
16702 "Convert a string H:MM to a number of minutes.
16703 If the string is just a number, interpret it as minutes.
16704 In fact, the first hh:mm or number in the string will be taken,
16705 there can be extra stuff in the string.
16706 If no number is found, the return value is 0."
16707 (cond
16708 ((integerp s) s)
16709 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16710 (+ (* (string-to-number (match-string 1 s)) 60)
16711 (string-to-number (match-string 2 s))))
16712 ((string-match "\\([0-9]+\\)" s)
16713 (string-to-number (match-string 1 s)))
16714 (t 0)))
16716 (defcustom org-effort-durations
16717 `(("h" . 60)
16718 ("d" . ,(* 60 8))
16719 ("w" . ,(* 60 8 5))
16720 ("m" . ,(* 60 8 5 4))
16721 ("y" . ,(* 60 8 5 40)))
16722 "Conversion factor to minutes for an effort modifier.
16724 Each entry has the form (MODIFIER . MINUTES).
16726 In an effort string, a number followed by MODIFIER is multiplied
16727 by the specified number of MINUTES to obtain an effort in
16728 minutes.
16730 For example, if the value of this variable is ((\"hours\" . 60)), then an
16731 effort string \"2hours\" is equivalent to 120 minutes."
16732 :group 'org-agenda
16733 :version "24.1"
16734 :type '(alist :key-type (string :tag "Modifier")
16735 :value-type (number :tag "Minutes")))
16737 (defun org-duration-string-to-minutes (s &optional output-to-string)
16738 "Convert a duration string S to minutes.
16740 A bare number is interpreted as minutes, modifiers can be set by
16741 customizing `org-effort-durations' (which see).
16743 Entries containing a colon are interpreted as H:MM by
16744 `org-hh:mm-string-to-minutes'."
16745 (let ((result 0)
16746 (re (concat "\\([0-9.]+\\) *\\("
16747 (regexp-opt (mapcar 'car org-effort-durations))
16748 "\\)")))
16749 (while (string-match re s)
16750 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16751 (string-to-number (match-string 1 s))))
16752 (setq s (replace-match "" nil t s)))
16753 (setq result (floor result))
16754 (incf result (org-hh:mm-string-to-minutes s))
16755 (if output-to-string (number-to-string result) result)))
16757 ;;;; Files
16759 (defun org-save-all-org-buffers ()
16760 "Save all Org-mode buffers without user confirmation."
16761 (interactive)
16762 (message "Saving all Org-mode buffers...")
16763 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16764 (when (featurep 'org-id) (org-id-locations-save))
16765 (message "Saving all Org-mode buffers... done"))
16767 (defun org-revert-all-org-buffers ()
16768 "Revert all Org-mode buffers.
16769 Prompt for confirmation when there are unsaved changes.
16770 Be sure you know what you are doing before letting this function
16771 overwrite your changes.
16773 This function is useful in a setup where one tracks org files
16774 with a version control system, to revert on one machine after pulling
16775 changes from another. I believe the procedure must be like this:
16777 1. M-x org-save-all-org-buffers
16778 2. Pull changes from the other machine, resolve conflicts
16779 3. M-x org-revert-all-org-buffers"
16780 (interactive)
16781 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16782 (error "Abort"))
16783 (save-excursion
16784 (save-window-excursion
16785 (mapc
16786 (lambda (b)
16787 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16788 (with-current-buffer b buffer-file-name))
16789 (org-pop-to-buffer-same-window b)
16790 (revert-buffer t 'no-confirm)))
16791 (buffer-list))
16792 (when (and (featurep 'org-id) org-id-track-globally)
16793 (org-id-locations-load)))))
16795 ;;;; Agenda files
16797 ;;;###autoload
16798 (defun org-switchb (&optional arg)
16799 "Switch between Org buffers.
16800 With one prefix argument, restrict available buffers to files.
16801 With two prefix arguments, restrict available buffers to agenda files.
16803 Defaults to `iswitchb' for buffer name completion.
16804 Set `org-completion-use-ido' to make it use ido instead."
16805 (interactive "P")
16806 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16807 ((equal arg '(16)) (org-buffer-list 'agenda))
16808 (t (org-buffer-list))))
16809 (org-completion-use-iswitchb org-completion-use-iswitchb)
16810 (org-completion-use-ido org-completion-use-ido))
16811 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16812 (setq org-completion-use-iswitchb t))
16813 (org-pop-to-buffer-same-window
16814 (org-icompleting-read "Org buffer: "
16815 (mapcar 'list (mapcar 'buffer-name blist))
16816 nil t))))
16818 ;;; Define some older names previously used for this functionality
16819 ;;;###autoload
16820 (defalias 'org-ido-switchb 'org-switchb)
16821 ;;;###autoload
16822 (defalias 'org-iswitchb 'org-switchb)
16824 (defun org-buffer-list (&optional predicate exclude-tmp)
16825 "Return a list of Org buffers.
16826 PREDICATE can be `export', `files' or `agenda'.
16828 export restrict the list to Export buffers.
16829 files restrict the list to buffers visiting Org files.
16830 agenda restrict the list to buffers visiting agenda files.
16832 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16833 (let* ((bfn nil)
16834 (agenda-files (and (eq predicate 'agenda)
16835 (mapcar 'file-truename (org-agenda-files t))))
16836 (filter
16837 (cond
16838 ((eq predicate 'files)
16839 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16840 ((eq predicate 'export)
16841 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16842 ((eq predicate 'agenda)
16843 (lambda (b)
16844 (with-current-buffer b
16845 (and (derived-mode-p 'org-mode)
16846 (setq bfn (buffer-file-name b))
16847 (member (file-truename bfn) agenda-files)))))
16848 (t (lambda (b) (with-current-buffer b
16849 (or (derived-mode-p 'org-mode)
16850 (string-match "\*Org .*Export"
16851 (buffer-name b)))))))))
16852 (delq nil
16853 (mapcar
16854 (lambda(b)
16855 (if (and (funcall filter b)
16856 (or (not exclude-tmp)
16857 (not (string-match "tmp" (buffer-name b)))))
16859 nil))
16860 (buffer-list)))))
16862 (defun org-agenda-files (&optional unrestricted archives)
16863 "Get the list of agenda files.
16864 Optional UNRESTRICTED means return the full list even if a restriction
16865 is currently in place.
16866 When ARCHIVES is t, include all archive files that are really being
16867 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16868 `org-agenda-archives-mode' is t."
16869 (let ((files
16870 (cond
16871 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16872 ((stringp org-agenda-files) (org-read-agenda-file-list))
16873 ((listp org-agenda-files) org-agenda-files)
16874 (t (error "Invalid value of `org-agenda-files'")))))
16875 (setq files (apply 'append
16876 (mapcar (lambda (f)
16877 (if (file-directory-p f)
16878 (directory-files
16879 f t org-agenda-file-regexp)
16880 (list f)))
16881 files)))
16882 (when org-agenda-skip-unavailable-files
16883 (setq files (delq nil
16884 (mapcar (function
16885 (lambda (file)
16886 (and (file-readable-p file) file)))
16887 files))))
16888 (when (or (eq archives t)
16889 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16890 (setq files (org-add-archive-files files)))
16891 files))
16893 (defun org-agenda-file-p (&optional file)
16894 "Return non-nil, if FILE is an agenda file.
16895 If FILE is omitted, use the file associated with the current
16896 buffer."
16897 (member (or file (buffer-file-name))
16898 (org-agenda-files t)))
16900 (defun org-edit-agenda-file-list ()
16901 "Edit the list of agenda files.
16902 Depending on setup, this either uses customize to edit the variable
16903 `org-agenda-files', or it visits the file that is holding the list. In the
16904 latter case, the buffer is set up in a way that saving it automatically kills
16905 the buffer and restores the previous window configuration."
16906 (interactive)
16907 (if (stringp org-agenda-files)
16908 (let ((cw (current-window-configuration)))
16909 (find-file org-agenda-files)
16910 (org-set-local 'org-window-configuration cw)
16911 (org-add-hook 'after-save-hook
16912 (lambda ()
16913 (set-window-configuration
16914 (prog1 org-window-configuration
16915 (kill-buffer (current-buffer))))
16916 (org-install-agenda-files-menu)
16917 (message "New agenda file list installed"))
16918 nil 'local)
16919 (message "%s" (substitute-command-keys
16920 "Edit list and finish with \\[save-buffer]")))
16921 (customize-variable 'org-agenda-files)))
16923 (defun org-store-new-agenda-file-list (list)
16924 "Set new value for the agenda file list and save it correctly."
16925 (if (stringp org-agenda-files)
16926 (let ((fe (org-read-agenda-file-list t)) b u)
16927 (while (setq b (find-buffer-visiting org-agenda-files))
16928 (kill-buffer b))
16929 (with-temp-file org-agenda-files
16930 (insert
16931 (mapconcat
16932 (lambda (f) ;; Keep un-expanded entries.
16933 (if (setq u (assoc f fe))
16934 (cdr u)
16936 list "\n")
16937 "\n")))
16938 (let ((org-mode-hook nil) (org-inhibit-startup t)
16939 (org-insert-mode-line-in-empty-file nil))
16940 (setq org-agenda-files list)
16941 (customize-save-variable 'org-agenda-files org-agenda-files))))
16943 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16944 "Read the list of agenda files from a file.
16945 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16946 filenames, used by `org-store-new-agenda-file-list' to write back
16947 un-expanded file names."
16948 (when (file-directory-p org-agenda-files)
16949 (error "`org-agenda-files' cannot be a single directory"))
16950 (when (stringp org-agenda-files)
16951 (with-temp-buffer
16952 (insert-file-contents org-agenda-files)
16953 (mapcar
16954 (lambda (f)
16955 (let ((e (expand-file-name (substitute-in-file-name f)
16956 org-directory)))
16957 (if pair-with-expansion
16958 (cons e f)
16959 e)))
16960 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16962 ;;;###autoload
16963 (defun org-cycle-agenda-files ()
16964 "Cycle through the files in `org-agenda-files'.
16965 If the current buffer visits an agenda file, find the next one in the list.
16966 If the current buffer does not, find the first agenda file."
16967 (interactive)
16968 (let* ((fs (org-agenda-files t))
16969 (files (append fs (list (car fs))))
16970 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16971 file)
16972 (unless files (error "No agenda files"))
16973 (catch 'exit
16974 (while (setq file (pop files))
16975 (if (equal (file-truename file) tcf)
16976 (when (car files)
16977 (find-file (car files))
16978 (throw 'exit t))))
16979 (find-file (car fs)))
16980 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16982 (defun org-agenda-file-to-front (&optional to-end)
16983 "Move/add the current file to the top of the agenda file list.
16984 If the file is not present in the list, it is added to the front. If it is
16985 present, it is moved there. With optional argument TO-END, add/move to the
16986 end of the list."
16987 (interactive "P")
16988 (let ((org-agenda-skip-unavailable-files nil)
16989 (file-alist (mapcar (lambda (x)
16990 (cons (file-truename x) x))
16991 (org-agenda-files t)))
16992 (ctf (file-truename buffer-file-name))
16993 x had)
16994 (setq x (assoc ctf file-alist) had x)
16996 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16997 (if to-end
16998 (setq file-alist (append (delq x file-alist) (list x)))
16999 (setq file-alist (cons x (delq x file-alist))))
17000 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17001 (org-install-agenda-files-menu)
17002 (message "File %s to %s of agenda file list"
17003 (if had "moved" "added") (if to-end "end" "front"))))
17005 (defun org-remove-file (&optional file)
17006 "Remove current file from the list of files in variable `org-agenda-files'.
17007 These are the files which are being checked for agenda entries.
17008 Optional argument FILE means use this file instead of the current."
17009 (interactive)
17010 (let* ((org-agenda-skip-unavailable-files nil)
17011 (file (or file buffer-file-name))
17012 (true-file (file-truename file))
17013 (afile (abbreviate-file-name file))
17014 (files (delq nil (mapcar
17015 (lambda (x)
17016 (if (equal true-file
17017 (file-truename x))
17018 nil x))
17019 (org-agenda-files t)))))
17020 (if (not (= (length files) (length (org-agenda-files t))))
17021 (progn
17022 (org-store-new-agenda-file-list files)
17023 (org-install-agenda-files-menu)
17024 (message "Removed file: %s" afile))
17025 (message "File was not in list: %s (not removed)" afile))))
17027 (defun org-file-menu-entry (file)
17028 (vector file (list 'find-file file) t))
17030 (defun org-check-agenda-file (file)
17031 "Make sure FILE exists. If not, ask user what to do."
17032 (when (not (file-exists-p file))
17033 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17034 (abbreviate-file-name file))
17035 (let ((r (downcase (read-char-exclusive))))
17036 (cond
17037 ((equal r ?r)
17038 (org-remove-file file)
17039 (throw 'nextfile t))
17040 (t (error "Abort"))))))
17042 (defun org-get-agenda-file-buffer (file)
17043 "Get a buffer visiting FILE. If the buffer needs to be created, add
17044 it to the list of buffers which might be released later."
17045 (let ((buf (org-find-base-buffer-visiting file)))
17046 (if buf
17047 buf ; just return it
17048 ;; Make a new buffer and remember it
17049 (setq buf (find-file-noselect file))
17050 (if buf (push buf org-agenda-new-buffers))
17051 buf)))
17053 (defun org-release-buffers (blist)
17054 "Release all buffers in list, asking the user for confirmation when needed.
17055 When a buffer is unmodified, it is just killed. When modified, it is saved
17056 \(if the user agrees) and then killed."
17057 (let (buf file)
17058 (while (setq buf (pop blist))
17059 (setq file (buffer-file-name buf))
17060 (when (and (buffer-modified-p buf)
17061 file
17062 (y-or-n-p (format "Save file %s? " file)))
17063 (with-current-buffer buf (save-buffer)))
17064 (kill-buffer buf))))
17066 (defun org-agenda-prepare-buffers (files)
17067 "Create buffers for all agenda files, protect archived trees and comments."
17068 (interactive)
17069 (let ((pa '(:org-archived t))
17070 (pc '(:org-comment t))
17071 (pall '(:org-archived t :org-comment t))
17072 (inhibit-read-only t)
17073 (rea (concat ":" org-archive-tag ":"))
17074 bmp file re)
17075 (save-excursion
17076 (save-restriction
17077 (while (setq file (pop files))
17078 (catch 'nextfile
17079 (if (bufferp file)
17080 (set-buffer file)
17081 (org-check-agenda-file file)
17082 (set-buffer (org-get-agenda-file-buffer file)))
17083 (widen)
17084 (setq bmp (buffer-modified-p))
17085 (org-refresh-category-properties)
17086 (setq org-todo-keywords-for-agenda
17087 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17088 (setq org-done-keywords-for-agenda
17089 (append org-done-keywords-for-agenda org-done-keywords))
17090 (setq org-todo-keyword-alist-for-agenda
17091 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17092 (setq org-drawers-for-agenda
17093 (append org-drawers-for-agenda org-drawers))
17094 (setq org-tag-alist-for-agenda
17095 (append org-tag-alist-for-agenda org-tag-alist))
17097 (save-excursion
17098 (remove-text-properties (point-min) (point-max) pall)
17099 (when org-agenda-skip-archived-trees
17100 (goto-char (point-min))
17101 (while (re-search-forward rea nil t)
17102 (if (org-at-heading-p t)
17103 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17104 (goto-char (point-min))
17105 (setq re (format org-heading-keyword-regexp-format
17106 org-comment-string))
17107 (while (re-search-forward re nil t)
17108 (add-text-properties
17109 (match-beginning 0) (org-end-of-subtree t) pc)))
17110 (set-buffer-modified-p bmp)))))
17111 (setq org-todo-keywords-for-agenda
17112 (org-uniquify org-todo-keywords-for-agenda))
17113 (setq org-todo-keyword-alist-for-agenda
17114 (org-uniquify org-todo-keyword-alist-for-agenda)
17115 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17117 ;;;; Embedded LaTeX
17119 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17120 "Keymap for the minor `org-cdlatex-mode'.")
17122 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17123 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17124 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17125 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17126 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17128 (defvar org-cdlatex-texmathp-advice-is-done nil
17129 "Flag remembering if we have applied the advice to texmathp already.")
17131 (define-minor-mode org-cdlatex-mode
17132 "Toggle the minor `org-cdlatex-mode'.
17133 This mode supports entering LaTeX environment and math in LaTeX fragments
17134 in Org-mode.
17135 \\{org-cdlatex-mode-map}"
17136 nil " OCDL" nil
17137 (when org-cdlatex-mode
17138 (require 'cdlatex)
17139 (run-hooks 'cdlatex-mode-hook)
17140 (cdlatex-compute-tables))
17141 (unless org-cdlatex-texmathp-advice-is-done
17142 (setq org-cdlatex-texmathp-advice-is-done t)
17143 (defadvice texmathp (around org-math-always-on activate)
17144 "Always return t in org-mode buffers.
17145 This is because we want to insert math symbols without dollars even outside
17146 the LaTeX math segments. If Orgmode thinks that point is actually inside
17147 an embedded LaTeX fragment, let texmathp do its job.
17148 \\[org-cdlatex-mode-map]"
17149 (interactive)
17150 (let (p)
17151 (cond
17152 ((not (derived-mode-p 'org-mode)) ad-do-it)
17153 ((eq this-command 'cdlatex-math-symbol)
17154 (setq ad-return-value t
17155 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17157 (let ((p (org-inside-LaTeX-fragment-p)))
17158 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17159 (setq ad-return-value t
17160 texmathp-why '("Org-mode embedded math" . 0))
17161 (if p ad-do-it)))))))))
17163 (defun turn-on-org-cdlatex ()
17164 "Unconditionally turn on `org-cdlatex-mode'."
17165 (org-cdlatex-mode 1))
17167 (defun org-inside-LaTeX-fragment-p ()
17168 "Test if point is inside a LaTeX fragment.
17169 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17170 sequence appearing also before point.
17171 Even though the matchers for math are configurable, this function assumes
17172 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17173 delimiters are skipped when they have been removed by customization.
17174 The return value is nil, or a cons cell with the delimiter and the
17175 position of this delimiter.
17177 This function does a reasonably good job, but can locally be fooled by
17178 for example currency specifications. For example it will assume being in
17179 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17180 fragments that are properly closed, but during editing, we have to live
17181 with the uncertainty caused by missing closing delimiters. This function
17182 looks only before point, not after."
17183 (catch 'exit
17184 (let ((pos (point))
17185 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17186 (lim (progn
17187 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17188 (point)))
17189 dd-on str (start 0) m re)
17190 (goto-char pos)
17191 (when dodollar
17192 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17193 re (nth 1 (assoc "$" org-latex-regexps)))
17194 (while (string-match re str start)
17195 (cond
17196 ((= (match-end 0) (length str))
17197 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17198 ((= (match-end 0) (- (length str) 5))
17199 (throw 'exit nil))
17200 (t (setq start (match-end 0))))))
17201 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17202 (goto-char pos)
17203 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17204 (and (match-beginning 2) (throw 'exit nil))
17205 ;; count $$
17206 (while (re-search-backward "\\$\\$" lim t)
17207 (setq dd-on (not dd-on)))
17208 (goto-char pos)
17209 (if dd-on (cons "$$" m))))))
17211 (defun org-inside-latex-macro-p ()
17212 "Is point inside a LaTeX macro or its arguments?"
17213 (save-match-data
17214 (org-in-regexp
17215 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17217 (defun org-try-cdlatex-tab ()
17218 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17219 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17220 - inside a LaTeX fragment, or
17221 - after the first word in a line, where an abbreviation expansion could
17222 insert a LaTeX environment."
17223 (when org-cdlatex-mode
17224 (cond
17225 ;; Before any word on the line: No expansion possible.
17226 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17227 ;; Just after first word on the line: Expand it. Make sure it
17228 ;; cannot happen on headlines, though.
17229 ((save-excursion
17230 (skip-chars-backward "a-zA-Z0-9*")
17231 (skip-chars-backward " \t")
17232 (and (bolp) (not (org-at-heading-p))))
17233 (cdlatex-tab) t)
17234 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17236 (defun org-cdlatex-underscore-caret (&optional arg)
17237 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17238 Revert to the normal definition outside of these fragments."
17239 (interactive "P")
17240 (if (org-inside-LaTeX-fragment-p)
17241 (call-interactively 'cdlatex-sub-superscript)
17242 (let (org-cdlatex-mode)
17243 (call-interactively (key-binding (vector last-input-event))))))
17245 (defun org-cdlatex-math-modify (&optional arg)
17246 "Execute `cdlatex-math-modify' in LaTeX fragments.
17247 Revert to the normal definition outside of these fragments."
17248 (interactive "P")
17249 (if (org-inside-LaTeX-fragment-p)
17250 (call-interactively 'cdlatex-math-modify)
17251 (let (org-cdlatex-mode)
17252 (call-interactively (key-binding (vector last-input-event))))))
17254 (defvar org-latex-fragment-image-overlays nil
17255 "List of overlays carrying the images of latex fragments.")
17256 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17258 (defun org-remove-latex-fragment-image-overlays ()
17259 "Remove all overlays with LaTeX fragment images in current buffer."
17260 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17261 (setq org-latex-fragment-image-overlays nil))
17263 (defun org-preview-latex-fragment (&optional subtree)
17264 "Preview the LaTeX fragment at point, or all locally or globally.
17265 If the cursor is in a LaTeX fragment, create the image and overlay
17266 it over the source code. If there is no fragment at point, display
17267 all fragments in the current text, from one headline to the next. With
17268 prefix SUBTREE, display all fragments in the current subtree. With a
17269 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17270 the cursor is before the first headline,
17271 display all fragments in the buffer.
17272 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17273 (interactive "P")
17274 (unless buffer-file-name
17275 (error "Can't preview LaTeX fragment in a non-file buffer"))
17276 (org-remove-latex-fragment-image-overlays)
17277 (save-excursion
17278 (save-restriction
17279 (let (beg end at msg)
17280 (cond
17281 ((or (equal subtree '(16))
17282 (not (save-excursion
17283 (re-search-backward org-outline-regexp-bol nil t))))
17284 (setq beg (point-min) end (point-max)
17285 msg "Creating images for buffer...%s"))
17286 ((equal subtree '(4))
17287 (org-back-to-heading)
17288 (setq beg (point) end (org-end-of-subtree t)
17289 msg "Creating images for subtree...%s"))
17291 (if (setq at (org-inside-LaTeX-fragment-p))
17292 (goto-char (max (point-min) (- (cdr at) 2)))
17293 (org-back-to-heading))
17294 (setq beg (point) end (progn (outline-next-heading) (point))
17295 msg (if at "Creating image...%s"
17296 "Creating images for entry...%s"))))
17297 (message msg "")
17298 (narrow-to-region beg end)
17299 (goto-char beg)
17300 (org-format-latex
17301 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17302 (file-name-nondirectory
17303 buffer-file-name)))
17304 default-directory 'overlays msg at 'forbuffer
17305 org-latex-create-formula-image-program)
17306 (message msg "done. Use `C-c C-c' to remove images.")))))
17308 (defvar org-latex-regexps
17309 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17310 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17311 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17312 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17313 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17314 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17315 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17316 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17317 "Regular expressions for matching embedded LaTeX.")
17319 (defvar org-export-have-math nil) ;; dynamic scoping
17320 (defun org-format-latex (prefix &optional dir overlays msg at
17321 forbuffer processing-type)
17322 "Replace LaTeX fragments with links to an image, and produce images.
17323 Some of the options can be changed using the variable
17324 `org-format-latex-options'."
17325 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17326 (let* ((prefixnodir (file-name-nondirectory prefix))
17327 (absprefix (expand-file-name prefix dir))
17328 (todir (file-name-directory absprefix))
17329 (opt org-format-latex-options)
17330 (matchers (plist-get opt :matchers))
17331 (re-list org-latex-regexps)
17332 (org-format-latex-header-extra
17333 (plist-get (org-infile-export-plist) :latex-header-extra))
17334 (cnt 0) txt hash link beg end re e checkdir
17335 executables-checked string
17336 m n block-type block linkfile movefile ov)
17337 ;; Check the different regular expressions
17338 (while (setq e (pop re-list))
17339 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17340 block (if block-type "\n\n" ""))
17341 (when (member m matchers)
17342 (goto-char (point-min))
17343 (while (re-search-forward re nil t)
17344 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17345 (not (get-text-property (match-beginning n)
17346 'org-protected))
17347 (or (not overlays)
17348 (not (eq (get-char-property (match-beginning n)
17349 'org-overlay-type)
17350 'org-latex-overlay))))
17351 (setq org-export-have-math t)
17352 (cond
17353 ((eq processing-type 'verbatim)
17354 ;; Leave the text verbatim, just protect it
17355 (add-text-properties (match-beginning n) (match-end n)
17356 '(org-protected t)))
17357 ((eq processing-type 'mathjax)
17358 ;; Prepare for MathJax processing
17359 (setq string (match-string n))
17360 (if (member m '("$" "$1"))
17361 (save-excursion
17362 (delete-region (match-beginning n) (match-end n))
17363 (goto-char (match-beginning n))
17364 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17365 "\\)")
17366 '(org-protected t))))
17367 (add-text-properties (match-beginning n) (match-end n)
17368 '(org-protected t))))
17369 ((or (eq processing-type 'dvipng)
17370 (eq processing-type 'imagemagick))
17371 ;; Process to an image
17372 (setq txt (match-string n)
17373 beg (match-beginning n) end (match-end n)
17374 cnt (1+ cnt))
17375 (let (print-length print-level) ; make sure full list is printed
17376 (setq hash (sha1 (prin1-to-string
17377 (list org-format-latex-header
17378 org-format-latex-header-extra
17379 org-export-latex-default-packages-alist
17380 org-export-latex-packages-alist
17381 org-format-latex-options
17382 forbuffer txt)))
17383 linkfile (format "%s_%s.png" prefix hash)
17384 movefile (format "%s_%s.png" absprefix hash)))
17385 (setq link (concat block "[[file:" linkfile "]]" block))
17386 (if msg (message msg cnt))
17387 (goto-char beg)
17388 (unless checkdir ; make sure the directory exists
17389 (setq checkdir t)
17390 (or (file-directory-p todir) (make-directory todir t)))
17391 (cond
17392 ((eq processing-type 'dvipng)
17393 (unless executables-checked
17394 (org-check-external-command
17395 "latex" "needed to convert LaTeX fragments to images")
17396 (org-check-external-command
17397 "dvipng" "needed to convert LaTeX fragments to images")
17398 (setq executables-checked t))
17399 (unless (file-exists-p movefile)
17400 (org-create-formula-image-with-dvipng
17401 txt movefile opt forbuffer)))
17402 ((eq processing-type 'imagemagick)
17403 (unless executables-checked
17404 (org-check-external-command
17405 "convert" "you need to install imagemagick")
17406 (setq executables-checked t))
17407 (unless (file-exists-p movefile)
17408 (org-create-formula-image-with-imagemagick
17409 txt movefile opt forbuffer))))
17410 (if overlays
17411 (progn
17412 (mapc (lambda (o)
17413 (if (eq (overlay-get o 'org-overlay-type)
17414 'org-latex-overlay)
17415 (delete-overlay o)))
17416 (overlays-in beg end))
17417 (setq ov (make-overlay beg end))
17418 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17419 (if (featurep 'xemacs)
17420 (progn
17421 (overlay-put ov 'invisible t)
17422 (overlay-put
17423 ov 'end-glyph
17424 (make-glyph (vector 'png :file movefile))))
17425 (overlay-put
17426 ov 'display
17427 (list 'image :type 'png :file movefile :ascent 'center)))
17428 (push ov org-latex-fragment-image-overlays)
17429 (goto-char end))
17430 (delete-region beg end)
17431 (insert (org-add-props link
17432 (list 'org-latex-src
17433 (replace-regexp-in-string
17434 "\"" "" txt)
17435 'org-latex-src-embed-type
17436 (if block-type 'paragraph 'character))))))
17437 ((eq processing-type 'mathml)
17438 ;; Process to MathML
17439 (unless executables-checked
17440 (unless (save-match-data (org-format-latex-mathml-available-p))
17441 (error "LaTeX to MathML converter not configured"))
17442 (setq executables-checked t))
17443 (setq txt (match-string n)
17444 beg (match-beginning n) end (match-end n)
17445 cnt (1+ cnt))
17446 (if msg (message msg cnt))
17447 (goto-char beg)
17448 (delete-region beg end)
17449 (insert (org-format-latex-as-mathml
17450 txt block-type prefix dir)))
17452 (error "Unknown conversion type %s for latex fragments"
17453 processing-type)))))))))
17455 (defun org-create-math-formula (latex-frag &optional mathml-file)
17456 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17457 Use `org-latex-to-mathml-convert-command'. If the conversion is
17458 sucessful, return the portion between \"<math...> </math>\"
17459 elements otherwise return nil. When MATHML-FILE is specified,
17460 write the results in to that file. When invoked as an
17461 interactive command, prompt for LATEX-FRAG, with initial value
17462 set to the current active region and echo the results for user
17463 inspection."
17464 (interactive (list (let ((frag (when (org-region-active-p)
17465 (buffer-substring-no-properties
17466 (region-beginning) (region-end)))))
17467 (read-string "LaTeX Fragment: " frag nil frag))))
17468 (unless latex-frag (error "Invalid latex-frag"))
17469 (let* ((tmp-in-file (file-relative-name
17470 (make-temp-name (expand-file-name "ltxmathml-in"))))
17471 (ignore (write-region latex-frag nil tmp-in-file))
17472 (tmp-out-file (file-relative-name
17473 (make-temp-name (expand-file-name "ltxmathml-out"))))
17474 (cmd (format-spec
17475 org-latex-to-mathml-convert-command
17476 `((?j . ,(shell-quote-argument
17477 (expand-file-name org-latex-to-mathml-jar-file)))
17478 (?I . ,(shell-quote-argument tmp-in-file))
17479 (?o . ,(shell-quote-argument tmp-out-file)))))
17480 mathml shell-command-output)
17481 (when (org-called-interactively-p 'any)
17482 (unless (org-format-latex-mathml-available-p)
17483 (error "LaTeX to MathML converter not configured")))
17484 (message "Running %s" cmd)
17485 (setq shell-command-output (shell-command-to-string cmd))
17486 (setq mathml
17487 (when (file-readable-p tmp-out-file)
17488 (with-current-buffer (find-file-noselect tmp-out-file t)
17489 (goto-char (point-min))
17490 (when (re-search-forward
17491 (concat
17492 (regexp-quote
17493 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17494 "\\(.\\|\n\\)*"
17495 (regexp-quote "</math>")) nil t)
17496 (prog1 (match-string 0) (kill-buffer))))))
17497 (cond
17498 (mathml
17499 (setq mathml
17500 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17501 (when mathml-file
17502 (write-region mathml nil mathml-file))
17503 (when (org-called-interactively-p 'any)
17504 (message mathml)))
17505 ((message "LaTeX to MathML conversion failed")
17506 (message shell-command-output)))
17507 (delete-file tmp-in-file)
17508 (when (file-exists-p tmp-out-file)
17509 (delete-file tmp-out-file))
17510 mathml))
17512 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17513 prefix &optional dir)
17514 "Use `org-create-math-formula' but check local cache first."
17515 (let* ((absprefix (expand-file-name prefix dir))
17516 (print-length nil) (print-level nil)
17517 (formula-id (concat
17518 "formula-"
17519 (sha1
17520 (prin1-to-string
17521 (list latex-frag
17522 org-latex-to-mathml-convert-command)))))
17523 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17524 (formula-cache-dir (file-name-directory formula-cache)))
17526 (unless (file-directory-p formula-cache-dir)
17527 (make-directory formula-cache-dir t))
17529 (unless (file-exists-p formula-cache)
17530 (org-create-math-formula latex-frag formula-cache))
17532 (if (file-exists-p formula-cache)
17533 ;; Successful conversion. Return the link to MathML file.
17534 (org-add-props
17535 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17536 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17537 'org-latex-src-embed-type (if latex-frag-type
17538 'paragraph 'character)))
17539 ;; Failed conversion. Return the LaTeX fragment verbatim
17540 (add-text-properties
17541 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17542 latex-frag)))
17544 ;; This function borrows from Ganesh Swami's latex2png.el
17545 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17546 "This calls dvipng."
17547 (require 'org-latex)
17548 (let* ((tmpdir (if (featurep 'xemacs)
17549 (temp-directory)
17550 temporary-file-directory))
17551 (texfilebase (make-temp-name
17552 (expand-file-name "orgtex" tmpdir)))
17553 (texfile (concat texfilebase ".tex"))
17554 (dvifile (concat texfilebase ".dvi"))
17555 (pngfile (concat texfilebase ".png"))
17556 (fnh (if (featurep 'xemacs)
17557 (font-height (face-font 'default))
17558 (face-attribute 'default :height nil)))
17559 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17560 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17561 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17562 "Black"))
17563 (bg (or (plist-get options (if buffer :background :html-background))
17564 "Transparent")))
17565 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17566 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17567 (with-temp-file texfile
17568 (insert (org-splice-latex-header
17569 org-format-latex-header
17570 org-export-latex-default-packages-alist
17571 org-export-latex-packages-alist t
17572 org-format-latex-header-extra))
17573 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17574 (require 'org-latex)
17575 (org-export-latex-fix-inputenc))
17576 (let ((dir default-directory))
17577 (condition-case nil
17578 (progn
17579 (cd tmpdir)
17580 (call-process "latex" nil nil nil texfile))
17581 (error nil))
17582 (cd dir))
17583 (if (not (file-exists-p dvifile))
17584 (progn (message "Failed to create dvi file from %s" texfile) nil)
17585 (condition-case nil
17586 (if (featurep 'xemacs)
17587 (call-process "dvipng" nil nil nil
17588 "-fg" fg "-bg" bg
17589 "-T" "tight"
17590 "-o" pngfile
17591 dvifile)
17592 (call-process "dvipng" nil nil nil
17593 "-fg" fg "-bg" bg
17594 "-D" dpi
17595 ;;"-x" scale "-y" scale
17596 "-T" "tight"
17597 "-o" pngfile
17598 dvifile))
17599 (error nil))
17600 (if (not (file-exists-p pngfile))
17601 (if org-format-latex-signal-error
17602 (error "Failed to create png file from %s" texfile)
17603 (message "Failed to create png file from %s" texfile)
17604 nil)
17605 ;; Use the requested file name and clean up
17606 (copy-file pngfile tofile 'replace)
17607 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17608 (if (file-exists-p (concat texfilebase e))
17609 (delete-file (concat texfilebase e))))
17610 pngfile))))
17612 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17613 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17614 "This calls convert, which is included into imagemagick."
17615 (require 'org-latex)
17616 (let* ((tmpdir (if (featurep 'xemacs)
17617 (temp-directory)
17618 temporary-file-directory))
17619 (texfilebase (make-temp-name
17620 (expand-file-name "orgtex" tmpdir)))
17621 (texfile (concat texfilebase ".tex"))
17622 (pdffile (concat texfilebase ".pdf"))
17623 (pngfile (concat texfilebase ".png"))
17624 (fnh (if (featurep 'xemacs)
17625 (font-height (face-font 'default))
17626 (face-attribute 'default :height nil)))
17627 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17628 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17629 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17630 "black"))
17631 (bg (or (plist-get options (if buffer :background :html-background))
17632 "white")))
17633 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17634 (setq fg (org-latex-color-format fg)))
17635 (if (eq bg 'default) (setq bg (org-latex-color :background))
17636 (setq bg (org-latex-color-format
17637 (if (string= bg "Transparent")(setq bg "white")))))
17638 (with-temp-file texfile
17639 (insert (org-splice-latex-header
17640 org-format-latex-header
17641 org-export-latex-default-packages-alist
17642 org-export-latex-packages-alist t
17643 org-format-latex-header-extra))
17644 (insert "\n\\begin{document}\n"
17645 "\\definecolor{fg}{rgb}{" fg "}\n"
17646 "\\definecolor{bg}{rgb}{" bg "}\n"
17647 "\n\\pagecolor{bg}\n"
17648 "\n{\\color{fg}\n"
17649 string
17650 "\n}\n"
17651 "\n\\end{document}\n" )
17652 (require 'org-latex)
17653 (org-export-latex-fix-inputenc))
17654 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17655 (condition-case nil
17656 (progn
17657 (cd tmpdir)
17658 (setq cmds org-latex-to-pdf-process)
17659 (while cmds
17660 (setq latex-frags-cmds (pop cmds))
17661 (if (listp latex-frags-cmds)
17662 (setq cmds nil)
17663 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17664 (while latex-frags-cmds
17665 (setq cmd (pop latex-frags-cmds))
17666 (while (string-match "%b" cmd)
17667 (setq cmd (replace-match
17668 (save-match-data
17669 (shell-quote-argument texfile))
17670 t t cmd)))
17671 (while (string-match "%f" cmd)
17672 (setq cmd (replace-match
17673 (save-match-data
17674 (shell-quote-argument (file-name-nondirectory texfile)))
17675 t t cmd)))
17676 (while (string-match "%o" cmd)
17677 (setq cmd (replace-match
17678 (save-match-data
17679 (shell-quote-argument (file-name-directory texfile)))
17680 t t cmd)))
17681 (setq cmd (split-string cmd))
17682 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17683 (error nil))
17684 (cd dir))
17685 (if (not (file-exists-p pdffile))
17686 (progn (message "Failed to create pdf file from %s" texfile) nil)
17687 (condition-case nil
17688 (if (featurep 'xemacs)
17689 (call-process "convert" nil nil nil
17690 "-density" "96"
17691 "-trim"
17692 "-antialias"
17693 pdffile
17694 "-quality" "100"
17695 ;; "-sharpen" "0x1.0"
17696 pngfile)
17697 (call-process "convert" nil nil nil
17698 "-density" dpi
17699 "-trim"
17700 "-antialias"
17701 pdffile
17702 "-quality" "100"
17703 ; "-sharpen" "0x1.0"
17704 pngfile))
17705 (error nil))
17706 (if (not (file-exists-p pngfile))
17707 (if org-format-latex-signal-error
17708 (error "Failed to create png file from %s" texfile)
17709 (message "Failed to create png file from %s" texfile)
17710 nil)
17711 ;; Use the requested file name and clean up
17712 (copy-file pngfile tofile 'replace)
17713 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17714 (if (file-exists-p (concat texfilebase e))
17715 (delete-file (concat texfilebase e))))
17716 pngfile))))
17718 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17719 "Fill a LaTeX header template TPL.
17720 In the template, the following place holders will be recognized:
17722 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17723 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17724 [PACKAGES] \\usepackage statements for PKG
17725 [NO-PACKAGES] do not include PKG
17726 [EXTRA] the string EXTRA
17727 [NO-EXTRA] do not include EXTRA
17729 For backward compatibility, if both the positive and the negative place
17730 holder is missing, the positive one (without the \"NO-\") will be
17731 assumed to be present at the end of the template.
17732 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17733 EXTRA is a string.
17734 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17735 (let (rpl (end ""))
17736 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17737 (setq rpl (if (or (match-end 1) (not def-pkg))
17738 "" (org-latex-packages-to-string def-pkg snippets-p t))
17739 tpl (replace-match rpl t t tpl))
17740 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17742 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17743 (setq rpl (if (or (match-end 1) (not pkg))
17744 "" (org-latex-packages-to-string pkg snippets-p t))
17745 tpl (replace-match rpl t t tpl))
17746 (if pkg (setq end
17747 (concat end "\n"
17748 (org-latex-packages-to-string pkg snippets-p)))))
17750 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17751 (setq rpl (if (or (match-end 1) (not extra))
17752 "" (concat extra "\n"))
17753 tpl (replace-match rpl t t tpl))
17754 (if (and extra (string-match "\\S-" extra))
17755 (setq end (concat end "\n" extra))))
17757 (if (string-match "\\S-" end)
17758 (concat tpl "\n" end)
17759 tpl)))
17761 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17762 "Turn an alist of packages into a string with the \\usepackage macros."
17763 (setq pkg (mapconcat (lambda(p)
17764 (cond
17765 ((stringp p) p)
17766 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17767 (format "%% Package %s omitted" (cadr p)))
17768 ((equal "" (car p))
17769 (format "\\usepackage{%s}" (cadr p)))
17771 (format "\\usepackage[%s]{%s}"
17772 (car p) (cadr p)))))
17774 "\n"))
17775 (if newline (concat pkg "\n") pkg))
17777 (defun org-dvipng-color (attr)
17778 "Return a RGB color specification for dvipng."
17779 (apply 'format "rgb %s %s %s"
17780 (mapcar 'org-normalize-color
17781 (if (featurep 'xemacs)
17782 (color-rgb-components
17783 (face-property 'default
17784 (cond ((eq attr :foreground) 'foreground)
17785 ((eq attr :background) 'background))))
17786 (color-values (face-attribute 'default attr nil))))))
17788 (defun org-latex-color (attr)
17789 "Return a RGB color for the LaTeX color package."
17790 (apply 'format "%s,%s,%s"
17791 (mapcar 'org-normalize-color
17792 (if (featurep 'xemacs)
17793 (color-rgb-components
17794 (face-property 'default
17795 (cond ((eq attr :foreground) 'foreground)
17796 ((eq attr :background) 'background))))
17797 (color-values (face-attribute 'default attr nil))))))
17799 (defun org-latex-color-format (color-name)
17800 "Convert COLOR-NAME to a RGB color value."
17801 (apply 'format "%s,%s,%s"
17802 (mapcar 'org-normalize-color
17803 (color-values color-name))))
17805 (defun org-normalize-color (value)
17806 "Return string to be used as color value for an RGB component."
17807 (format "%g" (/ value 65535.0)))
17809 ;; Image display
17812 (defvar org-inline-image-overlays nil)
17813 (make-variable-buffer-local 'org-inline-image-overlays)
17815 (defun org-toggle-inline-images (&optional include-linked)
17816 "Toggle the display of inline images.
17817 INCLUDE-LINKED is passed to `org-display-inline-images'."
17818 (interactive "P")
17819 (if org-inline-image-overlays
17820 (progn
17821 (org-remove-inline-images)
17822 (message "Inline image display turned off"))
17823 (org-display-inline-images include-linked)
17824 (if 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."
17831 (interactive)
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
17843 like.
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."
17847 (interactive "P")
17848 (unless refresh
17849 (org-remove-inline-images)
17850 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17851 (save-excursion
17852 (save-restriction
17853 (widen)
17854 (setq beg (or beg (point-min)) end (or end (point-max)))
17855 (goto-char beg)
17856 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17857 (substring (org-image-file-name-regexp) 0 -2)
17858 "\\)\\]" (if include-linked "" "\\]")))
17859 old file ov img)
17860 (while (re-search-forward re end t)
17861 (setq old (get-char-property-and-overlay (match-beginning 1)
17862 'org-image-overlay))
17863 (setq file (expand-file-name
17864 (concat (or (match-string 3) "") (match-string 4))))
17865 (when (file-exists-p file)
17866 (if (and (car-safe old) refresh)
17867 (image-refresh (overlay-get (cdr old) 'display))
17868 (setq img (save-match-data (create-image file)))
17869 (when img
17870 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17871 (overlay-put ov 'display img)
17872 (overlay-put ov 'face 'default)
17873 (overlay-put ov 'org-image-overlay t)
17874 (overlay-put ov 'modification-hooks
17875 (list 'org-display-inline-modification-hook))
17876 (push ov org-inline-image-overlays)))))))))
17878 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17879 "Remove inline-display overlay if a corresponding region is modified."
17880 (let ((inhibit-modification-hooks t))
17881 (when (and ov after)
17882 (delete ov org-inline-image-overlays)
17883 (delete-overlay ov))))
17885 (defun org-remove-inline-images ()
17886 "Remove inline display of images."
17887 (interactive)
17888 (mapc 'delete-overlay org-inline-image-overlays)
17889 (setq org-inline-image-overlays nil))
17891 ;;;; Key bindings
17893 ;; Outline functions from `outline-mode-prefix-map'
17894 ;; that can be remapped in Org:
17895 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17896 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17897 (define-key org-mode-map [remap outline-forward-same-level]
17898 'org-forward-heading-same-level)
17899 (define-key org-mode-map [remap outline-backward-same-level]
17900 'org-backward-heading-same-level)
17901 (define-key org-mode-map [remap show-branches]
17902 'org-kill-note-or-show-branches)
17903 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17904 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17905 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17907 ;; Outline functions from `outline-mode-prefix-map' that can not
17908 ;; be remapped in Org:
17910 ;; - the column "key binding" shows whether the Outline function is still
17911 ;; available in Org mode on the same key that it has been bound to in
17912 ;; Outline mode:
17913 ;; - "overridden": key used for a different functionality in Org mode
17914 ;; - else: key still bound to the same Outline function in Org mode
17916 ;; | Outline function | key binding | Org replacement |
17917 ;; |------------------------------------+-------------+-----------------------|
17918 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17919 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17920 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17921 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17922 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17923 ;; | `show-entry' | overridden | no replacement |
17924 ;; | `show-children' | `C-c C-i' | visibility cycling |
17925 ;; | `show-branches' | `C-c C-k' | still same function |
17926 ;; | `show-subtree' | overridden | visibility cycling |
17927 ;; | `show-all' | overridden | no replacement |
17928 ;; | `hide-subtree' | overridden | visibility cycling |
17929 ;; | `hide-body' | overridden | no replacement |
17930 ;; | `hide-entry' | overridden | visibility cycling |
17931 ;; | `hide-leaves' | overridden | no replacement |
17932 ;; | `hide-sublevels' | overridden | no replacement |
17933 ;; | `hide-other' | overridden | no replacement |
17935 ;; Make `C-c C-x' a prefix key
17936 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17938 ;; TAB key with modifiers
17939 (org-defkey org-mode-map "\C-i" 'org-cycle)
17940 (org-defkey org-mode-map [(tab)] 'org-cycle)
17941 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17942 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17943 ;; The following line is necessary under Suse GNU/Linux
17944 (unless (featurep 'xemacs)
17945 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17946 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17947 (define-key org-mode-map [backtab] 'org-shifttab)
17949 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17950 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17951 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17953 ;; Cursor keys with modifiers
17954 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17955 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17956 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17957 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17959 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17960 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17961 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17962 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17964 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17965 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17966 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17967 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17969 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17970 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17971 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17972 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17974 ;; Babel keys
17975 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17976 (mapc (lambda (pair)
17977 (define-key org-babel-map (car pair) (cdr pair)))
17978 org-babel-key-bindings)
17980 ;;; Extra keys for tty access.
17981 ;; We only set them when really needed because otherwise the
17982 ;; menus don't show the simple keys
17984 (when (or org-use-extra-keys
17985 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17986 (not window-system))
17987 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17988 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17989 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17990 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17991 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17992 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17993 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17994 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17995 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17996 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17997 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17998 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17999 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18000 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18001 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18002 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18003 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18004 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18005 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18006 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18007 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18008 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18009 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18010 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18011 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18012 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18013 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18014 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18016 ;; All the other keys
18018 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18019 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18020 (if (boundp 'narrow-map)
18021 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18022 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18023 (if (boundp 'narrow-map)
18024 (org-defkey narrow-map "b" 'org-narrow-to-block)
18025 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18026 (if (boundp 'narrow-map)
18027 (org-defkey narrow-map "e" 'org-narrow-to-element)
18028 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18029 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18030 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18031 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18032 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18033 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18034 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18035 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18036 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18037 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18038 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18039 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18040 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18041 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18042 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18043 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18044 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18045 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18046 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18047 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18048 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18049 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18050 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18051 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18052 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18053 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18054 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18055 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18056 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18057 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18058 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18059 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18060 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18061 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18062 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18063 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18064 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18065 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18066 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18067 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18068 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18069 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18070 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18071 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18072 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18073 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18074 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18075 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18076 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18077 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18078 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18079 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18080 (org-defkey org-mode-map "\C-c^" 'org-sort)
18081 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18082 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18083 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18084 (org-defkey org-mode-map "\C-m" 'org-return)
18085 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18086 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18087 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18088 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18089 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18090 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18091 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18092 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18093 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18094 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18095 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18096 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18097 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18098 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18099 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18100 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18101 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18102 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18103 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18104 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18105 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18106 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18107 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18109 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18110 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18111 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18112 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18114 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18115 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18116 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18117 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18118 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18119 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18120 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18121 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18122 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18123 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18124 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18125 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18126 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18127 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18128 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18129 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18130 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18131 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18132 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18133 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18134 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18135 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18137 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18138 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18139 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18140 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18141 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18143 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18145 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18147 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18148 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18150 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18153 (when (featurep 'xemacs)
18154 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18157 (defconst org-speed-commands-default
18159 ("Outline Navigation")
18160 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18161 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18162 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18163 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18164 ("u" . (org-speed-move-safe 'outline-up-heading))
18165 ("j" . org-goto)
18166 ("g" . (org-refile t))
18167 ("Outline Visibility")
18168 ("c" . org-cycle)
18169 ("C" . org-shifttab)
18170 (" " . org-display-outline-path)
18171 (":" . org-columns)
18172 ("Outline Structure Editing")
18173 ("U" . org-shiftmetaup)
18174 ("D" . org-shiftmetadown)
18175 ("r" . org-metaright)
18176 ("l" . org-metaleft)
18177 ("R" . org-shiftmetaright)
18178 ("L" . org-shiftmetaleft)
18179 ("i" . (progn (forward-char 1) (call-interactively
18180 'org-insert-heading-respect-content)))
18181 ("^" . org-sort)
18182 ("w" . org-refile)
18183 ("a" . org-archive-subtree-default-with-confirmation)
18184 ("." . org-mark-subtree)
18185 ("#" . org-toggle-comment)
18186 ("Clock Commands")
18187 ("I" . org-clock-in)
18188 ("O" . org-clock-out)
18189 ("Meta Data Editing")
18190 ("t" . org-todo)
18191 ("0" . (org-priority ?\ ))
18192 ("1" . (org-priority ?A))
18193 ("2" . (org-priority ?B))
18194 ("3" . (org-priority ?C))
18195 (";" . org-set-tags-command)
18196 ("e" . org-set-effort)
18197 ("E" . org-inc-effort)
18198 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18199 (org-entry-put (point) "APPT_WARNTIME" m)))
18200 ("Agenda Views etc")
18201 ("v" . org-agenda)
18202 ("/" . org-sparse-tree)
18203 ("Misc")
18204 ("o" . org-open-at-point)
18205 ("?" . org-speed-command-help)
18206 ("<" . (org-agenda-set-restriction-lock 'subtree))
18207 (">" . (org-agenda-remove-restriction-lock))
18209 "The default speed commands.")
18211 (defun org-print-speed-command (e)
18212 (if (> (length (car e)) 1)
18213 (progn
18214 (princ "\n")
18215 (princ (car e))
18216 (princ "\n")
18217 (princ (make-string (length (car e)) ?-))
18218 (princ "\n"))
18219 (princ (car e))
18220 (princ " ")
18221 (if (symbolp (cdr e))
18222 (princ (symbol-name (cdr e)))
18223 (prin1 (cdr e)))
18224 (princ "\n")))
18226 (defun org-speed-command-help ()
18227 "Show the available speed commands."
18228 (interactive)
18229 (if (not org-use-speed-commands)
18230 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18231 (with-output-to-temp-buffer "*Help*"
18232 (princ "User-defined Speed commands\n===========================\n")
18233 (mapc 'org-print-speed-command org-speed-commands-user)
18234 (princ "\n")
18235 (princ "Built-in Speed commands\n=======================\n")
18236 (mapc 'org-print-speed-command org-speed-commands-default))
18237 (with-current-buffer "*Help*"
18238 (setq truncate-lines t))))
18240 (defun org-speed-move-safe (cmd)
18241 "Execute CMD, but make sure that the cursor always ends up in a headline.
18242 If not, return to the original position and throw an error."
18243 (interactive)
18244 (let ((pos (point)))
18245 (call-interactively cmd)
18246 (unless (and (bolp) (org-at-heading-p))
18247 (goto-char pos)
18248 (error "Boundary reached while executing %s" cmd))))
18250 (defvar org-self-insert-command-undo-counter 0)
18252 (defvar org-table-auto-blank-field) ; defined in org-table.el
18253 (defvar org-speed-command nil)
18255 (defun org-speed-command-default-hook (keys)
18256 "Hook for activating single-letter speed commands.
18257 `org-speed-commands-default' specifies a minimal command set.
18258 Use `org-speed-commands-user' for further customization."
18259 (when (or (and (bolp) (looking-at org-outline-regexp))
18260 (and (functionp org-use-speed-commands)
18261 (funcall org-use-speed-commands)))
18262 (cdr (assoc keys (append org-speed-commands-user
18263 org-speed-commands-default)))))
18265 (defun org-babel-speed-command-hook (keys)
18266 "Hook for activating single-letter code block commands."
18267 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18268 (cdr (assoc keys org-babel-key-bindings))))
18270 (defcustom org-speed-command-hook
18271 '(org-speed-command-default-hook org-babel-speed-command-hook)
18272 "Hook for activating speed commands at strategic locations.
18273 Hook functions are called in sequence until a valid handler is
18274 found.
18276 Each hook takes a single argument, a user-pressed command key
18277 which is also a `self-insert-command' from the global map.
18279 Within the hook, examine the cursor position and the command key
18280 and return nil or a valid handler as appropriate. Handler could
18281 be one of an interactive command, a function, or a form.
18283 Set `org-use-speed-commands' to non-nil value to enable this
18284 hook. The default setting is `org-speed-command-default-hook'."
18285 :group 'org-structure
18286 :version "24.1"
18287 :type 'hook)
18289 (defun org-self-insert-command (N)
18290 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18291 If the cursor is in a table looking at whitespace, the whitespace is
18292 overwritten, and the table is not marked as requiring realignment."
18293 (interactive "p")
18294 (org-check-before-invisible-edit 'insert)
18295 (cond
18296 ((and org-use-speed-commands
18297 (setq org-speed-command
18298 (run-hook-with-args-until-success
18299 'org-speed-command-hook (this-command-keys))))
18300 (cond
18301 ((commandp org-speed-command)
18302 (setq this-command org-speed-command)
18303 (call-interactively org-speed-command))
18304 ((functionp org-speed-command)
18305 (funcall org-speed-command))
18306 ((and org-speed-command (listp org-speed-command))
18307 (eval org-speed-command))
18308 (t (let (org-use-speed-commands)
18309 (call-interactively 'org-self-insert-command)))))
18310 ((and
18311 (org-table-p)
18312 (progn
18313 ;; check if we blank the field, and if that triggers align
18314 (and (featurep 'org-table) org-table-auto-blank-field
18315 (member last-command
18316 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18317 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18318 ;; got extra space, this field does not determine column width
18319 (let (org-table-may-need-update) (org-table-blank-field))
18320 ;; no extra space, this field may determine column width
18321 (org-table-blank-field)))
18323 (eq N 1)
18324 (looking-at "[^|\n]* |"))
18325 (let (org-table-may-need-update)
18326 (goto-char (1- (match-end 0)))
18327 (backward-delete-char 1)
18328 (goto-char (match-beginning 0))
18329 (self-insert-command N)))
18331 (setq org-table-may-need-update t)
18332 (self-insert-command N)
18333 (org-fix-tags-on-the-fly)
18334 (if org-self-insert-cluster-for-undo
18335 (if (not (eq last-command 'org-self-insert-command))
18336 (setq org-self-insert-command-undo-counter 1)
18337 (if (>= org-self-insert-command-undo-counter 20)
18338 (setq org-self-insert-command-undo-counter 1)
18339 (and (> org-self-insert-command-undo-counter 0)
18340 buffer-undo-list (listp buffer-undo-list)
18341 (not (cadr buffer-undo-list)) ; remove nil entry
18342 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18343 (setq org-self-insert-command-undo-counter
18344 (1+ org-self-insert-command-undo-counter))))))))
18346 (defun org-check-before-invisible-edit (kind)
18347 "Check is editing if kind KIND would be dangerous with invisible text around.
18348 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18349 ;; First, try to get out of here as quickly as possible, to reduce overhead
18350 (if (and org-catch-invisible-edits
18351 (or (not (boundp 'visible-mode)) (not visible-mode))
18352 (or (get-char-property (point) 'invisible)
18353 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18354 ;; OK, we need to take a closer look
18355 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18356 (invisible-before-point (if (bobp) nil (get-char-property
18357 (1- (point)) 'invisible)))
18358 (border-and-ok-direction
18360 ;; Check if we are acting predictably before invisible text
18361 (and invisible-at-point (not invisible-before-point)
18362 (memq kind '(insert delete-backward)))
18363 ;; Check if we are acting predictably after invisible text
18364 ;; This works not well, and I have turned it off. It seems
18365 ;; better to always show and stop after invisible text.
18366 ;; (and (not invisible-at-point) invisible-before-point
18367 ;; (memq kind '(insert delete)))
18369 (when (or (memq invisible-at-point '(outline org-hide-block t))
18370 (memq invisible-before-point '(outline org-hide-block t)))
18371 (if (eq org-catch-invisible-edits 'error)
18372 (error "Editing in invisible areas is prohibited - make visible first"))
18373 (if (and org-custom-properties-overlays
18374 (y-or-n-p "Display invisible properties in this buffer? "))
18375 (org-toggle-custom-properties-visibility)
18376 ;; Make the area visible
18377 (save-excursion
18378 (if invisible-before-point
18379 (goto-char (previous-single-char-property-change
18380 (point) 'invisible)))
18381 (org-cycle))
18382 (cond
18383 ((eq org-catch-invisible-edits 'show)
18384 ;; That's it, we do the edit after showing
18385 (message
18386 "Unfolding invisible region around point before editing")
18387 (sit-for 1))
18388 ((and (eq org-catch-invisible-edits 'smart)
18389 border-and-ok-direction)
18390 (message "Unfolding invisible region around point before editing"))
18392 ;; Don't do the edit, make the user repeat it in full visibility
18393 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18395 (defun org-fix-tags-on-the-fly ()
18396 (when (and (equal (char-after (point-at-bol)) ?*)
18397 (org-at-heading-p))
18398 (org-align-tags-here org-tags-column)))
18400 (defun org-delete-backward-char (N)
18401 "Like `delete-backward-char', insert whitespace at field end in tables.
18402 When deleting backwards, in tables this function will insert whitespace in
18403 front of the next \"|\" separator, to keep the table aligned. The table will
18404 still be marked for re-alignment if the field did fill the entire column,
18405 because, in this case the deletion might narrow the column."
18406 (interactive "p")
18407 (org-check-before-invisible-edit 'delete-backward)
18408 (if (and (org-table-p)
18409 (eq N 1)
18410 (string-match "|" (buffer-substring (point-at-bol) (point)))
18411 (looking-at ".*?|"))
18412 (let ((pos (point))
18413 (noalign (looking-at "[^|\n\r]* |"))
18414 (c org-table-may-need-update))
18415 (backward-delete-char N)
18416 (if (not overwrite-mode)
18417 (progn
18418 (skip-chars-forward "^|")
18419 (insert " ")
18420 (goto-char (1- pos))))
18421 ;; noalign: if there were two spaces at the end, this field
18422 ;; does not determine the width of the column.
18423 (if noalign (setq org-table-may-need-update c)))
18424 (backward-delete-char N)
18425 (org-fix-tags-on-the-fly)))
18427 (defun org-delete-char (N)
18428 "Like `delete-char', but insert whitespace at field end in tables.
18429 When deleting characters, 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."
18433 (interactive "p")
18434 (org-check-before-invisible-edit 'delete)
18435 (if (and (org-table-p)
18436 (not (bolp))
18437 (not (= (char-after) ?|))
18438 (eq N 1))
18439 (if (looking-at ".*?|")
18440 (let ((pos (point))
18441 (noalign (looking-at "[^|\n\r]* |"))
18442 (c org-table-may-need-update))
18443 (replace-match (concat
18444 (substring (match-string 0) 1 -1)
18445 " |"))
18446 (goto-char pos)
18447 ;; noalign: if there were two spaces at the end, this field
18448 ;; does not determine the width of the column.
18449 (if noalign (setq org-table-may-need-update c)))
18450 (delete-char N))
18451 (delete-char N)
18452 (org-fix-tags-on-the-fly)))
18454 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18455 (put 'org-self-insert-command 'delete-selection t)
18456 (put 'orgtbl-self-insert-command 'delete-selection t)
18457 (put 'org-delete-char 'delete-selection 'supersede)
18458 (put 'org-delete-backward-char 'delete-selection 'supersede)
18459 (put 'org-yank 'delete-selection 'yank)
18461 ;; Make `flyspell-mode' delay after some commands
18462 (put 'org-self-insert-command 'flyspell-delayed t)
18463 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18464 (put 'org-delete-char 'flyspell-delayed t)
18465 (put 'org-delete-backward-char 'flyspell-delayed t)
18467 ;; Make pabbrev-mode expand after org-mode commands
18468 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18469 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18471 ;; How to do this: Measure non-white length of current string
18472 ;; If equal to column width, we should realign.
18474 (defun org-remap (map &rest commands)
18475 "In MAP, remap the functions given in COMMANDS.
18476 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18477 (let (new old)
18478 (while commands
18479 (setq old (pop commands) new (pop commands))
18480 (if (fboundp 'command-remapping)
18481 (org-defkey map (vector 'remap old) new)
18482 (substitute-key-definition old new map global-map)))))
18484 (when (eq org-enable-table-editor 'optimized)
18485 ;; If the user wants maximum table support, we need to hijack
18486 ;; some standard editing functions
18487 (org-remap org-mode-map
18488 'self-insert-command 'org-self-insert-command
18489 'delete-char 'org-delete-char
18490 'delete-backward-char 'org-delete-backward-char)
18491 (org-defkey org-mode-map "|" 'org-force-self-insert))
18493 (defvar org-ctrl-c-ctrl-c-hook nil
18494 "Hook for functions attaching themselves to `C-c C-c'.
18496 This can be used to add additional functionality to the C-c C-c
18497 key which executes context-dependent commands. This hook is run
18498 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18499 run after the last test.
18501 Each function will be called with no arguments. The function
18502 must check if the context is appropriate for it to act. If yes,
18503 it should do its thing and then return a non-nil value. If the
18504 context is wrong, just do nothing and return nil.")
18506 (defvar org-ctrl-c-ctrl-c-final-hook nil
18507 "Hook for functions attaching themselves to `C-c C-c'.
18509 This can be used to add additional functionality to the C-c C-c
18510 key which executes context-dependent commands. This hook is run
18511 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18512 before the first test.
18514 Each function will be called with no arguments. The function
18515 must check if the context is appropriate for it to act. If yes,
18516 it should do its thing and then return a non-nil value. If the
18517 context is wrong, just do nothing and return nil.")
18519 (defvar org-tab-first-hook nil
18520 "Hook for functions to attach themselves to TAB.
18521 See `org-ctrl-c-ctrl-c-hook' for more information.
18522 This hook runs as the first action when TAB is pressed, even before
18523 `org-cycle' messes around with the `outline-regexp' to cater for
18524 inline tasks and plain list item folding.
18525 If any function in this hook returns t, any other actions that
18526 would have been caused by TAB (such as table field motion or visibility
18527 cycling) will not occur.")
18529 (defvar org-tab-after-check-for-table-hook nil
18530 "Hook for functions to attach themselves to TAB.
18531 See `org-ctrl-c-ctrl-c-hook' for more information.
18532 This hook runs after it has been established that the cursor is not in a
18533 table, but before checking if the cursor is in a headline or if global cycling
18534 should be done.
18535 If any function in this hook returns t, not other actions like visibility
18536 cycling will be done.")
18538 (defvar org-tab-after-check-for-cycling-hook nil
18539 "Hook for functions to attach themselves to TAB.
18540 See `org-ctrl-c-ctrl-c-hook' for more information.
18541 This hook runs after it has been established that not table field motion and
18542 not visibility should be done because of current context. This is probably
18543 the place where a package like yasnippets can hook in.")
18545 (defvar org-tab-before-tab-emulation-hook nil
18546 "Hook for functions to attach themselves to TAB.
18547 See `org-ctrl-c-ctrl-c-hook' for more information.
18548 This hook runs after every other options for TAB have been exhausted, but
18549 before indentation and \t insertion takes place.")
18551 (defvar org-metaleft-hook nil
18552 "Hook for functions attaching themselves to `M-left'.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.")
18554 (defvar org-metaright-hook nil
18555 "Hook for functions attaching themselves to `M-right'.
18556 See `org-ctrl-c-ctrl-c-hook' for more information.")
18557 (defvar org-metaup-hook nil
18558 "Hook for functions attaching themselves to `M-up'.
18559 See `org-ctrl-c-ctrl-c-hook' for more information.")
18560 (defvar org-metadown-hook nil
18561 "Hook for functions attaching themselves to `M-down'.
18562 See `org-ctrl-c-ctrl-c-hook' for more information.")
18563 (defvar org-shiftmetaleft-hook nil
18564 "Hook for functions attaching themselves to `M-S-left'.
18565 See `org-ctrl-c-ctrl-c-hook' for more information.")
18566 (defvar org-shiftmetaright-hook nil
18567 "Hook for functions attaching themselves to `M-S-right'.
18568 See `org-ctrl-c-ctrl-c-hook' for more information.")
18569 (defvar org-shiftmetaup-hook nil
18570 "Hook for functions attaching themselves to `M-S-up'.
18571 See `org-ctrl-c-ctrl-c-hook' for more information.")
18572 (defvar org-shiftmetadown-hook nil
18573 "Hook for functions attaching themselves to `M-S-down'.
18574 See `org-ctrl-c-ctrl-c-hook' for more information.")
18575 (defvar org-metareturn-hook nil
18576 "Hook for functions attaching themselves to `M-RET'.
18577 See `org-ctrl-c-ctrl-c-hook' for more information.")
18578 (defvar org-shiftup-hook nil
18579 "Hook for functions attaching themselves to `S-up'.
18580 See `org-ctrl-c-ctrl-c-hook' for more information.")
18581 (defvar org-shiftup-final-hook nil
18582 "Hook for functions attaching themselves to `S-up'.
18583 This one runs after all other options except shift-select have been excluded.
18584 See `org-ctrl-c-ctrl-c-hook' for more information.")
18585 (defvar org-shiftdown-hook nil
18586 "Hook for functions attaching themselves to `S-down'.
18587 See `org-ctrl-c-ctrl-c-hook' for more information.")
18588 (defvar org-shiftdown-final-hook nil
18589 "Hook for functions attaching themselves to `S-down'.
18590 This one runs after all other options except shift-select have been excluded.
18591 See `org-ctrl-c-ctrl-c-hook' for more information.")
18592 (defvar org-shiftleft-hook nil
18593 "Hook for functions attaching themselves to `S-left'.
18594 See `org-ctrl-c-ctrl-c-hook' for more information.")
18595 (defvar org-shiftleft-final-hook nil
18596 "Hook for functions attaching themselves to `S-left'.
18597 This one runs after all other options except shift-select have been excluded.
18598 See `org-ctrl-c-ctrl-c-hook' for more information.")
18599 (defvar org-shiftright-hook nil
18600 "Hook for functions attaching themselves to `S-right'.
18601 See `org-ctrl-c-ctrl-c-hook' for more information.")
18602 (defvar org-shiftright-final-hook nil
18603 "Hook for functions attaching themselves to `S-right'.
18604 This one runs after all other options except shift-select have been excluded.
18605 See `org-ctrl-c-ctrl-c-hook' for more information.")
18607 (defun org-modifier-cursor-error ()
18608 "Throw an error, a modified cursor command was applied in wrong context."
18609 (error "This command is active in special context like tables, headlines or items"))
18611 (defun org-shiftselect-error ()
18612 "Throw an error because Shift-Cursor command was applied in wrong context."
18613 (if (and (boundp 'shift-select-mode) shift-select-mode)
18614 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18615 (error "This command works only in special context like headlines or timestamps")))
18617 (defun org-call-for-shift-select (cmd)
18618 (let ((this-command-keys-shift-translated t))
18619 (call-interactively cmd)))
18621 (defun org-shifttab (&optional arg)
18622 "Global visibility cycling or move to previous table field.
18623 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18624 on context.
18625 See the individual commands for more information."
18626 (interactive "P")
18627 (cond
18628 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18629 ((integerp arg)
18630 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18631 (message "Content view to level: %d" arg)
18632 (org-content (prefix-numeric-value arg2))
18633 (setq org-cycle-global-status 'overview)))
18634 (t (call-interactively 'org-global-cycle))))
18636 (defun org-shiftmetaleft ()
18637 "Promote subtree or delete table column.
18638 Calls `org-promote-subtree', `org-outdent-item-tree', or
18639 `org-table-delete-column', depending on context. See the
18640 individual commands for more information."
18641 (interactive)
18642 (cond
18643 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18644 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18645 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18646 ((if (not (org-region-active-p)) (org-at-item-p)
18647 (save-excursion (goto-char (region-beginning))
18648 (org-at-item-p)))
18649 (call-interactively 'org-outdent-item-tree))
18650 (t (org-modifier-cursor-error))))
18652 (defun org-shiftmetaright ()
18653 "Demote subtree or insert table column.
18654 Calls `org-demote-subtree', `org-indent-item-tree', or
18655 `org-table-insert-column', depending on context. See the
18656 individual commands for more information."
18657 (interactive)
18658 (cond
18659 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18660 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18661 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18662 ((if (not (org-region-active-p)) (org-at-item-p)
18663 (save-excursion (goto-char (region-beginning))
18664 (org-at-item-p)))
18665 (call-interactively 'org-indent-item-tree))
18666 (t (org-modifier-cursor-error))))
18668 (defun org-shiftmetaup (&optional arg)
18669 "Move subtree up or kill table row.
18670 Calls `org-move-subtree-up' or `org-table-kill-row' or
18671 `org-move-item-up' or `org-timestamp-up', depending on context.
18672 See the individual commands for more information."
18673 (interactive "P")
18674 (cond
18675 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18676 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18677 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18678 ((org-at-item-p) (call-interactively 'org-move-item-up))
18679 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18680 (call-interactively 'org-timestamp-up)))
18681 (t (org-modifier-cursor-error))))
18683 (defun org-shiftmetadown (&optional arg)
18684 "Move subtree down or insert table row.
18685 Calls `org-move-subtree-down' or `org-table-insert-row' or
18686 `org-move-item-down' or `org-timestamp-up', depending on context.
18687 See the individual commands for more information."
18688 (interactive "P")
18689 (cond
18690 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18691 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18692 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18693 ((org-at-item-p) (call-interactively 'org-move-item-down))
18694 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18695 (call-interactively 'org-timestamp-down)))
18696 (t (org-modifier-cursor-error))))
18698 (defsubst org-hidden-tree-error ()
18699 (error
18700 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18702 (defun org-metaleft (&optional arg)
18703 "Promote heading or move table column to left.
18704 Calls `org-do-promote' or `org-table-move-column', depending on context.
18705 With no specific context, calls the Emacs default `backward-word'.
18706 See the individual commands for more information."
18707 (interactive "P")
18708 (cond
18709 ((run-hook-with-args-until-success 'org-metaleft-hook))
18710 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18711 ((org-with-limited-levels
18712 (or (org-at-heading-p)
18713 (and (org-region-active-p)
18714 (save-excursion
18715 (goto-char (region-beginning))
18716 (org-at-heading-p)))))
18717 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18718 (call-interactively 'org-do-promote))
18719 ;; At an inline task.
18720 ((org-at-heading-p)
18721 (call-interactively 'org-inlinetask-promote))
18722 ((or (org-at-item-p)
18723 (and (org-region-active-p)
18724 (save-excursion
18725 (goto-char (region-beginning))
18726 (org-at-item-p))))
18727 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18728 (call-interactively 'org-outdent-item))
18729 (t (call-interactively 'backward-word))))
18731 (defun org-metaright (&optional arg)
18732 "Demote a subtree, a list item or move table column to right.
18733 In front of a drawer or a block keyword, indent it correctly.
18734 With no specific context, calls the Emacs default `forward-word'.
18735 See the individual commands for more information."
18736 (interactive "P")
18737 (cond
18738 ((run-hook-with-args-until-success 'org-metaright-hook))
18739 ((org-at-table-p) (call-interactively 'org-table-move-column))
18740 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18741 ((org-at-block-p) (call-interactively 'org-indent-block))
18742 ((org-with-limited-levels
18743 (or (org-at-heading-p)
18744 (and (org-region-active-p)
18745 (save-excursion
18746 (goto-char (region-beginning))
18747 (org-at-heading-p)))))
18748 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18749 (call-interactively 'org-do-demote))
18750 ;; At an inline task.
18751 ((org-at-heading-p)
18752 (call-interactively 'org-inlinetask-demote))
18753 ((or (org-at-item-p)
18754 (and (org-region-active-p)
18755 (save-excursion
18756 (goto-char (region-beginning))
18757 (org-at-item-p))))
18758 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18759 (call-interactively 'org-indent-item))
18760 (t (call-interactively 'forward-word))))
18762 (defun org-check-for-hidden (what)
18763 "Check if there are hidden headlines/items in the current visual line.
18764 WHAT can be either `headlines' or `items'. If the current line is
18765 an outline or item heading and it has a folded subtree below it,
18766 this function returns t, nil otherwise."
18767 (let ((re (cond
18768 ((eq what 'headlines) org-outline-regexp-bol)
18769 ((eq what 'items) (org-item-beginning-re))
18770 (t (error "This should not happen"))))
18771 beg end)
18772 (save-excursion
18773 (catch 'exit
18774 (unless (org-region-active-p)
18775 (setq beg (point-at-bol))
18776 (beginning-of-line 2)
18777 (while (and (not (eobp)) ;; this is like `next-line'
18778 (get-char-property (1- (point)) 'invisible))
18779 (beginning-of-line 2))
18780 (setq end (point))
18781 (goto-char beg)
18782 (goto-char (point-at-eol))
18783 (setq end (max end (point)))
18784 (while (re-search-forward re end t)
18785 (if (get-char-property (match-beginning 0) 'invisible)
18786 (throw 'exit t))))
18787 nil))))
18789 (autoload 'org-element-at-point "org-element")
18791 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18792 (declare-function org-element-type "org-element" (element))
18793 (declare-function org-element-context "org-element" ())
18794 (declare-function org-element-contents "org-element" (element))
18795 (declare-function org-element-property "org-element" (property element))
18796 (declare-function org-element-paragraph-parser "org-element" (limit))
18797 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18798 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18799 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18800 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18801 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18803 (defun org-metaup (&optional arg)
18804 "Move subtree up or move table row up.
18805 Calls `org-move-subtree-up' or `org-table-move-row' or
18806 `org-move-item-up', depending on context. See the individual commands
18807 for more information."
18808 (interactive "P")
18809 (cond
18810 ((run-hook-with-args-until-success 'org-metaup-hook))
18811 ((org-region-active-p)
18812 (let* ((a (min (region-beginning) (region-end)))
18813 (b (1- (max (region-beginning) (region-end))))
18814 (c (save-excursion (goto-char a)
18815 (move-beginning-of-line 0)))
18816 (d (save-excursion (goto-char a)
18817 (move-end-of-line 0) (point))))
18818 (transpose-regions a b c d)
18819 (goto-char c)))
18820 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18821 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18822 ((org-at-item-p) (call-interactively 'org-move-item-up))
18823 (t (org-drag-element-backward))))
18825 (defun org-metadown (&optional arg)
18826 "Move subtree down or move table row down.
18827 Calls `org-move-subtree-down' or `org-table-move-row' or
18828 `org-move-item-down', depending on context. See the individual
18829 commands for more information."
18830 (interactive "P")
18831 (cond
18832 ((run-hook-with-args-until-success 'org-metadown-hook))
18833 ((org-region-active-p)
18834 (let* ((a (min (region-beginning) (region-end)))
18835 (b (max (region-beginning) (region-end)))
18836 (c (save-excursion (goto-char b)
18837 (move-beginning-of-line 1)))
18838 (d (save-excursion (goto-char b)
18839 (move-end-of-line 1) (1+ (point)))))
18840 (transpose-regions a b c d)
18841 (goto-char d)))
18842 ((org-at-table-p) (call-interactively 'org-table-move-row))
18843 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18844 ((org-at-item-p) (call-interactively 'org-move-item-down))
18845 (t (org-drag-element-forward))))
18847 (defun org-shiftup (&optional arg)
18848 "Increase item in timestamp or increase priority of current headline.
18849 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18850 depending on context. See the individual commands for more information."
18851 (interactive "P")
18852 (cond
18853 ((run-hook-with-args-until-success 'org-shiftup-hook))
18854 ((and org-support-shift-select (org-region-active-p))
18855 (org-call-for-shift-select 'previous-line))
18856 ((org-at-timestamp-p t)
18857 (call-interactively (if org-edit-timestamp-down-means-later
18858 'org-timestamp-down 'org-timestamp-up)))
18859 ((and (not (eq org-support-shift-select 'always))
18860 org-enable-priority-commands
18861 (org-at-heading-p))
18862 (call-interactively 'org-priority-up))
18863 ((and (not org-support-shift-select) (org-at-item-p))
18864 (call-interactively 'org-previous-item))
18865 ((org-clocktable-try-shift 'up arg))
18866 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18867 (org-support-shift-select
18868 (org-call-for-shift-select 'previous-line))
18869 (t (org-shiftselect-error))))
18871 (defun org-shiftdown (&optional arg)
18872 "Decrease item in timestamp or decrease priority of current headline.
18873 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18874 depending on context. See the individual commands for more information."
18875 (interactive "P")
18876 (cond
18877 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18878 ((and org-support-shift-select (org-region-active-p))
18879 (org-call-for-shift-select 'next-line))
18880 ((org-at-timestamp-p t)
18881 (call-interactively (if org-edit-timestamp-down-means-later
18882 'org-timestamp-up 'org-timestamp-down)))
18883 ((and (not (eq org-support-shift-select 'always))
18884 org-enable-priority-commands
18885 (org-at-heading-p))
18886 (call-interactively 'org-priority-down))
18887 ((and (not org-support-shift-select) (org-at-item-p))
18888 (call-interactively 'org-next-item))
18889 ((org-clocktable-try-shift 'down arg))
18890 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18891 (org-support-shift-select
18892 (org-call-for-shift-select 'next-line))
18893 (t (org-shiftselect-error))))
18895 (defun org-shiftright (&optional arg)
18896 "Cycle the thing at point or in the current line, depending on context.
18897 Depending on context, this does one of the following:
18899 - switch a timestamp at point one day into the future
18900 - on a headline, switch to the next TODO keyword.
18901 - on an item, switch entire list to the next bullet type
18902 - on a property line, switch to the next allowed value
18903 - on a clocktable definition line, move time block into the future"
18904 (interactive "P")
18905 (cond
18906 ((run-hook-with-args-until-success 'org-shiftright-hook))
18907 ((and org-support-shift-select (org-region-active-p))
18908 (org-call-for-shift-select 'forward-char))
18909 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18910 ((and (not (eq org-support-shift-select 'always))
18911 (org-at-heading-p))
18912 (let ((org-inhibit-logging
18913 (not org-treat-S-cursor-todo-selection-as-state-change))
18914 (org-inhibit-blocking
18915 (not org-treat-S-cursor-todo-selection-as-state-change)))
18916 (org-call-with-arg 'org-todo 'right)))
18917 ((or (and org-support-shift-select
18918 (not (eq org-support-shift-select 'always))
18919 (org-at-item-bullet-p))
18920 (and (not org-support-shift-select) (org-at-item-p)))
18921 (org-call-with-arg 'org-cycle-list-bullet nil))
18922 ((and (not (eq org-support-shift-select 'always))
18923 (org-at-property-p))
18924 (call-interactively 'org-property-next-allowed-value))
18925 ((org-clocktable-try-shift 'right arg))
18926 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18927 (org-support-shift-select
18928 (org-call-for-shift-select 'forward-char))
18929 (t (org-shiftselect-error))))
18931 (defun org-shiftleft (&optional arg)
18932 "Cycle the thing at point or in the current line, depending on context.
18933 Depending on context, this does one of the following:
18935 - switch a timestamp at point one day into the past
18936 - on a headline, switch to the previous TODO keyword.
18937 - on an item, switch entire list to the previous bullet type
18938 - on a property line, switch to the previous allowed value
18939 - on a clocktable definition line, move time block into the past"
18940 (interactive "P")
18941 (cond
18942 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18943 ((and org-support-shift-select (org-region-active-p))
18944 (org-call-for-shift-select 'backward-char))
18945 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18946 ((and (not (eq org-support-shift-select 'always))
18947 (org-at-heading-p))
18948 (let ((org-inhibit-logging
18949 (not org-treat-S-cursor-todo-selection-as-state-change))
18950 (org-inhibit-blocking
18951 (not org-treat-S-cursor-todo-selection-as-state-change)))
18952 (org-call-with-arg 'org-todo 'left)))
18953 ((or (and org-support-shift-select
18954 (not (eq org-support-shift-select 'always))
18955 (org-at-item-bullet-p))
18956 (and (not org-support-shift-select) (org-at-item-p)))
18957 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18958 ((and (not (eq org-support-shift-select 'always))
18959 (org-at-property-p))
18960 (call-interactively 'org-property-previous-allowed-value))
18961 ((org-clocktable-try-shift 'left arg))
18962 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18963 (org-support-shift-select
18964 (org-call-for-shift-select 'backward-char))
18965 (t (org-shiftselect-error))))
18967 (defun org-shiftcontrolright ()
18968 "Switch to next TODO set."
18969 (interactive)
18970 (cond
18971 ((and org-support-shift-select (org-region-active-p))
18972 (org-call-for-shift-select 'forward-word))
18973 ((and (not (eq org-support-shift-select 'always))
18974 (org-at-heading-p))
18975 (org-call-with-arg 'org-todo 'nextset))
18976 (org-support-shift-select
18977 (org-call-for-shift-select 'forward-word))
18978 (t (org-shiftselect-error))))
18980 (defun org-shiftcontrolleft ()
18981 "Switch to previous TODO set."
18982 (interactive)
18983 (cond
18984 ((and org-support-shift-select (org-region-active-p))
18985 (org-call-for-shift-select 'backward-word))
18986 ((and (not (eq org-support-shift-select 'always))
18987 (org-at-heading-p))
18988 (org-call-with-arg 'org-todo 'previousset))
18989 (org-support-shift-select
18990 (org-call-for-shift-select 'backward-word))
18991 (t (org-shiftselect-error))))
18993 (defun org-shiftcontrolup ()
18994 "Change timestamps synchronously up in CLOCK log lines."
18995 (interactive)
18996 (cond ((and (not org-support-shift-select)
18997 (org-at-clock-log-p)
18998 (org-at-timestamp-p t))
18999 (org-clock-timestamps-up))
19000 (t (org-shiftselect-error))))
19002 (defun org-shiftcontroldown ()
19003 "Change timestamps synchronously down in CLOCK log lines."
19004 (interactive)
19005 (cond ((and (not org-support-shift-select)
19006 (org-at-clock-log-p)
19007 (org-at-timestamp-p t))
19008 (org-clock-timestamps-down))
19009 (t (org-shiftselect-error))))
19011 (defun org-ctrl-c-ret ()
19012 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19013 (interactive)
19014 (cond
19015 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19016 (t (call-interactively 'org-insert-heading))))
19018 (defun org-find-visible ()
19019 (let ((s (point)))
19020 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19021 (get-char-property s 'invisible)))
19023 (defun org-find-invisible ()
19024 (let ((s (point)))
19025 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19026 (not (get-char-property s 'invisible))))
19029 (defun org-copy-visible (beg end)
19030 "Copy the visible parts of the region."
19031 (interactive "r")
19032 (let (snippets s)
19033 (save-excursion
19034 (save-restriction
19035 (narrow-to-region beg end)
19036 (setq s (goto-char (point-min)))
19037 (while (not (= (point) (point-max)))
19038 (goto-char (org-find-invisible))
19039 (push (buffer-substring s (point)) snippets)
19040 (setq s (goto-char (org-find-visible))))))
19041 (kill-new (apply 'concat (nreverse snippets)))))
19043 (defun org-copy-special ()
19044 "Copy region in table or copy current subtree.
19045 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19046 See the individual commands for more information."
19047 (interactive)
19048 (call-interactively
19049 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19051 (defun org-cut-special ()
19052 "Cut region in table or cut current subtree.
19053 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19054 See the individual commands for more information."
19055 (interactive)
19056 (call-interactively
19057 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19059 (defun org-paste-special (arg)
19060 "Paste rectangular region into table, or past subtree relative to level.
19061 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19062 See the individual commands for more information."
19063 (interactive "P")
19064 (if (org-at-table-p)
19065 (org-table-paste-rectangle)
19066 (org-paste-subtree arg)))
19068 (defun org-edit-special (&optional arg)
19069 "Call a special editor for the stuff at point.
19070 When at a table, call the formula editor with `org-table-edit-formulas'.
19071 When at the first line of an src example, call `org-edit-src-code'.
19072 When in an #+include line, visit the include file. Otherwise call
19073 `ffap' to visit the file at point."
19074 (interactive)
19075 ;; possibly prep session before editing source
19076 (when arg
19077 (let* ((info (org-babel-get-src-block-info))
19078 (lang (nth 0 info))
19079 (params (nth 2 info))
19080 (session (cdr (assoc :session params))))
19081 (when (and info session) ;; we are in a source-code block with a session
19082 (funcall
19083 (intern (concat "org-babel-prep-session:" lang)) session params))))
19084 (cond ;; proceed with `org-edit-special'
19085 ((save-excursion
19086 (beginning-of-line 1)
19087 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19088 (find-file (org-trim (match-string 1))))
19089 ((org-edit-src-code))
19090 ((org-edit-fixed-width-region))
19091 ((org-at-table.el-p)
19092 (org-edit-src-code))
19093 ((or (org-at-table-p)
19094 (save-excursion
19095 (beginning-of-line 1)
19096 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19097 (call-interactively 'org-table-edit-formulas))
19098 (t (call-interactively 'ffap))))
19100 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19101 (defun org-ctrl-c-ctrl-c (&optional arg)
19102 "Set tags in headline, or update according to changed information at point.
19104 This command does many different things, depending on context:
19106 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19107 this is what we do.
19109 - If the cursor is on a statistics cookie, update it.
19111 - If the cursor is in a headline, prompt for tags and insert them
19112 into the current line, aligned to `org-tags-column'. When called
19113 with prefix arg, realign all tags in the current buffer.
19115 - If the cursor is in one of the special #+KEYWORD lines, this
19116 triggers scanning the buffer for these lines and updating the
19117 information.
19119 - If the cursor is inside a table, realign the table. This command
19120 works even if the automatic table editor has been turned off.
19122 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19123 the entire table.
19125 - If the cursor is at a footnote reference or definition, jump to
19126 the corresponding definition or references, respectively.
19128 - If the cursor is a the beginning of a dynamic block, update it.
19130 - If the current buffer is a capture buffer, close note and file it.
19132 - If the cursor is on a <<<target>>>, update radio targets and
19133 corresponding links in this buffer.
19135 - If the cursor is on a numbered item in a plain list, renumber the
19136 ordered list.
19138 - If the cursor is on a checkbox, toggle it.
19140 - If the cursor is on a code block, evaluate it. The variable
19141 `org-confirm-babel-evaluate' can be used to control prompting
19142 before code block evaluation, by default every code block
19143 evaluation requires confirmation. Code block evaluation can be
19144 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19145 (interactive "P")
19146 (let ((org-enable-table-editor t))
19147 (cond
19148 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19149 org-occur-highlights
19150 org-latex-fragment-image-overlays)
19151 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19152 (org-remove-occur-highlights)
19153 (org-remove-latex-fragment-image-overlays)
19154 (message "Temporary highlights/overlays removed from current buffer"))
19155 ((and (local-variable-p 'org-finish-function (current-buffer))
19156 (fboundp org-finish-function))
19157 (funcall org-finish-function))
19158 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19159 ((org-in-regexp org-ts-regexp-both)
19160 (org-timestamp-change 0 'day))
19161 ((or (looking-at org-property-start-re)
19162 (org-at-property-p))
19163 (call-interactively 'org-property-action))
19164 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19165 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19166 (or (org-at-heading-p) (org-at-item-p)))
19167 (call-interactively 'org-update-statistics-cookies))
19168 ((org-at-heading-p) (call-interactively 'org-set-tags))
19169 ((org-at-table.el-p)
19170 (message "Use C-c ' to edit table.el tables"))
19171 ((org-at-table-p)
19172 (org-table-maybe-eval-formula)
19173 (if arg
19174 (call-interactively 'org-table-recalculate)
19175 (org-table-maybe-recalculate-line))
19176 (call-interactively 'org-table-align)
19177 (orgtbl-send-table 'maybe))
19178 ((or (org-footnote-at-reference-p)
19179 (org-footnote-at-definition-p))
19180 (call-interactively 'org-footnote-action))
19181 ((org-at-item-checkbox-p)
19182 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19183 ;; list only if at top item.
19184 (let* ((cbox (match-string 1))
19185 (struct (org-list-struct))
19186 (old-struct (copy-tree struct))
19187 (parents (org-list-parents-alist struct))
19188 (orderedp (org-entry-get nil "ORDERED"))
19189 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19190 block-item)
19191 ;; Use a light version of `org-toggle-checkbox' to avoid
19192 ;; computing list structure twice.
19193 (let ((new-box (cond
19194 ((equal arg '(16)) "[-]")
19195 ((equal arg '(4)) nil)
19196 ((equal "[X]" cbox) "[ ]")
19197 (t "[X]"))))
19198 (if (and firstp arg)
19199 ;; If at first item of sub-list, remove check-box from
19200 ;; every item at the same level.
19201 (mapc
19202 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19203 (org-list-get-all-items
19204 (point-at-bol) struct (org-list-prevs-alist struct)))
19205 (org-list-set-checkbox (point-at-bol) struct new-box)))
19206 ;; Replicate `org-list-write-struct', while grabbing a return
19207 ;; value from `org-list-struct-fix-box'.
19208 (org-list-struct-fix-ind struct parents 2)
19209 (org-list-struct-fix-item-end struct)
19210 (let ((prevs (org-list-prevs-alist struct)))
19211 (org-list-struct-fix-bul struct prevs)
19212 (org-list-struct-fix-ind struct parents)
19213 (setq block-item
19214 (org-list-struct-fix-box struct parents prevs orderedp)))
19215 (org-list-struct-apply-struct struct old-struct)
19216 (org-update-checkbox-count-maybe)
19217 (when block-item
19218 (message
19219 "Checkboxes were removed due to unchecked box at line %d"
19220 (org-current-line block-item)))
19221 (when firstp (org-list-send-list 'maybe))))
19222 ((org-at-item-p)
19223 ;; Cursor at an item: repair list. Do checkbox related actions
19224 ;; only if function was called with an argument. Send list only
19225 ;; if at top item.
19226 (let* ((struct (org-list-struct))
19227 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19228 old-struct)
19229 (when arg
19230 (setq old-struct (copy-tree struct))
19231 (if firstp
19232 ;; If at first item of sub-list, add check-box to every
19233 ;; item at the same level.
19234 (mapc
19235 (lambda (pos)
19236 (unless (org-list-get-checkbox pos struct)
19237 (org-list-set-checkbox pos struct "[ ]")))
19238 (org-list-get-all-items
19239 (point-at-bol) struct (org-list-prevs-alist struct)))
19240 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19241 (org-list-write-struct
19242 struct (org-list-parents-alist struct) old-struct)
19243 (when arg (org-update-checkbox-count-maybe))
19244 (when firstp (org-list-send-list 'maybe))))
19245 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19246 ;; Dynamic block
19247 (beginning-of-line 1)
19248 (save-excursion (org-update-dblock)))
19249 ((save-excursion
19250 (let ((case-fold-search t))
19251 (beginning-of-line 1)
19252 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19253 (cond
19254 ((or (equal (match-string 1) "TBLFM")
19255 (equal (match-string 1) "tblfm"))
19256 ;; Recalculate the table before this line
19257 (save-excursion
19258 (beginning-of-line 1)
19259 (skip-chars-backward " \r\n\t")
19260 (if (org-at-table-p)
19261 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19263 (let ((org-inhibit-startup-visibility-stuff t)
19264 (org-startup-align-all-tables nil))
19265 (when (boundp 'org-table-coordinate-overlays)
19266 (mapc 'delete-overlay org-table-coordinate-overlays)
19267 (setq org-table-coordinate-overlays nil))
19268 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19269 (message "Local setup has been refreshed"))))
19270 ((org-clock-update-time-maybe))
19272 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19273 (error "C-c C-c can do nothing useful at this location"))))))
19275 (defun org-mode-restart ()
19276 "Restart Org-mode, to scan again for special lines.
19277 Also updates the keyword regular expressions."
19278 (interactive)
19279 (org-mode)
19280 (message "Org-mode restarted"))
19282 (defun org-kill-note-or-show-branches ()
19283 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19284 (interactive)
19285 (if (not org-finish-function)
19286 (progn
19287 (hide-subtree)
19288 (call-interactively 'show-branches))
19289 (let ((org-note-abort t))
19290 (funcall org-finish-function))))
19292 (defun org-return (&optional indent)
19293 "Goto next table row or insert a newline.
19294 Calls `org-table-next-row' or `newline', depending on context.
19295 See the individual commands for more information."
19296 (interactive)
19297 (let (org-ts-what)
19298 (cond
19299 ((or (bobp) (org-in-src-block-p))
19300 (if indent (newline-and-indent) (newline)))
19301 ((org-at-table-p)
19302 (org-table-justify-field-maybe)
19303 (call-interactively 'org-table-next-row))
19304 ;; when `newline-and-indent' is called within a list, make sure
19305 ;; text moved stays inside the item.
19306 ((and (org-in-item-p) indent)
19307 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19308 (progn
19309 (save-match-data (newline))
19310 (org-indent-line-to (length (match-string 0))))
19311 (let ((ind (org-get-indentation)))
19312 (newline)
19313 (if (org-looking-back org-list-end-re)
19314 (org-indent-line)
19315 (org-indent-line-to ind)))))
19316 ((and org-return-follows-link
19317 (org-at-timestamp-p t)
19318 (not (eq org-ts-what 'after)))
19319 (org-follow-timestamp-link))
19320 ((and org-return-follows-link
19321 (let ((tprop (get-text-property (point) 'face)))
19322 (or (eq tprop 'org-link)
19323 (and (listp tprop) (memq 'org-link tprop)))))
19324 (call-interactively 'org-open-at-point))
19325 ((and (org-at-heading-p)
19326 (looking-at
19327 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19328 (org-show-entry)
19329 (end-of-line 1)
19330 (newline))
19331 (t (if indent (newline-and-indent) (newline))))))
19333 (defun org-return-indent ()
19334 "Goto next table row or insert a newline and indent.
19335 Calls `org-table-next-row' or `newline-and-indent', depending on
19336 context. See the individual commands for more information."
19337 (interactive)
19338 (org-return t))
19340 (defun org-ctrl-c-star ()
19341 "Compute table, or change heading status of lines.
19342 Calls `org-table-recalculate' or `org-toggle-heading',
19343 depending on context."
19344 (interactive)
19345 (cond
19346 ((org-at-table-p)
19347 (call-interactively 'org-table-recalculate))
19349 ;; Convert all lines in region to list items
19350 (call-interactively 'org-toggle-heading))))
19352 (defun org-ctrl-c-minus ()
19353 "Insert separator line in table or modify bullet status of line.
19354 Also turns a plain line or a region of lines into list items.
19355 Calls `org-table-insert-hline', `org-toggle-item', or
19356 `org-cycle-list-bullet', depending on context."
19357 (interactive)
19358 (cond
19359 ((org-at-table-p)
19360 (call-interactively 'org-table-insert-hline))
19361 ((org-region-active-p)
19362 (call-interactively 'org-toggle-item))
19363 ((org-in-item-p)
19364 (call-interactively 'org-cycle-list-bullet))
19366 (call-interactively 'org-toggle-item))))
19368 (defun org-toggle-item (arg)
19369 "Convert headings or normal lines to items, items to normal lines.
19370 If there is no active region, only the current line is considered.
19372 If the first non blank line in the region is an headline, convert
19373 all headlines to items, shifting text accordingly.
19375 If it is an item, convert all items to normal lines.
19377 If it is normal text, change region into an item. With a prefix
19378 argument ARG, change each line in region into an item."
19379 (interactive "P")
19380 (let ((shift-text
19381 (function
19382 ;; Shift text in current section to IND, from point to END.
19383 ;; The function leaves point to END line.
19384 (lambda (ind end)
19385 (let ((min-i 1000) (end (copy-marker end)))
19386 ;; First determine the minimum indentation (MIN-I) of
19387 ;; the text.
19388 (save-excursion
19389 (catch 'exit
19390 (while (< (point) end)
19391 (let ((i (org-get-indentation)))
19392 (cond
19393 ;; Skip blank lines and inline tasks.
19394 ((looking-at "^[ \t]*$"))
19395 ((looking-at org-outline-regexp-bol))
19396 ;; We can't find less than 0 indentation.
19397 ((zerop i) (throw 'exit (setq min-i 0)))
19398 ((< i min-i) (setq min-i i))))
19399 (forward-line))))
19400 ;; Then indent each line so that a line indented to
19401 ;; MIN-I becomes indented to IND. Ignore blank lines
19402 ;; and inline tasks in the process.
19403 (let ((delta (- ind min-i)))
19404 (while (< (point) end)
19405 (unless (or (looking-at "^[ \t]*$")
19406 (looking-at org-outline-regexp-bol))
19407 (org-indent-line-to (+ (org-get-indentation) delta)))
19408 (forward-line)))))))
19409 (skip-blanks
19410 (function
19411 ;; Return beginning of first non-blank line, starting from
19412 ;; line at POS.
19413 (lambda (pos)
19414 (save-excursion
19415 (goto-char pos)
19416 (skip-chars-forward " \r\t\n")
19417 (point-at-bol)))))
19418 beg end)
19419 ;; Determine boundaries of changes.
19420 (if (org-region-active-p)
19421 (setq beg (funcall skip-blanks (region-beginning))
19422 end (copy-marker (region-end)))
19423 (setq beg (funcall skip-blanks (point-at-bol))
19424 end (copy-marker (point-at-eol))))
19425 ;; Depending on the starting line, choose an action on the text
19426 ;; between BEG and END.
19427 (org-with-limited-levels
19428 (save-excursion
19429 (goto-char beg)
19430 (cond
19431 ;; Case 1. Start at an item: de-itemize. Note that it only
19432 ;; happens when a region is active: `org-ctrl-c-minus'
19433 ;; would call `org-cycle-list-bullet' otherwise.
19434 ((org-at-item-p)
19435 (while (< (point) end)
19436 (when (org-at-item-p)
19437 (skip-chars-forward " \t")
19438 (delete-region (point) (match-end 0)))
19439 (forward-line)))
19440 ;; Case 2. Start at an heading: convert to items.
19441 ((org-at-heading-p)
19442 (let* ((bul (org-list-bullet-string "-"))
19443 (bul-len (length bul))
19444 ;; Indentation of the first heading. It should be
19445 ;; relative to the indentation of its parent, if any.
19446 (start-ind (save-excursion
19447 (cond
19448 ((not org-adapt-indentation) 0)
19449 ((not (outline-previous-heading)) 0)
19450 (t (length (match-string 0))))))
19451 ;; Level of first heading. Further headings will be
19452 ;; compared to it to determine hierarchy in the list.
19453 (ref-level (org-reduced-level (org-outline-level))))
19454 (while (< (point) end)
19455 (let* ((level (org-reduced-level (org-outline-level)))
19456 (delta (max 0 (- level ref-level))))
19457 ;; If current headline is less indented than the first
19458 ;; one, set it as reference, in order to preserve
19459 ;; subtrees.
19460 (when (< level ref-level) (setq ref-level level))
19461 (replace-match bul t t)
19462 (org-indent-line-to (+ start-ind (* delta bul-len)))
19463 ;; Ensure all text down to END (or SECTION-END) belongs
19464 ;; to the newly created item.
19465 (let ((section-end (save-excursion
19466 (or (outline-next-heading) (point)))))
19467 (forward-line)
19468 (funcall shift-text
19469 (+ start-ind (* (1+ delta) bul-len))
19470 (min end section-end)))))))
19471 ;; Case 3. Normal line with ARG: turn each non-item line into
19472 ;; an item.
19473 (arg
19474 (while (< (point) end)
19475 (unless (or (org-at-heading-p) (org-at-item-p))
19476 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19477 (replace-match
19478 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19479 (forward-line)))
19480 ;; Case 4. Normal line without ARG: make the first line of
19481 ;; region an item, and shift indentation of others
19482 ;; lines to set them as item's body.
19483 (t (let* ((bul (org-list-bullet-string "-"))
19484 (bul-len (length bul))
19485 (ref-ind (org-get-indentation)))
19486 (skip-chars-forward " \t")
19487 (insert bul)
19488 (forward-line)
19489 (while (< (point) end)
19490 ;; Ensure that lines less indented than first one
19491 ;; still get included in item body.
19492 (funcall shift-text
19493 (+ ref-ind bul-len)
19494 (min end (save-excursion (or (outline-next-heading)
19495 (point)))))
19496 (forward-line)))))))))
19498 (defun org-toggle-heading (&optional nstars)
19499 "Convert headings to normal text, or items or text to headings.
19500 If there is no active region, only the current line is considered.
19502 With a \\[universal-argument] prefix, convert the whole list at
19503 point into heading.
19505 In a region:
19507 - If the first non blank line is an headline, remove the stars
19508 from all headlines in the region.
19510 - If it is a normal line turn each and every normal line (i.e. not an
19511 heading or an item) in the region into a heading.
19513 - If it is a plain list item, turn all plain list items into headings.
19515 When converting a line into a heading, the number of stars is chosen
19516 such that the lines become children of the current entry. However,
19517 when a prefix argument is given, its value determines the number of
19518 stars to add."
19519 (interactive "P")
19520 (let ((skip-blanks
19521 (function
19522 ;; Return beginning of first non-blank line, starting from
19523 ;; line at POS.
19524 (lambda (pos)
19525 (save-excursion
19526 (goto-char pos)
19527 (while (org-at-comment-p) (forward-line))
19528 (skip-chars-forward " \r\t\n")
19529 (point-at-bol)))))
19530 beg end toggled)
19531 ;; Determine boundaries of changes. If a universal prefix has
19532 ;; been given, put the list in a region. If region ends at a bol,
19533 ;; do not consider the last line to be in the region.
19535 (when (and current-prefix-arg (org-at-item-p))
19536 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19537 (org-mark-element))
19539 (if (org-region-active-p)
19540 (setq beg (funcall skip-blanks (region-beginning))
19541 end (copy-marker (save-excursion
19542 (goto-char (region-end))
19543 (if (bolp) (point) (point-at-eol)))))
19544 (setq beg (funcall skip-blanks (point-at-bol))
19545 end (copy-marker (point-at-eol))))
19546 ;; Ensure inline tasks don't count as headings.
19547 (org-with-limited-levels
19548 (save-excursion
19549 (goto-char beg)
19550 (cond
19551 ;; Case 1. Started at an heading: de-star headings.
19552 ((org-at-heading-p)
19553 (while (< (point) end)
19554 (when (org-at-heading-p t)
19555 (looking-at org-outline-regexp) (replace-match "")
19556 (setq toggled t))
19557 (forward-line)))
19558 ;; Case 2. Started at an item: change items into headlines.
19559 ;; One star will be added by `org-list-to-subtree'.
19560 ((org-at-item-p)
19561 (let* ((stars (make-string
19562 (if nstars
19563 ;; subtract the star that will be added again by
19564 ;; `org-list-to-subtree'
19565 (1- (prefix-numeric-value current-prefix-arg))
19566 (or (org-current-level) 0))
19567 ?*))
19568 (add-stars
19569 (cond (nstars "") ; stars from prefix only
19570 ((equal stars "") "") ; before first heading
19571 (org-odd-levels-only "*") ; inside heading, odd
19572 (t "")))) ; inside heading, oddeven
19573 (while (< (point) end)
19574 (when (org-at-item-p)
19575 ;; Pay attention to cases when region ends before list.
19576 (let* ((struct (org-list-struct))
19577 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19578 (save-restriction
19579 (narrow-to-region (point) list-end)
19580 (insert
19581 (org-list-to-subtree
19582 (org-list-parse-list t)
19583 '(:istart (concat stars add-stars (funcall get-stars depth))
19584 :icount (concat stars add-stars (funcall get-stars depth)))))))
19585 (setq toggled t))
19586 (forward-line))))
19587 ;; Case 3. Started at normal text: make every line an heading,
19588 ;; skipping headlines and items.
19589 (t (let* ((stars (make-string
19590 (if nstars
19591 (prefix-numeric-value current-prefix-arg)
19592 (or (org-current-level) 0))
19593 ?*))
19594 (add-stars
19595 (cond (nstars "") ; stars from prefix only
19596 ((equal stars "") "*") ; before first heading
19597 (org-odd-levels-only "**") ; inside heading, odd
19598 (t "*"))) ; inside heading, oddeven
19599 (rpl (concat stars add-stars " ")))
19600 (while (< (point) end)
19601 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19602 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19603 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19604 (forward-line)))))))
19605 (unless toggled (message "Cannot toggle heading from here"))))
19607 (defun org-meta-return (&optional arg)
19608 "Insert a new heading or wrap a region in a table.
19609 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19610 See the individual commands for more information."
19611 (interactive "P")
19612 (cond
19613 ((run-hook-with-args-until-success 'org-metareturn-hook))
19614 ((or (org-at-drawer-p) (org-at-property-p))
19615 (newline-and-indent))
19616 ((org-at-table-p)
19617 (call-interactively 'org-table-wrap-region))
19618 (t (call-interactively 'org-insert-heading))))
19620 ;;; Menu entries
19622 ;; Define the Org-mode menus
19623 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19624 '("Tbl"
19625 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19626 ["Next Field" org-cycle (org-at-table-p)]
19627 ["Previous Field" org-shifttab (org-at-table-p)]
19628 ["Next Row" org-return (org-at-table-p)]
19629 "--"
19630 ["Blank Field" org-table-blank-field (org-at-table-p)]
19631 ["Edit Field" org-table-edit-field (org-at-table-p)]
19632 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19633 "--"
19634 ("Column"
19635 ["Move Column Left" org-metaleft (org-at-table-p)]
19636 ["Move Column Right" org-metaright (org-at-table-p)]
19637 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19638 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19639 ("Row"
19640 ["Move Row Up" org-metaup (org-at-table-p)]
19641 ["Move Row Down" org-metadown (org-at-table-p)]
19642 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19643 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19644 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19645 "--"
19646 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19647 ("Rectangle"
19648 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19649 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19650 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19651 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19652 "--"
19653 ("Calculate"
19654 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19655 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19656 ["Edit Formulas" org-edit-special (org-at-table-p)]
19657 "--"
19658 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19659 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19660 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19661 "--"
19662 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19663 "--"
19664 ["Sum Column/Rectangle" org-table-sum
19665 (or (org-at-table-p) (org-region-active-p))]
19666 ["Which Column?" org-table-current-column (org-at-table-p)])
19667 ["Debug Formulas"
19668 org-table-toggle-formula-debugger
19669 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19670 ["Show Col/Row Numbers"
19671 org-table-toggle-coordinate-overlays
19672 :style toggle
19673 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19674 "--"
19675 ["Create" org-table-create (and (not (org-at-table-p))
19676 org-enable-table-editor)]
19677 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19678 ["Import from File" org-table-import (not (org-at-table-p))]
19679 ["Export to File" org-table-export (org-at-table-p)]
19680 "--"
19681 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19683 (easy-menu-define org-org-menu org-mode-map "Org menu"
19684 '("Org"
19685 ("Show/Hide"
19686 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19687 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19688 ["Sparse Tree..." org-sparse-tree t]
19689 ["Reveal Context" org-reveal t]
19690 ["Show All" show-all t]
19691 "--"
19692 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19693 "--"
19694 ["New Heading" org-insert-heading t]
19695 ("Navigate Headings"
19696 ["Up" outline-up-heading t]
19697 ["Next" outline-next-visible-heading t]
19698 ["Previous" outline-previous-visible-heading t]
19699 ["Next Same Level" outline-forward-same-level t]
19700 ["Previous Same Level" outline-backward-same-level t]
19701 "--"
19702 ["Jump" org-goto t])
19703 ("Edit Structure"
19704 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19705 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19706 "--"
19707 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19708 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19709 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19710 "--"
19711 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19712 "--"
19713 ["Copy visible text" org-copy-visible t]
19714 "--"
19715 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19716 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19717 ["Demote Heading" org-metaright (not (org-at-table-p))]
19718 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19719 "--"
19720 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19721 "--"
19722 ["Convert to odd levels" org-convert-to-odd-levels t]
19723 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19724 ("Editing"
19725 ["Emphasis..." org-emphasize t]
19726 ["Edit Source Example" org-edit-special t]
19727 "--"
19728 ["Footnote new/jump" org-footnote-action t]
19729 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19730 ("Archive"
19731 ["Archive (default method)" org-archive-subtree-default t]
19732 "--"
19733 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19734 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19735 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19737 "--"
19738 ("Hyperlinks"
19739 ["Store Link (Global)" org-store-link t]
19740 ["Find existing link to here" org-occur-link-in-agenda-files t]
19741 ["Insert Link" org-insert-link t]
19742 ["Follow Link" org-open-at-point t]
19743 "--"
19744 ["Next link" org-next-link t]
19745 ["Previous link" org-previous-link t]
19746 "--"
19747 ["Descriptive Links"
19748 org-toggle-link-display
19749 :style radio
19750 :selected org-descriptive-links
19752 ["Literal Links"
19753 org-toggle-link-display
19754 :style radio
19755 :selected (not org-descriptive-links)])
19756 "--"
19757 ("TODO Lists"
19758 ["TODO/DONE/-" org-todo t]
19759 ("Select keyword"
19760 ["Next keyword" org-shiftright (org-at-heading-p)]
19761 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19762 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19763 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19764 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19765 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19766 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19767 "--"
19768 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19769 :selected org-enforce-todo-dependencies :style toggle :active t]
19770 "Settings for tree at point"
19771 ["Do Children sequentially" org-toggle-ordered-property :style radio
19772 :selected (org-entry-get nil "ORDERED")
19773 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19774 ["Do Children parallel" org-toggle-ordered-property :style radio
19775 :selected (not (org-entry-get nil "ORDERED"))
19776 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19777 "--"
19778 ["Set Priority" org-priority t]
19779 ["Priority Up" org-shiftup t]
19780 ["Priority Down" org-shiftdown t]
19781 "--"
19782 ["Get news from all feeds" org-feed-update-all t]
19783 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19784 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19785 ("TAGS and Properties"
19786 ["Set Tags" org-set-tags-command t]
19787 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19788 "--"
19789 ["Set property" org-set-property t]
19790 ["Column view of properties" org-columns t]
19791 ["Insert Column View DBlock" org-insert-columns-dblock t])
19792 ("Dates and Scheduling"
19793 ["Timestamp" org-time-stamp t]
19794 ["Timestamp (inactive)" org-time-stamp-inactive t]
19795 ("Change Date"
19796 ["1 Day Later" org-shiftright t]
19797 ["1 Day Earlier" org-shiftleft t]
19798 ["1 ... Later" org-shiftup t]
19799 ["1 ... Earlier" org-shiftdown t])
19800 ["Compute Time Range" org-evaluate-time-range t]
19801 ["Schedule Item" org-schedule t]
19802 ["Deadline" org-deadline t]
19803 "--"
19804 ["Custom time format" org-toggle-time-stamp-overlays
19805 :style radio :selected org-display-custom-times]
19806 "--"
19807 ["Goto Calendar" org-goto-calendar t]
19808 ["Date from Calendar" org-date-from-calendar t]
19809 "--"
19810 ["Start/Restart Timer" org-timer-start t]
19811 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19812 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19813 ["Insert Timer String" org-timer t]
19814 ["Insert Timer Item" org-timer-item t])
19815 ("Logging work"
19816 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19817 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19818 ["Clock out" org-clock-out t]
19819 ["Clock cancel" org-clock-cancel t]
19820 "--"
19821 ["Mark as default task" org-clock-mark-default-task t]
19822 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19823 ["Goto running clock" org-clock-goto t]
19824 "--"
19825 ["Display times" org-clock-display t]
19826 ["Create clock table" org-clock-report t]
19827 "--"
19828 ["Record DONE time"
19829 (progn (setq org-log-done (not org-log-done))
19830 (message "Switching to %s will %s record a timestamp"
19831 (car org-done-keywords)
19832 (if org-log-done "automatically" "not")))
19833 :style toggle :selected org-log-done])
19834 "--"
19835 ["Agenda Command..." org-agenda t]
19836 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19837 ("File List for Agenda")
19838 ("Special views current file"
19839 ["TODO Tree" org-show-todo-tree t]
19840 ["Check Deadlines" org-check-deadlines t]
19841 ["Timeline" org-timeline t]
19842 ["Tags/Property tree" org-match-sparse-tree t])
19843 "--"
19844 ["Export/Publish..." org-export t]
19845 ("LaTeX"
19846 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19847 :selected org-cdlatex-mode]
19848 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19849 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19850 ["Modify math symbol" org-cdlatex-math-modify
19851 (org-inside-LaTeX-fragment-p)]
19852 ["Insert citation" org-reftex-citation t]
19853 "--"
19854 ["Template for BEAMER" (progn (require 'org-beamer)
19855 (org-insert-beamer-options-template)) t])
19856 "--"
19857 ("MobileOrg"
19858 ["Push Files and Views" org-mobile-push t]
19859 ["Get Captured and Flagged" org-mobile-pull t]
19860 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19861 "--"
19862 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19863 "--"
19864 ("Documentation"
19865 ["Show Version" org-version t]
19866 ["Info Documentation" org-info t])
19867 ("Customize"
19868 ["Browse Org Group" org-customize t]
19869 "--"
19870 ["Expand This Menu" org-create-customize-menu
19871 (fboundp 'customize-menu-create)])
19872 ["Send bug report" org-submit-bug-report t]
19873 "--"
19874 ("Refresh/Reload"
19875 ["Refresh setup current buffer" org-mode-restart t]
19876 ["Reload Org (after update)" org-reload t]
19877 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19880 (defun org-info (&optional node)
19881 "Read documentation for Org-mode in the info system.
19882 With optional NODE, go directly to that node."
19883 (interactive)
19884 (info (format "(org)%s" (or node ""))))
19886 ;;;###autoload
19887 (defun org-submit-bug-report ()
19888 "Submit a bug report on Org-mode via mail.
19890 Don't hesitate to report any problems or inaccurate documentation.
19892 If you don't have setup sending mail from (X)Emacs, please copy the
19893 output buffer into your mail program, as it gives us important
19894 information about your Org-mode version and configuration."
19895 (interactive)
19896 (require 'reporter)
19897 (org-load-modules-maybe)
19898 (org-require-autoloaded-modules)
19899 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19900 (reporter-submit-bug-report
19901 "emacs-orgmode@gnu.org"
19902 (org-version nil 'full)
19903 (let (list)
19904 (save-window-excursion
19905 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19906 (delete-other-windows)
19907 (erase-buffer)
19908 (insert "You are about to submit a bug report to the Org-mode mailing list.
19910 We would like to add your full Org-mode and Outline configuration to the
19911 bug report. This greatly simplifies the work of the maintainer and
19912 other experts on the mailing list.
19914 HOWEVER, some variables you have customized may contain private
19915 information. The names of customers, colleagues, or friends, might
19916 appear in the form of file names, tags, todo states, or search strings.
19917 If you answer yes to the prompt, you might want to check and remove
19918 such private information before sending the email.")
19919 (add-text-properties (point-min) (point-max) '(face org-warning))
19920 (when (yes-or-no-p "Include your Org-mode configuration ")
19921 (mapatoms
19922 (lambda (v)
19923 (and (boundp v)
19924 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19925 (or (and (symbol-value v)
19926 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19927 (and
19928 (get v 'custom-type) (get v 'standard-value)
19929 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19930 (push v list)))))
19931 (kill-buffer (get-buffer "*Warn about privacy*"))
19932 list))
19933 nil nil
19934 "Remember to cover the basics, that is, what you expected to happen and
19935 what in fact did happen. You don't know how to make a good report? See
19937 http://orgmode.org/manual/Feedback.html#Feedback
19939 Your bug report will be posted to the Org-mode mailing list.
19940 ------------------------------------------------------------------------")
19941 (save-excursion
19942 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19943 (replace-match "\\1Bug: \\3 [\\2]")))))
19946 (defun org-install-agenda-files-menu ()
19947 (let ((bl (buffer-list)))
19948 (save-excursion
19949 (while bl
19950 (set-buffer (pop bl))
19951 (if (derived-mode-p 'org-mode) (setq bl nil)))
19952 (when (derived-mode-p 'org-mode)
19953 (easy-menu-change
19954 '("Org") "File List for Agenda"
19955 (append
19956 (list
19957 ["Edit File List" (org-edit-agenda-file-list) t]
19958 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19959 ["Remove Current File from List" org-remove-file t]
19960 ["Cycle through agenda files" org-cycle-agenda-files t]
19961 ["Occur in all agenda files" org-occur-in-agenda-files t]
19962 "--")
19963 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19965 ;;;; Documentation
19967 ;;;###autoload
19968 (defun org-require-autoloaded-modules ()
19969 (interactive)
19970 (mapc 'require
19971 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19972 org-docbook org-exp org-html org-icalendar
19973 org-id org-latex
19974 org-publish org-remember org-table
19975 org-timer org-xoxo)))
19977 ;;;###autoload
19978 (defun org-reload (&optional uncompiled)
19979 "Reload all org lisp files.
19980 With prefix arg UNCOMPILED, load the uncompiled versions."
19981 (interactive "P")
19982 (require 'find-func)
19983 (let* ((file-re "^org\\(-.*\\)?\\.el")
19984 (dir-org (file-name-directory (org-find-library-dir "org")))
19985 (dir-org-contrib (ignore-errors
19986 (file-name-directory
19987 (org-find-library-dir "org-contribdir"))))
19988 (babel-files
19989 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19990 (append (list nil "comint" "eval" "exp" "keys"
19991 "lob" "ref" "table" "tangle")
19992 (delq nil
19993 (mapcar
19994 (lambda (lang)
19995 (when (cdr lang) (symbol-name (car lang))))
19996 org-babel-load-languages)))))
19997 (files
19998 (append babel-files
19999 (and dir-org-contrib
20000 (directory-files dir-org-contrib t file-re))
20001 (directory-files dir-org t file-re)))
20002 (remove-re (concat (if (featurep 'xemacs)
20003 "org-colview" "org-colview-xemacs")
20004 "\\'")))
20005 (setq files (mapcar 'file-name-sans-extension files))
20006 (setq files (mapcar
20007 (lambda (x) (if (string-match remove-re x) nil x))
20008 files))
20009 (setq files (delq nil files))
20010 (mapc
20011 (lambda (f)
20012 (when (featurep (intern (file-name-nondirectory f)))
20013 (if (and (not uncompiled)
20014 (file-exists-p (concat f ".elc")))
20015 (load (concat f ".elc") nil nil 'nosuffix)
20016 (load (concat f ".el") nil nil 'nosuffix))))
20017 files)
20018 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20019 (org-version nil 'full 'message))
20021 ;;;###autoload
20022 (defun org-customize ()
20023 "Call the customize function with org as argument."
20024 (interactive)
20025 (org-load-modules-maybe)
20026 (org-require-autoloaded-modules)
20027 (customize-browse 'org))
20029 (defun org-create-customize-menu ()
20030 "Create a full customization menu for Org-mode, insert it into the menu."
20031 (interactive)
20032 (org-load-modules-maybe)
20033 (org-require-autoloaded-modules)
20034 (if (fboundp 'customize-menu-create)
20035 (progn
20036 (easy-menu-change
20037 '("Org") "Customize"
20038 `(["Browse Org group" org-customize t]
20039 "--"
20040 ,(customize-menu-create 'org)
20041 ["Set" Custom-set t]
20042 ["Save" Custom-save t]
20043 ["Reset to Current" Custom-reset-current t]
20044 ["Reset to Saved" Custom-reset-saved t]
20045 ["Reset to Standard Settings" Custom-reset-standard t]))
20046 (message "\"Org\"-menu now contains full customization menu"))
20047 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20049 ;;;; Miscellaneous stuff
20051 ;;; Generally useful functions
20053 (defun org-get-at-bol (property)
20054 "Get text property PROPERTY at beginning of line."
20055 (get-text-property (point-at-bol) property))
20057 (defun org-find-text-property-in-string (prop s)
20058 "Return the first non-nil value of property PROP in string S."
20059 (or (get-text-property 0 prop s)
20060 (get-text-property (or (next-single-property-change 0 prop s) 0)
20061 prop s)))
20063 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20064 "Display the given MESSAGE as a warning."
20065 (if (fboundp 'display-warning)
20066 (display-warning 'org message
20067 (if (featurep 'xemacs) 'warning :warning))
20068 (let ((buf (get-buffer-create "*Org warnings*")))
20069 (with-current-buffer buf
20070 (goto-char (point-max))
20071 (insert "Warning (Org): " message)
20072 (unless (bolp)
20073 (newline)))
20074 (display-buffer buf)
20075 (sit-for 0))))
20077 (defun org-eval (form)
20078 "Eval FORM and return result."
20079 (condition-case error
20080 (eval form)
20081 (error (format "%%![Error: %s]" error))))
20083 (defun org-in-clocktable-p ()
20084 "Check if the cursor is in a clocktable."
20085 (let ((pos (point)) start)
20086 (save-excursion
20087 (end-of-line 1)
20088 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20089 (setq start (match-beginning 0))
20090 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20091 (>= (match-end 0) pos)
20092 start))))
20094 (defun org-in-commented-line ()
20095 "Is point in a line starting with `#'?"
20096 (equal (char-after (point-at-bol)) ?#))
20098 (defun org-in-indented-comment-line ()
20099 "Is point in a line starting with `#' after some white space?"
20100 (save-excursion
20101 (save-match-data
20102 (goto-char (point-at-bol))
20103 (looking-at "[ \t]*#"))))
20105 (defun org-in-verbatim-emphasis ()
20106 (save-match-data
20107 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20109 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20110 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20111 (if (and marker (marker-buffer marker)
20112 (buffer-live-p (marker-buffer marker)))
20113 (progn
20114 (org-pop-to-buffer-same-window (marker-buffer marker))
20115 (if (or (> marker (point-max)) (< marker (point-min)))
20116 (widen))
20117 (goto-char marker)
20118 (org-show-context 'org-goto))
20119 (if bookmark
20120 (bookmark-jump bookmark)
20121 (error "Cannot find location"))))
20123 (defun org-quote-csv-field (s)
20124 "Quote field for inclusion in CSV material."
20125 (if (string-match "[\",]" s)
20126 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20129 (defun org-force-self-insert (N)
20130 "Needed to enforce self-insert under remapping."
20131 (interactive "p")
20132 (self-insert-command N))
20134 (defun org-string-width (s)
20135 "Compute width of string, ignoring invisible characters.
20136 This ignores character with invisibility property `org-link', and also
20137 characters with property `org-cwidth', because these will become invisible
20138 upon the next fontification round."
20139 (let (b l)
20140 (when (or (eq t buffer-invisibility-spec)
20141 (assq 'org-link buffer-invisibility-spec))
20142 (while (setq b (text-property-any 0 (length s)
20143 'invisible 'org-link s))
20144 (setq s (concat (substring s 0 b)
20145 (substring s (or (next-single-property-change
20146 b 'invisible s) (length s)))))))
20147 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20148 (setq s (concat (substring s 0 b)
20149 (substring s (or (next-single-property-change
20150 b 'org-cwidth s) (length s))))))
20151 (setq l (string-width s) b -1)
20152 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20153 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20156 (defun org-shorten-string (s maxlength)
20157 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20158 If the string is shorter or has length MAXLENGTH, just return the
20159 original string. If it is longer, the functions finds a space in the
20160 string, breaks this string off at that locations and adds three dots
20161 as ellipsis. Including the ellipsis, the string will not be longer
20162 than MAXLENGTH. If finding a good breaking point in the string does
20163 not work, the string is just chopped off in the middle of a word
20164 if necessary."
20165 (if (<= (length s) maxlength)
20167 (let* ((n (max (- maxlength 4) 1))
20168 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20169 (if (string-match re s)
20170 (concat (match-string 1 s) "...")
20171 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20173 (defun org-get-indentation (&optional line)
20174 "Get the indentation of the current line, interpreting tabs.
20175 When LINE is given, assume it represents a line and compute its indentation."
20176 (if line
20177 (if (string-match "^ *" (org-remove-tabs line))
20178 (match-end 0))
20179 (save-excursion
20180 (beginning-of-line 1)
20181 (skip-chars-forward " \t")
20182 (current-column))))
20184 (defun org-get-string-indentation (s)
20185 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20186 (let ((n -1) (i 0) (w tab-width) c)
20187 (catch 'exit
20188 (while (< (setq n (1+ n)) (length s))
20189 (setq c (aref s n))
20190 (cond ((= c ?\ ) (setq i (1+ i)))
20191 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20192 (t (throw 'exit t)))))
20195 (defun org-remove-tabs (s &optional width)
20196 "Replace tabulators in S with spaces.
20197 Assumes that s is a single line, starting in column 0."
20198 (setq width (or width tab-width))
20199 (while (string-match "\t" s)
20200 (setq s (replace-match
20201 (make-string
20202 (- (* width (/ (+ (match-beginning 0) width) width))
20203 (match-beginning 0)) ?\ )
20204 t t s)))
20207 (defun org-fix-indentation (line ind)
20208 "Fix indentation in LINE.
20209 IND is a cons cell with target and minimum indentation.
20210 If the current indentation in LINE is smaller than the minimum,
20211 leave it alone. If it is larger than ind, set it to the target."
20212 (let* ((l (org-remove-tabs line))
20213 (i (org-get-indentation l))
20214 (i1 (car ind)) (i2 (cdr ind)))
20215 (if (>= i i2) (setq l (substring line i2)))
20216 (if (> i1 0)
20217 (concat (make-string i1 ?\ ) l)
20218 l)))
20220 (defun org-remove-indentation (code &optional n)
20221 "Remove the maximum common indentation from the lines in CODE.
20222 N may optionally be the number of spaces to remove."
20223 (with-temp-buffer
20224 (insert code)
20225 (org-do-remove-indentation n)
20226 (buffer-string)))
20228 (defun org-do-remove-indentation (&optional n)
20229 "Remove the maximum common indentation from the buffer."
20230 (untabify (point-min) (point-max))
20231 (let ((min 10000) re)
20232 (if n
20233 (setq min n)
20234 (goto-char (point-min))
20235 (while (re-search-forward "^ *[^ \n]" nil t)
20236 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20237 (unless (or (= min 0) (= min 10000))
20238 (setq re (format "^ \\{%d\\}" min))
20239 (goto-char (point-min))
20240 (while (re-search-forward re nil t)
20241 (replace-match "")
20242 (end-of-line 1))
20243 min)))
20245 (defun org-fill-template (template alist)
20246 "Find each %key of ALIST in TEMPLATE and replace it."
20247 (let ((case-fold-search nil)
20248 entry key value)
20249 (setq alist (sort (copy-sequence alist)
20250 (lambda (a b) (< (length (car a)) (length (car b))))))
20251 (while (setq entry (pop alist))
20252 (setq template
20253 (replace-regexp-in-string
20254 (concat "%" (regexp-quote (car entry)))
20255 (or (cdr entry) "") template t t)))
20256 template))
20258 (defun org-base-buffer (buffer)
20259 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20260 (if (not buffer)
20261 buffer
20262 (or (buffer-base-buffer buffer)
20263 buffer)))
20265 (defun org-trim (s)
20266 "Remove whitespace at beginning and end of string."
20267 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20268 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20271 (defun org-wrap (string &optional width lines)
20272 "Wrap string to either a number of lines, or a width in characters.
20273 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20274 that costs. If there is a word longer than WIDTH, the text is actually
20275 wrapped to the length of that word.
20276 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20277 many lines, whatever width that takes.
20278 The return value is a list of lines, without newlines at the end."
20279 (let* ((words (org-split-string string "[ \t\n]+"))
20280 (maxword (apply 'max (mapcar 'org-string-width words)))
20281 w ll)
20282 (cond (width
20283 (org-do-wrap words (max maxword width)))
20284 (lines
20285 (setq w maxword)
20286 (setq ll (org-do-wrap words maxword))
20287 (if (<= (length ll) lines)
20289 (setq ll words)
20290 (while (> (length ll) lines)
20291 (setq w (1+ w))
20292 (setq ll (org-do-wrap words w)))
20293 ll))
20294 (t (error "Cannot wrap this")))))
20296 (defun org-do-wrap (words width)
20297 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20298 (let (lines line)
20299 (while words
20300 (setq line (pop words))
20301 (while (and words (< (+ (length line) (length (car words))) width))
20302 (setq line (concat line " " (pop words))))
20303 (setq lines (push line lines)))
20304 (nreverse lines)))
20306 (defun org-split-string (string &optional separators)
20307 "Splits STRING into substrings at SEPARATORS.
20308 No empty strings are returned if there are matches at the beginning
20309 and end of string."
20310 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20311 (start 0)
20312 notfirst
20313 (list nil))
20314 (while (and (string-match rexp string
20315 (if (and notfirst
20316 (= start (match-beginning 0))
20317 (< start (length string)))
20318 (1+ start) start))
20319 (< (match-beginning 0) (length string)))
20320 (setq notfirst t)
20321 (or (eq (match-beginning 0) 0)
20322 (and (eq (match-beginning 0) (match-end 0))
20323 (eq (match-beginning 0) start))
20324 (setq list
20325 (cons (substring string start (match-beginning 0))
20326 list)))
20327 (setq start (match-end 0)))
20328 (or (eq start (length string))
20329 (setq list
20330 (cons (substring string start)
20331 list)))
20332 (nreverse list)))
20334 (defun org-quote-vert (s)
20335 "Replace \"|\" with \"\\vert\"."
20336 (while (string-match "|" s)
20337 (setq s (replace-match "\\vert" t t s)))
20340 (defun org-uuidgen-p (s)
20341 "Is S an ID created by UUIDGEN?"
20342 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20344 (defun org-in-src-block-p nil
20345 "Whether point is in a code source block."
20346 (let (ov)
20347 (when (setq ov (overlays-at (point)))
20348 (memq 'org-block-background
20349 (overlay-properties
20350 (car ov))))))
20352 (defun org-context ()
20353 "Return a list of contexts of the current cursor position.
20354 If several contexts apply, all are returned.
20355 Each context entry is a list with a symbol naming the context, and
20356 two positions indicating start and end of the context. Possible
20357 contexts are:
20359 :headline anywhere in a headline
20360 :headline-stars on the leading stars in a headline
20361 :todo-keyword on a TODO keyword (including DONE) in a headline
20362 :tags on the TAGS in a headline
20363 :priority on the priority cookie in a headline
20364 :item on the first line of a plain list item
20365 :item-bullet on the bullet/number of a plain list item
20366 :checkbox on the checkbox in a plain list item
20367 :table in an org-mode table
20368 :table-special on a special filed in a table
20369 :table-table in a table.el table
20370 :clocktable in a clocktable
20371 :src-block in a source block
20372 :link on a hyperlink
20373 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20374 :target on a <<target>>
20375 :radio-target on a <<<radio-target>>>
20376 :latex-fragment on a LaTeX fragment
20377 :latex-preview on a LaTeX fragment with overlaid preview image
20379 This function expects the position to be visible because it uses font-lock
20380 faces as a help to recognize the following contexts: :table-special, :link,
20381 and :keyword."
20382 (let* ((f (get-text-property (point) 'face))
20383 (faces (if (listp f) f (list f)))
20384 (case-fold-search t)
20385 (p (point)) clist o)
20386 ;; First the large context
20387 (cond
20388 ((org-at-heading-p t)
20389 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20390 (when (progn
20391 (beginning-of-line 1)
20392 (looking-at org-todo-line-tags-regexp))
20393 (push (org-point-in-group p 1 :headline-stars) clist)
20394 (push (org-point-in-group p 2 :todo-keyword) clist)
20395 (push (org-point-in-group p 4 :tags) clist))
20396 (goto-char p)
20397 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20398 (if (looking-at "\\[#[A-Z0-9]\\]")
20399 (push (org-point-in-group p 0 :priority) clist)))
20401 ((org-at-item-p)
20402 (push (org-point-in-group p 2 :item-bullet) clist)
20403 (push (list :item (point-at-bol)
20404 (save-excursion (org-end-of-item) (point)))
20405 clist)
20406 (and (org-at-item-checkbox-p)
20407 (push (org-point-in-group p 0 :checkbox) clist)))
20409 ((org-at-table-p)
20410 (push (list :table (org-table-begin) (org-table-end)) clist)
20411 (if (memq 'org-formula faces)
20412 (push (list :table-special
20413 (previous-single-property-change p 'face)
20414 (next-single-property-change p 'face)) clist)))
20415 ((org-at-table-p 'any)
20416 (push (list :table-table) clist)))
20417 (goto-char p)
20419 (let ((case-fold-search t))
20420 ;; New the "medium" contexts: clocktables, source blocks
20421 (cond ((org-in-clocktable-p)
20422 (push (list :clocktable
20423 (and (or (looking-at "#\\+BEGIN: clocktable")
20424 (search-backward "#+BEGIN: clocktable" nil t))
20425 (match-beginning 0))
20426 (and (re-search-forward "#\\+END:?" nil t)
20427 (match-end 0))) clist))
20428 ((org-in-src-block-p)
20429 (push (list :src-block
20430 (and (or (looking-at "#\\+BEGIN_SRC")
20431 (search-backward "#+BEGIN_SRC" nil t))
20432 (match-beginning 0))
20433 (and (search-forward "#+END_SRC" nil t)
20434 (match-beginning 0))) clist))))
20435 (goto-char p)
20437 ;; Now the small context
20438 (cond
20439 ((org-at-timestamp-p)
20440 (push (org-point-in-group p 0 :timestamp) clist))
20441 ((memq 'org-link faces)
20442 (push (list :link
20443 (previous-single-property-change p 'face)
20444 (next-single-property-change p 'face)) clist))
20445 ((memq 'org-special-keyword faces)
20446 (push (list :keyword
20447 (previous-single-property-change p 'face)
20448 (next-single-property-change p 'face)) clist))
20449 ((org-at-target-p)
20450 (push (org-point-in-group p 0 :target) clist)
20451 (goto-char (1- (match-beginning 0)))
20452 (if (looking-at org-radio-target-regexp)
20453 (push (org-point-in-group p 0 :radio-target) clist))
20454 (goto-char p))
20455 ((setq o (car (delq nil
20456 (mapcar
20457 (lambda (x)
20458 (if (memq x org-latex-fragment-image-overlays) x))
20459 (overlays-at (point))))))
20460 (push (list :latex-fragment
20461 (overlay-start o) (overlay-end o)) clist)
20462 (push (list :latex-preview
20463 (overlay-start o) (overlay-end o)) clist))
20464 ((org-inside-LaTeX-fragment-p)
20465 ;; FIXME: positions wrong.
20466 (push (list :latex-fragment (point) (point)) clist)))
20468 (setq clist (nreverse (delq nil clist)))
20469 clist))
20471 ;; FIXME: Compare with at-regexp-p Do we need both?
20472 (defun org-in-regexp (re &optional nlines visually)
20473 "Check if point is inside a match of regexp.
20474 Normally only the current line is checked, but you can include NLINES extra
20475 lines both before and after point into the search.
20476 If VISUALLY is set, require that the cursor is not after the match but
20477 really on, so that the block visually is on the match."
20478 (catch 'exit
20479 (let ((pos (point))
20480 (eol (point-at-eol (+ 1 (or nlines 0))))
20481 (inc (if visually 1 0)))
20482 (save-excursion
20483 (beginning-of-line (- 1 (or nlines 0)))
20484 (while (re-search-forward re eol t)
20485 (if (and (<= (match-beginning 0) pos)
20486 (>= (+ inc (match-end 0)) pos))
20487 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20489 (defun org-at-regexp-p (regexp)
20490 "Is point inside a match of REGEXP in the current line?"
20491 (catch 'exit
20492 (save-excursion
20493 (let ((pos (point)) (end (point-at-eol)))
20494 (beginning-of-line 1)
20495 (while (re-search-forward regexp end t)
20496 (if (and (<= (match-beginning 0) pos)
20497 (>= (match-end 0) pos))
20498 (throw 'exit t)))
20499 nil))))
20501 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20502 "Non-nil when point is between matches of START-RE and END-RE.
20504 Also return a non-nil value when point is on one of the matches.
20506 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20507 buffer positions. Default values are the positions of headlines
20508 surrounding the point.
20510 The functions returns a cons cell whose car (resp. cdr) is the
20511 position before START-RE (resp. after END-RE)."
20512 (save-match-data
20513 (let ((pos (point))
20514 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20515 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20516 beg end)
20517 (save-excursion
20518 ;; Point is on a block when on START-RE or if START-RE can be
20519 ;; found before it...
20520 (and (or (org-at-regexp-p start-re)
20521 (re-search-backward start-re limit-up t))
20522 (setq beg (match-beginning 0))
20523 ;; ... and END-RE after it...
20524 (goto-char (match-end 0))
20525 (re-search-forward end-re limit-down t)
20526 (> (setq end (match-end 0)) pos)
20527 ;; ... without another START-RE in-between.
20528 (goto-char (match-beginning 0))
20529 (not (re-search-backward start-re (1+ beg) t))
20530 ;; Return value.
20531 (cons beg end))))))
20533 (defun org-in-block-p (names)
20534 "Non-nil when point belongs to a block whose name belongs to NAMES.
20536 NAMES is a list of strings containing names of blocks.
20538 Return first block name matched, or nil. Beware that in case of
20539 nested blocks, the returned name may not belong to the closest
20540 block from point."
20541 (save-match-data
20542 (catch 'exit
20543 (let ((case-fold-search t)
20544 (lim-up (save-excursion (outline-previous-heading)))
20545 (lim-down (save-excursion (outline-next-heading))))
20546 (mapc (lambda (name)
20547 (let ((n (regexp-quote name)))
20548 (when (org-between-regexps-p
20549 (concat "^[ \t]*#\\+begin_" n)
20550 (concat "^[ \t]*#\\+end_" n)
20551 lim-up lim-down)
20552 (throw 'exit n))))
20553 names))
20554 nil)))
20556 (defun org-occur-in-agenda-files (regexp &optional nlines)
20557 "Call `multi-occur' with buffers for all agenda files."
20558 (interactive "sOrg-files matching: \np")
20559 (let* ((files (org-agenda-files))
20560 (tnames (mapcar 'file-truename files))
20561 (extra org-agenda-text-search-extra-files)
20563 (when (eq (car extra) 'agenda-archives)
20564 (setq extra (cdr extra))
20565 (setq files (org-add-archive-files files)))
20566 (while (setq f (pop extra))
20567 (unless (member (file-truename f) tnames)
20568 (add-to-list 'files f 'append)
20569 (add-to-list 'tnames (file-truename f) 'append)))
20570 (multi-occur
20571 (mapcar (lambda (x)
20572 (with-current-buffer
20573 (or (get-file-buffer x) (find-file-noselect x))
20574 (widen)
20575 (current-buffer)))
20576 files)
20577 regexp)))
20579 (if (boundp 'occur-mode-find-occurrence-hook)
20580 ;; Emacs 23
20581 (add-hook 'occur-mode-find-occurrence-hook
20582 (lambda ()
20583 (when (derived-mode-p 'org-mode)
20584 (org-reveal))))
20585 ;; Emacs 22
20586 (defadvice occur-mode-goto-occurrence
20587 (after org-occur-reveal activate)
20588 (and (derived-mode-p 'org-mode) (org-reveal)))
20589 (defadvice occur-mode-goto-occurrence-other-window
20590 (after org-occur-reveal activate)
20591 (and (derived-mode-p 'org-mode) (org-reveal)))
20592 (defadvice occur-mode-display-occurrence
20593 (after org-occur-reveal activate)
20594 (when (derived-mode-p 'org-mode)
20595 (let ((pos (occur-mode-find-occurrence)))
20596 (with-current-buffer (marker-buffer pos)
20597 (save-excursion
20598 (goto-char pos)
20599 (org-reveal)))))))
20601 (defun org-occur-link-in-agenda-files ()
20602 "Create a link and search for it in the agendas.
20603 The link is not stored in `org-stored-links', it is just created
20604 for the search purpose."
20605 (interactive)
20606 (let ((link (condition-case nil
20607 (org-store-link nil)
20608 (error "Unable to create a link to here"))))
20609 (org-occur-in-agenda-files (regexp-quote link))))
20611 (defun org-uniquify (list)
20612 "Remove duplicate elements from LIST."
20613 (let (res)
20614 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20615 res))
20617 (defun org-delete-all (elts list)
20618 "Remove all elements in ELTS from LIST."
20619 (while elts
20620 (setq list (delete (pop elts) list)))
20621 list)
20623 (defun org-count (cl-item cl-seq)
20624 "Count the number of occurrences of ITEM in SEQ.
20625 Taken from `count' in cl-seq.el with all keyword arguments removed."
20626 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20627 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20628 (while (< cl-start cl-end)
20629 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20630 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20631 (setq cl-start (1+ cl-start)))
20632 cl-count))
20634 (defun org-remove-if (predicate seq)
20635 "Remove everything from SEQ that fulfills PREDICATE."
20636 (let (res e)
20637 (while seq
20638 (setq e (pop seq))
20639 (if (not (funcall predicate e)) (push e res)))
20640 (nreverse res)))
20642 (defun org-remove-if-not (predicate seq)
20643 "Remove everything from SEQ that does not fulfill PREDICATE."
20644 (let (res e)
20645 (while seq
20646 (setq e (pop seq))
20647 (if (funcall predicate e) (push e res)))
20648 (nreverse res)))
20650 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20651 "Reduce two-argument FUNCTION across SEQ.
20652 Taken from `reduce' in cl-seq.el with all keyword arguments but
20653 \":initial-value\" removed."
20654 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20655 (cadr (memq :initial-value cl-keys)))
20656 (cl-seq (pop cl-seq))
20657 (t (funcall cl-func)))))
20658 (while cl-seq
20659 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20660 cl-accum))
20662 (defun org-back-over-empty-lines ()
20663 "Move backwards over whitespace, to the beginning of the first empty line.
20664 Returns the number of empty lines passed."
20665 (let ((pos (point)))
20666 (if (cdr (assoc 'heading org-blank-before-new-entry))
20667 (skip-chars-backward " \t\n\r")
20668 (unless (eobp)
20669 (forward-line -1)))
20670 (beginning-of-line 2)
20671 (goto-char (min (point) pos))
20672 (count-lines (point) pos)))
20674 (defun org-skip-whitespace ()
20675 (skip-chars-forward " \t\n\r"))
20677 (defun org-point-in-group (point group &optional context)
20678 "Check if POINT is in match-group GROUP.
20679 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20680 match. If the match group does not exist or point is not inside it,
20681 return nil."
20682 (and (match-beginning group)
20683 (>= point (match-beginning group))
20684 (<= point (match-end group))
20685 (if context
20686 (list context (match-beginning group) (match-end group))
20687 t)))
20689 (defun org-switch-to-buffer-other-window (&rest args)
20690 "Switch to buffer in a second window on the current frame.
20691 In particular, do not allow pop-up frames.
20692 Returns the newly created buffer."
20693 (let (pop-up-frames special-display-buffer-names special-display-regexps
20694 special-display-function)
20695 (apply 'switch-to-buffer-other-window args)))
20697 (defun org-combine-plists (&rest plists)
20698 "Create a single property list from all plists in PLISTS.
20699 The process starts by copying the first list, and then setting properties
20700 from the other lists. Settings in the last list are the most significant
20701 ones and overrule settings in the other lists."
20702 (let ((rtn (copy-sequence (pop plists)))
20703 p v ls)
20704 (while plists
20705 (setq ls (pop plists))
20706 (while ls
20707 (setq p (pop ls) v (pop ls))
20708 (setq rtn (plist-put rtn p v))))
20709 rtn))
20711 (defun org-replace-escapes (string table)
20712 "Replace %-escapes in STRING with values in TABLE.
20713 TABLE is an association list with keys like \"%a\" and string values.
20714 The sequences in STRING may contain normal field width and padding information,
20715 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20716 so values can contain further %-escapes if they are define later in TABLE."
20717 (let ((tbl (copy-alist table))
20718 (case-fold-search nil)
20719 (pchg 0)
20720 e re rpl)
20721 (while (setq e (pop tbl))
20722 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20723 (when (and (cdr e) (string-match re (cdr e)))
20724 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20725 (safe "SREF"))
20726 (add-text-properties 0 3 (list 'sref sref) safe)
20727 (setcdr e (replace-match safe t t (cdr e)))))
20728 (while (string-match re string)
20729 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20730 (cdr e)))
20731 (setq string (replace-match rpl t t string))))
20732 (while (setq pchg (next-property-change pchg string))
20733 (let ((sref (get-text-property pchg 'sref string)))
20734 (when (and sref (string-match "SREF" string pchg))
20735 (setq string (replace-match sref t t string)))))
20736 string))
20738 (defun org-sublist (list start end)
20739 "Return a section of LIST, from START to END.
20740 Counting starts at 1."
20741 (let (rtn (c start))
20742 (setq list (nthcdr (1- start) list))
20743 (while (and list (<= c end))
20744 (push (pop list) rtn)
20745 (setq c (1+ c)))
20746 (nreverse rtn)))
20748 (defun org-find-base-buffer-visiting (file)
20749 "Like `find-buffer-visiting' but always return the base buffer and
20750 not an indirect buffer."
20751 (let ((buf (or (get-file-buffer file)
20752 (find-buffer-visiting file))))
20753 (if buf
20754 (or (buffer-base-buffer buf) buf)
20755 nil)))
20757 (defun org-image-file-name-regexp (&optional extensions)
20758 "Return regexp matching the file names of images.
20759 If EXTENSIONS is given, only match these."
20760 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20761 (image-file-name-regexp)
20762 (let ((image-file-name-extensions
20763 (or extensions
20764 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20765 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20766 (concat "\\."
20767 (regexp-opt (nconc (mapcar 'upcase
20768 image-file-name-extensions)
20769 image-file-name-extensions)
20771 "\\'"))))
20773 (defun org-file-image-p (file &optional extensions)
20774 "Return non-nil if FILE is an image."
20775 (save-match-data
20776 (string-match (org-image-file-name-regexp extensions) file)))
20778 (defun org-get-cursor-date ()
20779 "Return the date at cursor in as a time.
20780 This works in the calendar and in the agenda, anywhere else it just
20781 returns the current time."
20782 (let (date day defd)
20783 (cond
20784 ((eq major-mode 'calendar-mode)
20785 (setq date (calendar-cursor-to-date)
20786 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20787 ((eq major-mode 'org-agenda-mode)
20788 (setq day (get-text-property (point) 'day))
20789 (if day
20790 (setq date (calendar-gregorian-from-absolute day)
20791 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20792 (nth 2 date))))))
20793 (or defd (current-time))))
20795 (defvar org-agenda-action-marker (make-marker)
20796 "Marker pointing to the entry for the next agenda action.")
20798 (defun org-mark-entry-for-agenda-action ()
20799 "Mark the current entry as target of an agenda action.
20800 Agenda actions are actions executed from the agenda with the key `k',
20801 which make use of the date at the cursor."
20802 (interactive)
20803 (move-marker org-agenda-action-marker
20804 (save-excursion (org-back-to-heading t) (point))
20805 (current-buffer))
20806 (message
20807 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20809 (defun org-mark-subtree (&optional up)
20810 "Mark the current subtree.
20811 This puts point at the start of the current subtree, and mark at
20812 the end. If a numeric prefix UP is given, move up into the
20813 hierarchy of headlines by UP levels before marking the subtree."
20814 (interactive "P")
20815 (org-with-limited-levels
20816 (cond ((org-at-heading-p) (beginning-of-line))
20817 ((org-before-first-heading-p) (error "Not in a subtree"))
20818 (t (outline-previous-visible-heading 1))))
20819 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20820 (if (org-called-interactively-p 'any)
20821 (call-interactively 'org-mark-element)
20822 (org-mark-element)))
20824 ;;; Indentation
20826 (defun org-indent-line ()
20827 "Indent line depending on context."
20828 (interactive)
20829 (let* ((pos (point))
20830 (itemp (org-at-item-p))
20831 (case-fold-search t)
20832 (org-drawer-regexp (or org-drawer-regexp "\000"))
20833 (inline-task-p (and (featurep 'org-inlinetask)
20834 (org-inlinetask-in-task-p)))
20835 (inline-re (and inline-task-p
20836 (org-inlinetask-outline-regexp)))
20837 column)
20838 (if (and orgstruct-is-++ (eq pos (point)))
20839 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20840 (indent-according-to-mode))
20841 (beginning-of-line 1)
20842 (cond
20843 ;; Headings
20844 ((looking-at org-outline-regexp) (setq column 0))
20845 ;; Included files
20846 ((looking-at "#\\+include:") (setq column 0))
20847 ;; Footnote definition
20848 ((looking-at org-footnote-definition-re) (setq column 0))
20849 ;; Literal examples
20850 ((looking-at "[ \t]*:\\( \\|$\\)")
20851 (setq column (org-get-indentation))) ; do nothing
20852 ;; Lists
20853 ((ignore-errors (goto-char (org-in-item-p)))
20854 (setq column (if itemp
20855 (org-get-indentation)
20856 (org-list-item-body-column (point))))
20857 (goto-char pos))
20858 ;; Drawers
20859 ((and (looking-at "[ \t]*:END:")
20860 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20861 (save-excursion
20862 (goto-char (1- (match-beginning 1)))
20863 (setq column (current-column))))
20864 ;; Special blocks
20865 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20866 (save-excursion
20867 (re-search-backward
20868 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20869 (setq column (org-get-indentation (match-string 0))))
20870 ((and (not (looking-at "[ \t]*#\\+begin_"))
20871 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20872 (save-excursion
20873 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20874 (setq column
20875 (cond ((equal (downcase (match-string 1)) "src")
20876 ;; src blocks: let `org-edit-src-exit' handle them
20877 (org-get-indentation))
20878 ((equal (downcase (match-string 1)) "example")
20879 (max (org-get-indentation)
20880 (org-get-indentation (match-string 0))))
20882 (org-get-indentation (match-string 0))))))
20883 ;; This line has nothing special, look at the previous relevant
20884 ;; line to compute indentation
20886 (beginning-of-line 0)
20887 (while (and (not (bobp))
20888 (not (looking-at org-drawer-regexp))
20889 ;; When point started in an inline task, do not move
20890 ;; above task starting line.
20891 (not (and inline-task-p (looking-at inline-re)))
20892 ;; Skip drawers, blocks, empty lines, verbatim,
20893 ;; comments, tables, footnotes definitions, lists,
20894 ;; inline tasks.
20895 (or (and (looking-at "[ \t]*:END:")
20896 (re-search-backward org-drawer-regexp nil t))
20897 (and (looking-at "[ \t]*#\\+end_")
20898 (re-search-backward "[ \t]*#\\+begin_"nil t))
20899 (looking-at "[ \t]*[\n:#|]")
20900 (looking-at org-footnote-definition-re)
20901 (and (ignore-errors (goto-char (org-in-item-p)))
20902 (goto-char
20903 (org-list-get-top-point (org-list-struct))))
20904 (and (not inline-task-p)
20905 (featurep 'org-inlinetask)
20906 (org-inlinetask-in-task-p)
20907 (or (org-inlinetask-goto-beginning) t))))
20908 (beginning-of-line 0))
20909 (cond
20910 ;; There was an heading above.
20911 ((looking-at "\\*+[ \t]+")
20912 (if (not org-adapt-indentation)
20913 (setq column 0)
20914 (goto-char (match-end 0))
20915 (setq column (current-column))))
20916 ;; A drawer had started and is unfinished
20917 ((looking-at org-drawer-regexp)
20918 (goto-char (1- (match-beginning 1)))
20919 (setq column (current-column)))
20920 ;; Else, nothing noticeable found: get indentation and go on.
20921 (t (setq column (org-get-indentation))))))
20922 ;; Now apply indentation and move cursor accordingly
20923 (goto-char pos)
20924 (if (<= (current-column) (current-indentation))
20925 (org-indent-line-to column)
20926 (save-excursion (org-indent-line-to column)))
20927 ;; Special polishing for properties, see `org-property-format'
20928 (setq column (current-column))
20929 (beginning-of-line 1)
20930 (if (looking-at
20931 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20932 (replace-match (concat (match-string 1)
20933 (format org-property-format
20934 (match-string 2) (match-string 3)))
20935 t t))
20936 (org-move-to-column column))))
20938 (defun org-indent-drawer ()
20939 "Indent the drawer at point."
20940 (interactive)
20941 (let ((p (point))
20942 (e (and (save-excursion (re-search-forward ":END:" nil t))
20943 (match-end 0)))
20944 (folded
20945 (save-excursion
20946 (end-of-line)
20947 (when (overlays-at (point))
20948 (member 'invisible (overlay-properties
20949 (car (overlays-at (point)))))))))
20950 (when folded (org-cycle))
20951 (indent-for-tab-command)
20952 (while (and (move-beginning-of-line 2) (< (point) e))
20953 (indent-for-tab-command))
20954 (goto-char p)
20955 (when folded (org-cycle)))
20956 (message "Drawer at point indented"))
20958 (defun org-indent-block ()
20959 "Indent the block at point."
20960 (interactive)
20961 (let ((p (point))
20962 (case-fold-search t)
20963 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20964 (match-end 0)))
20965 (folded
20966 (save-excursion
20967 (end-of-line)
20968 (when (overlays-at (point))
20969 (member 'invisible (overlay-properties
20970 (car (overlays-at (point)))))))))
20971 (when folded (org-cycle))
20972 (indent-for-tab-command)
20973 (while (and (move-beginning-of-line 2) (< (point) e))
20974 (indent-for-tab-command))
20975 (goto-char p)
20976 (when folded (org-cycle)))
20977 (message "Block at point indented"))
20979 (defun org-indent-region (start end)
20980 "Indent region."
20981 (interactive "r")
20982 (save-excursion
20983 (let ((line-end (org-current-line end)))
20984 (goto-char start)
20985 (while (< (org-current-line) line-end)
20986 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20987 (t (call-interactively 'org-indent-line)))
20988 (move-beginning-of-line 2)))))
20991 ;;; Filling
20993 ;; We use our own fill-paragraph and auto-fill functions.
20995 ;; `org-fill-paragraph' relies on adaptive filling and context
20996 ;; checking. Appropriate `fill-prefix' is computed with
20997 ;; `org-adaptive-fill-function'.
20999 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21000 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21001 ;; `org-adaptive-fill-function' value. Internally,
21002 ;; `org-comment-line-break-function' breaks the line.
21004 ;; `org-setup-filling' installs filling and auto-filling related
21005 ;; variables during `org-mode' initialization.
21007 (defun org-setup-filling ()
21008 (interactive)
21009 ;; Prevent auto-fill from inserting unwanted new items.
21010 (when (boundp 'fill-nobreak-predicate)
21011 (org-set-local
21012 'fill-nobreak-predicate
21013 (org-uniquify
21014 (append fill-nobreak-predicate
21015 '(org-fill-paragraph-separate-nobreak-p
21016 org-fill-line-break-nobreak-p)))))
21017 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21018 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21019 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21020 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21022 (defvar org-element-paragraph-separate) ; org-element.el
21023 (defun org-fill-paragraph-separate-nobreak-p ()
21024 "Non-nil when a line break at point would insert a new item."
21025 (looking-at (substring org-element-paragraph-separate 1)))
21027 (defun org-fill-line-break-nobreak-p ()
21028 "Non-nil when a line break at point would create an Org line break."
21029 (save-excursion
21030 (skip-chars-backward "[ \t]")
21031 (skip-chars-backward "\\\\")
21032 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21034 (declare-function message-in-body-p "message" ())
21035 (defvar org-element--affiliated-re) ; From org-element.el
21036 (defun org-adaptive-fill-function ()
21037 "Compute a fill prefix for the current line.
21038 Return fill prefix, as a string, or nil if current line isn't
21039 meant to be filled."
21040 (org-with-wide-buffer
21041 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21042 ;; FIXME: This is really the job of orgstruct++-mode
21043 (let* ((p (line-beginning-position))
21044 (element (save-excursion (beginning-of-line)
21045 (org-element-at-point)))
21046 (type (org-element-type element))
21047 (post-affiliated
21048 (save-excursion
21049 (goto-char (org-element-property :begin element))
21050 (while (looking-at org-element--affiliated-re) (forward-line))
21051 (point))))
21052 (unless (< p post-affiliated)
21053 (case type
21054 (comment (looking-at "[ \t]*# ?") (match-string 0))
21055 (footnote-definition "")
21056 ((item plain-list)
21057 (make-string (org-list-item-body-column post-affiliated) ? ))
21058 (paragraph
21059 ;; Fill prefix is usually the same as the current line,
21060 ;; except if the paragraph is at the beginning of an item.
21061 (let ((parent (org-element-property :parent element)))
21062 (cond ((eq (org-element-type parent) 'item)
21063 (make-string (org-list-item-body-column
21064 (org-element-property :begin parent))
21065 ? ))
21066 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21067 (match-string 0))
21068 (t ""))))
21069 (comment-block
21070 ;; Only fill contents if P is within block boundaries.
21071 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21072 (forward-line)
21073 (point)))
21074 (cend (save-excursion
21075 (goto-char (org-element-property :end element))
21076 (skip-chars-backward " \r\t\n")
21077 (line-beginning-position))))
21078 (when (and (>= p cbeg) (< p cend))
21079 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21080 (match-string 0)
21081 ""))))))))))
21083 (declare-function message-goto-body "message" ())
21084 (defvar message-cite-prefix-regexp) ; From message.el
21085 (defvar org-element-all-objects) ; From org-element.el
21086 (defun org-fill-paragraph (&optional justify)
21087 "Fill element at point, when applicable.
21089 This function only applies to comment blocks, comments, example
21090 blocks and paragraphs. Also, as a special case, re-align table
21091 when point is at one.
21093 If JUSTIFY is non-nil (interactively, with prefix argument),
21094 justify as well. If `sentence-end-double-space' is non-nil, then
21095 period followed by one space does not end a sentence, so don't
21096 break a line there. The variable `fill-column' controls the
21097 width for filling.
21099 For convenience, when point is at a plain list, an item or
21100 a footnote definition, try to fill the first paragraph within."
21101 ;; Falls back on message-fill-paragraph when necessary
21102 (interactive)
21103 (if (and (derived-mode-p 'message-mode)
21104 (or (not (message-in-body-p))
21105 (save-excursion (move-beginning-of-line 1)
21106 (looking-at message-cite-prefix-regexp))))
21107 (let ((fill-paragraph-function
21108 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21109 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21110 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21111 (paragraph-separate
21112 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21113 (fill-paragraph nil))
21114 (save-excursion
21115 ;; Move to end of line in order to get the first paragraph
21116 ;; within a plain list or a footnote definition.
21117 (end-of-line)
21118 (let ((element (org-element-at-point)))
21119 ;; First check if point is in a blank line at the beginning of
21120 ;; the buffer. In that case, ignore filling.
21121 (if (< (point) (org-element-property :begin element)) t
21122 (case (org-element-type element)
21123 ;; Align Org tables, leave table.el tables as-is.
21124 (table-row (org-table-align) t)
21125 (table
21126 (when (eq (org-element-property :type element) 'org)
21127 (org-table-align))
21129 (paragraph
21130 ;; Paragraphs may contain `line-break' type objects.
21131 (let ((beg (max (point-min)
21132 (org-element-property :contents-begin element)))
21133 (end (min (point-max)
21134 (org-element-property :contents-end element))))
21135 ;; Do nothing if point is at an affiliated keyword.
21136 (if (< (point) beg) t
21137 (when (derived-mode-p 'message-mode)
21138 ;; In `message-mode', do not fill following
21139 ;; citation in current paragraph nor text before
21140 ;; message body.
21141 (let ((body-start (save-excursion (message-goto-body))))
21142 (when body-start (setq beg (max body-start beg))))
21143 (when (save-excursion
21144 (re-search-forward
21145 (concat "^" message-cite-prefix-regexp) end t))
21146 (setq end (match-beginning 0))))
21147 ;; Fill paragraph, taking line breaks into
21148 ;; consideration. For that, slice the paragraph
21149 ;; using line breaks as separators, and fill the
21150 ;; parts in reverse order to avoid messing with
21151 ;; markers.
21152 (save-excursion
21153 (goto-char end)
21154 (mapc
21155 (lambda (pos)
21156 (fill-region-as-paragraph pos (point) justify)
21157 (goto-char pos))
21158 ;; Find the list of ending positions for line
21159 ;; breaks in the current paragraph. Add paragraph
21160 ;; beginning to include first slice.
21161 (nreverse
21162 (cons
21164 (org-element-map
21165 (org-element--parse-objects
21166 beg end nil org-element-all-objects)
21167 'line-break
21168 (lambda (lb) (org-element-property :end lb)))))))
21169 t)))
21170 ;; Contents of `comment-block' type elements should be
21171 ;; filled as plain text, but only if point is within block
21172 ;; markers.
21173 (comment-block
21174 (let* ((case-fold-search t)
21175 (beg (save-excursion
21176 (goto-char (org-element-property :begin element))
21177 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21178 (forward-line)
21179 (point)))
21180 (end (save-excursion
21181 (goto-char (org-element-property :end element))
21182 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21183 (line-beginning-position))))
21184 (when (and (>= (point) beg) (< (point) end))
21185 (fill-region-as-paragraph
21186 (save-excursion
21187 (end-of-line)
21188 (re-search-backward "^[ \t]*$" beg 'move)
21189 (line-beginning-position))
21190 (save-excursion
21191 (beginning-of-line)
21192 (re-search-forward "^[ \t]*$" end 'move)
21193 (line-beginning-position))
21194 justify)))
21196 ;; Fill comments.
21197 (comment (fill-comment-paragraph justify))
21198 ;; Ignore every other element.
21199 (otherwise t)))))))
21201 (defun org-auto-fill-function ()
21202 "Auto-fill function."
21203 ;; Check if auto-filling is meaningful.
21204 (let ((fc (current-fill-column)))
21205 (when (and fc (> (current-column) fc))
21206 (let ((fill-prefix (org-adaptive-fill-function)))
21207 (when fill-prefix (do-auto-fill))))))
21209 (defun org-comment-line-break-function (&optional soft)
21210 "Break line at point and indent, continuing comment if within one.
21211 The inserted newline is marked hard if variable
21212 `use-hard-newlines' is true, unless optional argument SOFT is
21213 non-nil."
21214 (if soft (insert-and-inherit ?\n) (newline 1))
21215 (save-excursion (forward-char -1) (delete-horizontal-space))
21216 (delete-horizontal-space)
21217 (indent-to-left-margin)
21218 (insert-before-markers-and-inherit fill-prefix))
21221 ;;; Comments
21223 ;; Org comments syntax is quite complex. It requires the entire line
21224 ;; to be just a comment. Also, even with the right syntax at the
21225 ;; beginning of line, some some elements (i.e. verse-block or
21226 ;; example-block) don't accept comments. Usual Emacs comment commands
21227 ;; cannot cope with those requirements. Therefore, Org replaces them.
21229 ;; Org still relies on `comment-dwim', but cannot trust
21230 ;; `comment-only-p'. So, `comment-region-function' and
21231 ;; `uncomment-region-function' both point
21232 ;; to`org-comment-or-uncomment-region'. Eventually,
21233 ;; `org-insert-comment' takes care of insertion of comments at the
21234 ;; beginning of line.
21236 ;; `org-setup-comments-handling' install comments related variables
21237 ;; during `org-mode' initialization.
21239 (defun org-setup-comments-handling ()
21240 (interactive)
21241 (org-set-local 'comment-use-syntax nil)
21242 (org-set-local 'comment-start "# ")
21243 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21244 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21245 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21246 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21248 (defun org-insert-comment ()
21249 "Insert an empty comment above current line.
21250 If the line is empty, insert comment at its beginning."
21251 (beginning-of-line)
21252 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21253 (org-indent-line)
21254 (insert "# "))
21256 (defvar comment-empty-lines) ; From newcomment.el.
21257 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21258 "Comment or uncomment each non-blank line in the region.
21259 Uncomment each non-blank line between BEG and END if it only
21260 contains commented lines. Otherwise, comment them."
21261 (save-restriction
21262 ;; Restrict region
21263 (narrow-to-region (save-excursion (goto-char beg)
21264 (skip-chars-forward " \r\t\n" end)
21265 (line-beginning-position))
21266 (save-excursion (goto-char end)
21267 (skip-chars-backward " \r\t\n" beg)
21268 (line-end-position)))
21269 (let ((uncommentp
21270 ;; UNCOMMENTP is non-nil when every non blank line between
21271 ;; BEG and END is a comment.
21272 (save-excursion
21273 (goto-char (point-min))
21274 (while (and (not (eobp))
21275 (let ((element (org-element-at-point)))
21276 (and (eq (org-element-type element) 'comment)
21277 (goto-char (min (point-max)
21278 (org-element-property
21279 :end element)))))))
21280 (eobp))))
21281 (if uncommentp
21282 ;; Only blank lines and comments in region: uncomment it.
21283 (save-excursion
21284 (goto-char (point-min))
21285 (while (not (eobp))
21286 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21287 (replace-match "" nil nil nil 1))
21288 (forward-line)))
21289 ;; Comment each line in region.
21290 (let ((min-indent (point-max)))
21291 ;; First find the minimum indentation across all lines.
21292 (save-excursion
21293 (goto-char (point-min))
21294 (while (and (not (eobp)) (not (zerop min-indent)))
21295 (unless (looking-at "[ \t]*$")
21296 (setq min-indent (min min-indent (current-indentation))))
21297 (forward-line)))
21298 ;; Then loop over all lines.
21299 (save-excursion
21300 (goto-char (point-min))
21301 (while (not (eobp))
21302 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21303 (org-move-to-column min-indent t)
21304 (insert comment-start))
21305 (forward-line))))))))
21308 ;;; Other stuff.
21310 (defun org-toggle-fixed-width-section (arg)
21311 "Toggle the fixed-width export.
21312 If there is no active region, the QUOTE keyword at the current headline is
21313 inserted or removed. When present, it causes the text between this headline
21314 and the next to be exported as fixed-width text, and unmodified.
21315 If there is an active region, this command adds or removes a colon as the
21316 first character of this line. If the first character of a line is a colon,
21317 this line is also exported in fixed-width font."
21318 (interactive "P")
21319 (let* ((cc 0)
21320 (regionp (org-region-active-p))
21321 (beg (if regionp (region-beginning) (point)))
21322 (end (if regionp (region-end)))
21323 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21324 (case-fold-search nil)
21325 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21326 off)
21327 (if regionp
21328 (save-excursion
21329 (goto-char beg)
21330 (setq cc (current-column))
21331 (beginning-of-line 1)
21332 (setq off (looking-at re))
21333 (while (> nlines 0)
21334 (setq nlines (1- nlines))
21335 (beginning-of-line 1)
21336 (cond
21337 (arg
21338 (org-move-to-column cc t)
21339 (insert ": \n")
21340 (forward-line -1))
21341 ((and off (looking-at re))
21342 (replace-match "" t t nil 1))
21343 ((not off) (org-move-to-column cc t) (insert ": ")))
21344 (forward-line 1)))
21345 (save-excursion
21346 (org-back-to-heading)
21347 (cond
21348 ((looking-at (format org-heading-keyword-regexp-format
21349 org-quote-string))
21350 (goto-char (match-end 1))
21351 (looking-at (concat " +" org-quote-string))
21352 (replace-match "" t t)
21353 (when (eolp) (insert " ")))
21354 ((looking-at org-outline-regexp)
21355 (goto-char (match-end 0))
21356 (insert org-quote-string " ")))))))
21358 (defun org-reftex-citation ()
21359 "Use reftex-citation to insert a citation into the buffer.
21360 This looks for a line like
21362 #+BIBLIOGRAPHY: foo plain option:-d
21364 and derives from it that foo.bib is the bibliography file relevant
21365 for this document. It then installs the necessary environment for RefTeX
21366 to work in this buffer and calls `reftex-citation' to insert a citation
21367 into the buffer.
21369 Export of such citations to both LaTeX and HTML is handled by the contributed
21370 package org-exp-bibtex by Taru Karttunen."
21371 (interactive)
21372 (let ((reftex-docstruct-symbol 'rds)
21373 (reftex-cite-format "\\cite{%l}")
21374 rds bib)
21375 (save-excursion
21376 (save-restriction
21377 (widen)
21378 (let ((case-fold-search t)
21379 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21380 (if (not (save-excursion
21381 (or (re-search-forward re nil t)
21382 (re-search-backward re nil t))))
21383 (error "No bibliography defined in file")
21384 (setq bib (concat (match-string 1) ".bib")
21385 rds (list (list 'bib bib)))))))
21386 (call-interactively 'reftex-citation)))
21388 ;;;; Functions extending outline functionality
21390 (defun org-beginning-of-line (&optional arg)
21391 "Go to the beginning of the current line. If that is invisible, continue
21392 to a visible line beginning. This makes the function of C-a more intuitive.
21393 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21394 first attempt, and only move to after the tags when the cursor is already
21395 beyond the end of the headline."
21396 (interactive "P")
21397 (let ((pos (point))
21398 (special (if (consp org-special-ctrl-a/e)
21399 (car org-special-ctrl-a/e)
21400 org-special-ctrl-a/e))
21401 refpos)
21402 (if (org-bound-and-true-p line-move-visual)
21403 (beginning-of-visual-line 1)
21404 (beginning-of-line 1))
21405 (if (and arg (fboundp 'move-beginning-of-line))
21406 (call-interactively 'move-beginning-of-line)
21407 (if (bobp)
21409 (backward-char 1)
21410 (if (org-truely-invisible-p)
21411 (while (and (not (bobp)) (org-truely-invisible-p))
21412 (backward-char 1)
21413 (beginning-of-line 1))
21414 (forward-char 1))))
21415 (when special
21416 (cond
21417 ((and (looking-at org-complex-heading-regexp)
21418 (= (char-after (match-end 1)) ?\ ))
21419 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21420 (point-at-eol)))
21421 (goto-char
21422 (if (eq special t)
21423 (cond ((> pos refpos) refpos)
21424 ((= pos (point)) refpos)
21425 (t (point)))
21426 (cond ((> pos (point)) (point))
21427 ((not (eq last-command this-command)) (point))
21428 (t refpos)))))
21429 ((org-at-item-p)
21430 ;; Being at an item and not looking at an the item means point
21431 ;; was previously moved to beginning of a visual line, which
21432 ;; doesn't contain the item. Therefore, do nothing special,
21433 ;; just stay here.
21434 (when (looking-at org-list-full-item-re)
21435 ;; Set special position at first white space character after
21436 ;; bullet, and check-box, if any.
21437 (let ((after-bullet
21438 (let ((box (match-end 3)))
21439 (if (not box) (match-end 1)
21440 (let ((after (char-after box)))
21441 (if (and after (= after ? )) (1+ box) box))))))
21442 ;; Special case: Move point to special position when
21443 ;; currently after it or at beginning of line.
21444 (if (eq special t)
21445 (when (or (> pos after-bullet) (= (point) pos))
21446 (goto-char after-bullet))
21447 ;; Reversed case: Move point to special position when
21448 ;; point was already at beginning of line and command is
21449 ;; repeated.
21450 (when (and (= (point) pos) (eq last-command this-command))
21451 (goto-char after-bullet))))))))
21452 (org-no-warnings
21453 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21455 (defun org-end-of-line (&optional arg)
21456 "Go to the end of the line.
21457 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21458 first attempt, and only move to after the tags when the cursor is already
21459 beyond the end of the headline."
21460 (interactive "P")
21461 (let ((special (if (consp org-special-ctrl-a/e)
21462 (cdr org-special-ctrl-a/e)
21463 org-special-ctrl-a/e)))
21464 (cond
21465 ((or (not special) arg
21466 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21467 (call-interactively
21468 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21469 ((fboundp 'move-end-of-line) 'move-end-of-line)
21470 (t 'end-of-line))))
21471 ((org-at-heading-p)
21472 (let ((pos (point)))
21473 (beginning-of-line 1)
21474 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21475 (if (eq special t)
21476 (if (or (< pos (match-beginning 1))
21477 (= pos (match-end 0)))
21478 (goto-char (match-beginning 1))
21479 (goto-char (match-end 0)))
21480 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21481 (goto-char (match-end 0))
21482 (goto-char (match-beginning 1))))
21483 (call-interactively (if (fboundp 'move-end-of-line)
21484 'move-end-of-line
21485 'end-of-line)))))
21486 ((org-at-drawer-p)
21487 (move-end-of-line 1)
21488 (when (overlays-at (1- (point))) (backward-char 1)))
21489 ;; At an item: Move before any hidden text.
21490 (t (call-interactively
21491 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21492 ((fboundp 'move-end-of-line) 'move-end-of-line)
21493 (t 'end-of-line)))))
21494 (org-no-warnings
21495 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21497 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21498 (define-key org-mode-map "\C-e" 'org-end-of-line)
21500 (defun org-backward-sentence (&optional arg)
21501 "Go to beginning of sentence, or beginning of table field.
21502 This will call `backward-sentence' or `org-table-beginning-of-field',
21503 depending on context."
21504 (interactive "P")
21505 (cond
21506 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21507 (t (call-interactively 'backward-sentence))))
21509 (defun org-forward-sentence (&optional arg)
21510 "Go to end of sentence, or end of table field.
21511 This will call `forward-sentence' or `org-table-end-of-field',
21512 depending on context."
21513 (interactive "P")
21514 (cond
21515 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21516 (t (call-interactively 'forward-sentence))))
21518 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21519 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21521 (defun org-kill-line (&optional arg)
21522 "Kill line, to tags or end of line."
21523 (interactive "P")
21524 (cond
21525 ((or (not org-special-ctrl-k)
21526 (bolp)
21527 (not (org-at-heading-p)))
21528 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21529 org-ctrl-k-protect-subtree)
21530 (if (or (eq org-ctrl-k-protect-subtree 'error)
21531 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21532 (error "C-k aborted - would kill hidden subtree")))
21533 (call-interactively
21534 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21535 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21536 (kill-region (point) (match-beginning 1))
21537 (org-set-tags nil t))
21538 (t (kill-region (point) (point-at-eol)))))
21540 (define-key org-mode-map "\C-k" 'org-kill-line)
21542 (defun org-yank (&optional arg)
21543 "Yank. If the kill is a subtree, treat it specially.
21544 This command will look at the current kill and check if is a single
21545 subtree, or a series of subtrees[1]. If it passes the test, and if the
21546 cursor is at the beginning of a line or after the stars of a currently
21547 empty headline, then the yank is handled specially. How exactly depends
21548 on the value of the following variables, both set by default.
21550 org-yank-folded-subtrees
21551 When set, the subtree(s) will be folded after insertion, but only
21552 if doing so would now swallow text after the yanked text.
21554 org-yank-adjusted-subtrees
21555 When set, the subtree will be promoted or demoted in order to
21556 fit into the local outline tree structure, which means that the level
21557 will be adjusted so that it becomes the smaller one of the two
21558 *visible* surrounding headings.
21560 Any prefix to this command will cause `yank' to be called directly with
21561 no special treatment. In particular, a simple \\[universal-argument] prefix \
21562 will just
21563 plainly yank the text as it is.
21565 \[1] The test checks if the first non-white line is a heading
21566 and if there are no other headings with fewer stars."
21567 (interactive "P")
21568 (org-yank-generic 'yank arg))
21570 (defun org-yank-generic (command arg)
21571 "Perform some yank-like command.
21573 This function implements the behavior described in the `org-yank'
21574 documentation. However, it has been generalized to work for any
21575 interactive command with similar behavior."
21577 ;; pretend to be command COMMAND
21578 (setq this-command command)
21580 (if arg
21581 (call-interactively command)
21583 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21584 (and (org-kill-is-subtree-p)
21585 (or (bolp)
21586 (and (looking-at "[ \t]*$")
21587 (string-match
21588 "\\`\\*+\\'"
21589 (buffer-substring (point-at-bol) (point)))))))
21590 swallowp)
21591 (cond
21592 ((and subtreep org-yank-folded-subtrees)
21593 (let ((beg (point))
21594 end)
21595 (if (and subtreep org-yank-adjusted-subtrees)
21596 (org-paste-subtree nil nil 'for-yank)
21597 (call-interactively command))
21599 (setq end (point))
21600 (goto-char beg)
21601 (when (and (bolp) subtreep
21602 (not (setq swallowp
21603 (org-yank-folding-would-swallow-text beg end))))
21604 (org-with-limited-levels
21605 (or (looking-at org-outline-regexp)
21606 (re-search-forward org-outline-regexp-bol end t))
21607 (while (and (< (point) end) (looking-at org-outline-regexp))
21608 (hide-subtree)
21609 (org-cycle-show-empty-lines 'folded)
21610 (condition-case nil
21611 (outline-forward-same-level 1)
21612 (error (goto-char end))))))
21613 (when swallowp
21614 (message
21615 "Inserted text not folded because that would swallow text"))
21617 (goto-char end)
21618 (skip-chars-forward " \t\n\r")
21619 (beginning-of-line 1)
21620 (push-mark beg 'nomsg)))
21621 ((and subtreep org-yank-adjusted-subtrees)
21622 (let ((beg (point-at-bol)))
21623 (org-paste-subtree nil nil 'for-yank)
21624 (push-mark beg 'nomsg)))
21626 (call-interactively command))))))
21628 (defun org-yank-folding-would-swallow-text (beg end)
21629 "Would hide-subtree at BEG swallow any text after END?"
21630 (let (level)
21631 (org-with-limited-levels
21632 (save-excursion
21633 (goto-char beg)
21634 (when (or (looking-at org-outline-regexp)
21635 (re-search-forward org-outline-regexp-bol end t))
21636 (setq level (org-outline-level)))
21637 (goto-char end)
21638 (skip-chars-forward " \t\r\n\v\f")
21639 (if (or (eobp)
21640 (and (bolp) (looking-at org-outline-regexp)
21641 (<= (org-outline-level) level)))
21642 nil ; Nothing would be swallowed
21643 t))))) ; something would swallow
21645 (define-key org-mode-map "\C-y" 'org-yank)
21647 (defun org-truely-invisible-p ()
21648 "Check if point is at a character currently not visible.
21649 This version does not only check the character property, but also
21650 `visible-mode'."
21651 ;; Early versions of noutline don't have `outline-invisible-p'.
21652 (if (org-bound-and-true-p visible-mode)
21654 (outline-invisible-p)))
21656 (defun org-invisible-p2 ()
21657 "Check if point is at a character currently not visible."
21658 (save-excursion
21659 (if (and (eolp) (not (bobp))) (backward-char 1))
21660 ;; Early versions of noutline don't have `outline-invisible-p'.
21661 (outline-invisible-p)))
21663 (defun org-back-to-heading (&optional invisible-ok)
21664 "Call `outline-back-to-heading', but provide a better error message."
21665 (condition-case nil
21666 (outline-back-to-heading invisible-ok)
21667 (error (error "Before first headline at position %d in buffer %s"
21668 (point) (current-buffer)))))
21670 (defun org-before-first-heading-p ()
21671 "Before first heading?"
21672 (save-excursion
21673 (end-of-line)
21674 (null (re-search-backward org-outline-regexp-bol nil t))))
21676 (defun org-at-heading-p (&optional ignored)
21677 (outline-on-heading-p t))
21678 ;; Compatibility alias with Org versions < 7.8.03
21679 (defalias 'org-on-heading-p 'org-at-heading-p)
21681 (defun org-at-comment-p nil
21682 "Is cursor in a line starting with a # character?"
21683 (save-excursion
21684 (beginning-of-line)
21685 (looking-at "^#")))
21687 (defun org-at-drawer-p nil
21688 "Is cursor at a drawer keyword?"
21689 (save-excursion
21690 (move-beginning-of-line 1)
21691 (looking-at org-drawer-regexp)))
21693 (defun org-at-block-p nil
21694 "Is cursor at a block keyword?"
21695 (save-excursion
21696 (move-beginning-of-line 1)
21697 (looking-at org-block-regexp)))
21699 (defun org-point-at-end-of-empty-headline ()
21700 "If point is at the end of an empty headline, return t, else nil.
21701 If the heading only contains a TODO keyword, it is still still considered
21702 empty."
21703 (and (looking-at "[ \t]*$")
21704 (when org-todo-line-regexp
21705 (save-excursion
21706 (beginning-of-line 1)
21707 (let ((case-fold-search nil))
21708 (looking-at org-todo-line-regexp)
21709 (string= (match-string 3) ""))))))
21711 (defun org-at-heading-or-item-p ()
21712 (or (org-at-heading-p) (org-at-item-p)))
21714 (defun org-at-target-p ()
21715 (or (org-in-regexp org-radio-target-regexp)
21716 (org-in-regexp org-target-regexp)))
21717 ;; Compatibility alias with Org versions < 7.8.03
21718 (defalias 'org-on-target-p 'org-at-target-p)
21720 (defun org-up-heading-all (arg)
21721 "Move to the heading line of which the present line is a subheading.
21722 This function considers both visible and invisible heading lines.
21723 With argument, move up ARG levels."
21724 (if (fboundp 'outline-up-heading-all)
21725 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21726 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21728 (defun org-up-heading-safe ()
21729 "Move to the heading line of which the present line is a subheading.
21730 This version will not throw an error. It will return the level of the
21731 headline found, or nil if no higher level is found.
21733 Also, this function will be a lot faster than `outline-up-heading',
21734 because it relies on stars being the outline starters. This can really
21735 make a significant difference in outlines with very many siblings."
21736 (let (start-level re)
21737 (org-back-to-heading t)
21738 (setq start-level (funcall outline-level))
21739 (if (equal start-level 1)
21741 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21742 (if (re-search-backward re nil t)
21743 (funcall outline-level)))))
21745 (defun org-first-sibling-p ()
21746 "Is this heading the first child of its parents?"
21747 (interactive)
21748 (let ((re org-outline-regexp-bol)
21749 level l)
21750 (unless (org-at-heading-p t)
21751 (error "Not at a heading"))
21752 (setq level (funcall outline-level))
21753 (save-excursion
21754 (if (not (re-search-backward re nil t))
21756 (setq l (funcall outline-level))
21757 (< l level)))))
21759 (defun org-goto-sibling (&optional previous)
21760 "Goto the next sibling, even if it is invisible.
21761 When PREVIOUS is set, go to the previous sibling instead. Returns t
21762 when a sibling was found. When none is found, return nil and don't
21763 move point."
21764 (let ((fun (if previous 're-search-backward 're-search-forward))
21765 (pos (point))
21766 (re org-outline-regexp-bol)
21767 level l)
21768 (when (condition-case nil (org-back-to-heading t) (error nil))
21769 (setq level (funcall outline-level))
21770 (catch 'exit
21771 (or previous (forward-char 1))
21772 (while (funcall fun re nil t)
21773 (setq l (funcall outline-level))
21774 (when (< l level) (goto-char pos) (throw 'exit nil))
21775 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21776 (goto-char pos)
21777 nil))))
21779 (defun org-show-siblings ()
21780 "Show all siblings of the current headline."
21781 (save-excursion
21782 (while (org-goto-sibling) (org-flag-heading nil)))
21783 (save-excursion
21784 (while (org-goto-sibling 'previous)
21785 (org-flag-heading nil))))
21787 (defun org-goto-first-child ()
21788 "Goto the first child, even if it is invisible.
21789 Return t when a child was found. Otherwise don't move point and
21790 return nil."
21791 (let (level (pos (point)) (re org-outline-regexp-bol))
21792 (when (condition-case nil (org-back-to-heading t) (error nil))
21793 (setq level (outline-level))
21794 (forward-char 1)
21795 (if (and (re-search-forward re nil t) (> (outline-level) level))
21796 (progn (goto-char (match-beginning 0)) t)
21797 (goto-char pos) nil))))
21799 (defun org-show-hidden-entry ()
21800 "Show an entry where even the heading is hidden."
21801 (save-excursion
21802 (org-show-entry)))
21804 (defun org-flag-heading (flag &optional entry)
21805 "Flag the current heading. FLAG non-nil means make invisible.
21806 When ENTRY is non-nil, show the entire entry."
21807 (save-excursion
21808 (org-back-to-heading t)
21809 ;; Check if we should show the entire entry
21810 (if entry
21811 (progn
21812 (org-show-entry)
21813 (save-excursion
21814 (and (outline-next-heading)
21815 (org-flag-heading nil))))
21816 (outline-flag-region (max (point-min) (1- (point)))
21817 (save-excursion (outline-end-of-heading) (point))
21818 flag))))
21820 (defun org-get-next-sibling ()
21821 "Move to next heading of the same level, and return point.
21822 If there is no such heading, return nil.
21823 This is like outline-next-sibling, but invisible headings are ok."
21824 (let ((level (funcall outline-level)))
21825 (outline-next-heading)
21826 (while (and (not (eobp)) (> (funcall outline-level) level))
21827 (outline-next-heading))
21828 (if (or (eobp) (< (funcall outline-level) level))
21830 (point))))
21832 (defun org-get-last-sibling ()
21833 "Move to previous heading of the same level, and return point.
21834 If there is no such heading, return nil."
21835 (let ((opoint (point))
21836 (level (funcall outline-level)))
21837 (outline-previous-heading)
21838 (when (and (/= (point) opoint) (outline-on-heading-p t))
21839 (while (and (> (funcall outline-level) level)
21840 (not (bobp)))
21841 (outline-previous-heading))
21842 (if (< (funcall outline-level) level)
21844 (point)))))
21846 (defun org-end-of-subtree (&optional invisible-OK to-heading)
21847 ;; This contains an exact copy of the original function, but it uses
21848 ;; `org-back-to-heading', to make it work also in invisible
21849 ;; trees. And is uses an invisible-OK argument.
21850 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21851 ;; Furthermore, when used inside Org, finding the end of a large subtree
21852 ;; with many children and grandchildren etc, this can be much faster
21853 ;; than the outline version.
21854 (org-back-to-heading invisible-OK)
21855 (let ((first t)
21856 (level (funcall outline-level)))
21857 (if (and (derived-mode-p 'org-mode) (< level 1000))
21858 ;; A true heading (not a plain list item), in Org-mode
21859 ;; This means we can easily find the end by looking
21860 ;; only for the right number of stars. Using a regexp to do
21861 ;; this is so much faster than using a Lisp loop.
21862 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21863 (forward-char 1)
21864 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21865 ;; something else, do it the slow way
21866 (while (and (not (eobp))
21867 (or first (> (funcall outline-level) level)))
21868 (setq first nil)
21869 (outline-next-heading)))
21870 (unless to-heading
21871 (if (memq (preceding-char) '(?\n ?\^M))
21872 (progn
21873 ;; Go to end of line before heading
21874 (forward-char -1)
21875 (if (memq (preceding-char) '(?\n ?\^M))
21876 ;; leave blank line before heading
21877 (forward-char -1))))))
21878 (point))
21880 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21881 "Use Org version in org-mode, for dramatic speed-up."
21882 (if (derived-mode-p 'org-mode)
21883 (progn
21884 (org-end-of-subtree nil t)
21885 (unless (eobp) (backward-char 1)))
21886 ad-do-it))
21888 (defun org-end-of-meta-data-and-drawers ()
21889 "Jump to the first text after meta data and drawers in the current entry.
21890 This will move over empty lines, lines with planning time stamps,
21891 clocking lines, and drawers."
21892 (org-back-to-heading t)
21893 (let ((end (save-excursion (outline-next-heading) (point)))
21894 (re (concat "\\(" org-drawer-regexp "\\)"
21895 "\\|" "[ \t]*" org-keyword-time-regexp)))
21896 (forward-line 1)
21897 (while (re-search-forward re end t)
21898 (if (not (match-end 1))
21899 ;; empty or planning line
21900 (forward-line 1)
21901 ;; a drawer, find the end
21902 (re-search-forward "^[ \t]*:END:" end 'move)
21903 (forward-line 1)))
21904 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21905 (point)))
21907 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21908 "Move forward to the arg'th subheading at same level as this one.
21909 Stop at the first and last subheadings of a superior heading.
21910 Normally this only looks at visible headings, but when INVISIBLE-OK is
21911 non-nil it will also look at invisible ones."
21912 (interactive "p")
21913 (org-back-to-heading invisible-ok)
21914 (org-at-heading-p)
21915 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21916 (re (format "^\\*\\{1,%d\\} " level))
21918 (forward-char 1)
21919 (while (> arg 0)
21920 (while (and (re-search-forward re nil 'move)
21921 (setq l (- (match-end 0) (match-beginning 0) 1))
21922 (= l level)
21923 (not invisible-ok)
21924 (progn (backward-char 1) (outline-invisible-p)))
21925 (if (< l level) (setq arg 1)))
21926 (setq arg (1- arg)))
21927 (beginning-of-line 1)))
21929 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21930 "Move backward to the arg'th subheading at same level as this one.
21931 Stop at the first and last subheadings of a superior heading."
21932 (interactive "p")
21933 (org-back-to-heading)
21934 (org-at-heading-p)
21935 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21936 (re (format "^\\*\\{1,%d\\} " level))
21938 (while (> arg 0)
21939 (while (and (re-search-backward re nil 'move)
21940 (setq l (- (match-end 0) (match-beginning 0) 1))
21941 (= l level)
21942 (not invisible-ok)
21943 (outline-invisible-p))
21944 (if (< l level) (setq arg 1)))
21945 (setq arg (1- arg)))))
21947 ;;;###autoload
21948 (defun org-forward-element ()
21949 "Move forward by one element.
21950 Move to the next element at the same level, when possible."
21951 (interactive)
21952 (cond ((eobp) (error "Cannot move further down"))
21953 ((org-with-limited-levels (org-at-heading-p))
21954 (let ((origin (point)))
21955 (org-forward-heading-same-level 1)
21956 (unless (org-with-limited-levels (org-at-heading-p))
21957 (goto-char origin)
21958 (error "Cannot move further down"))))
21960 (let* ((elem (org-element-at-point))
21961 (end (org-element-property :end elem))
21962 (parent (org-element-property :parent elem)))
21963 (if (and parent (= (org-element-property :contents-end parent) end))
21964 (goto-char (org-element-property :end parent))
21965 (goto-char end))))))
21967 ;;;###autoload
21968 (defun org-backward-element ()
21969 "Move backward by one element.
21970 Move to the previous element at the same level, when possible."
21971 (interactive)
21972 (cond ((bobp) (error "Cannot move further up"))
21973 ((org-with-limited-levels (org-at-heading-p))
21974 ;; At an headline, move to the previous one, if any, or stay
21975 ;; here.
21976 (let ((origin (point)))
21977 (org-backward-heading-same-level 1)
21978 (unless (org-with-limited-levels (org-at-heading-p))
21979 (goto-char origin)
21980 (error "Cannot move further up"))))
21982 (let* ((trail (org-element-at-point 'keep-trail))
21983 (elem (car trail))
21984 (prev-elem (nth 1 trail))
21985 (beg (org-element-property :begin elem)))
21986 (cond
21987 ;; Move to beginning of current element if point isn't
21988 ;; there already.
21989 ((/= (point) beg) (goto-char beg))
21990 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21991 ((org-before-first-heading-p) (goto-char (point-min)))
21992 (t (org-back-to-heading)))))))
21994 ;;;###autoload
21995 (defun org-up-element ()
21996 "Move to upper element."
21997 (interactive)
21998 (if (org-with-limited-levels (org-at-heading-p))
21999 (unless (org-up-heading-safe) (error "No surrounding element"))
22000 (let* ((elem (org-element-at-point))
22001 (parent (org-element-property :parent elem)))
22002 (if parent (goto-char (org-element-property :begin parent))
22003 (if (org-with-limited-levels (org-before-first-heading-p))
22004 (error "No surrounding element")
22005 (org-with-limited-levels (org-back-to-heading)))))))
22007 ;;;###autoload
22008 (defvar org-element-greater-elements)
22009 (defun org-down-element ()
22010 "Move to inner element."
22011 (interactive)
22012 (let ((element (org-element-at-point)))
22013 (cond
22014 ((memq (org-element-type element) '(plain-list table))
22015 (goto-char (org-element-property :contents-begin element))
22016 (forward-char))
22017 ((memq (org-element-type element) org-element-greater-elements)
22018 ;; If contents are hidden, first disclose them.
22019 (when (org-element-property :hiddenp element) (org-cycle))
22020 (goto-char (or (org-element-property :contents-begin element)
22021 (error "No content for this element"))))
22022 (t (error "No inner element")))))
22024 ;;;###autoload
22025 (defun org-drag-element-backward ()
22026 "Move backward element at point."
22027 (interactive)
22028 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22029 (let* ((trail (org-element-at-point 'keep-trail))
22030 (elem (car trail))
22031 (prev-elem (nth 1 trail)))
22032 ;; Error out if no previous element or previous element is
22033 ;; a parent of the current one.
22034 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22035 (error "Cannot drag element backward")
22036 (let ((pos (point)))
22037 (org-element-swap-A-B prev-elem elem)
22038 (goto-char (+ (org-element-property :begin prev-elem)
22039 (- pos (org-element-property :begin elem)))))))))
22041 ;;;###autoload
22042 (defun org-drag-element-forward ()
22043 "Move forward element at point."
22044 (interactive)
22045 (let* ((pos (point))
22046 (elem (org-element-at-point)))
22047 (when (= (point-max) (org-element-property :end elem))
22048 (error "Cannot drag element forward"))
22049 (goto-char (org-element-property :end elem))
22050 (let ((next-elem (org-element-at-point)))
22051 (when (or (org-element-nested-p elem next-elem)
22052 (and (eq (org-element-type next-elem) 'headline)
22053 (not (eq (org-element-type elem) 'headline))))
22054 (goto-char pos)
22055 (error "Cannot drag element forward"))
22056 ;; Compute new position of point: it's shifted by NEXT-ELEM
22057 ;; body's length (without final blanks) and by the length of
22058 ;; blanks between ELEM and NEXT-ELEM.
22059 (let ((size-next (- (save-excursion
22060 (goto-char (org-element-property :end next-elem))
22061 (skip-chars-backward " \r\t\n")
22062 (forward-line)
22063 ;; Small correction if buffer doesn't end
22064 ;; with a newline character.
22065 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22066 (org-element-property :begin next-elem)))
22067 (size-blank (- (org-element-property :end elem)
22068 (save-excursion
22069 (goto-char (org-element-property :end elem))
22070 (skip-chars-backward " \r\t\n")
22071 (forward-line)
22072 (point)))))
22073 (org-element-swap-A-B elem next-elem)
22074 (goto-char (+ pos size-next size-blank))))))
22076 ;;;###autoload
22077 (defun org-mark-element ()
22078 "Put point at beginning of this element, mark at end.
22080 Interactively, if this command is repeated or (in Transient Mark
22081 mode) if the mark is active, it marks the next element after the
22082 ones already marked."
22083 (interactive)
22084 (let (deactivate-mark)
22085 (if (and (org-called-interactively-p 'any)
22086 (or (and (eq last-command this-command) (mark t))
22087 (and transient-mark-mode mark-active)))
22088 (set-mark
22089 (save-excursion
22090 (goto-char (mark))
22091 (goto-char (org-element-property :end (org-element-at-point)))))
22092 (let ((element (org-element-at-point)))
22093 (end-of-line)
22094 (push-mark (org-element-property :end element) t t)
22095 (goto-char (org-element-property :begin element))))))
22097 ;;;###autoload
22098 (defun org-narrow-to-element ()
22099 "Narrow buffer to current element."
22100 (interactive)
22101 (let ((elem (org-element-at-point)))
22102 (cond
22103 ((eq (car elem) 'headline)
22104 (narrow-to-region
22105 (org-element-property :begin elem)
22106 (org-element-property :end elem)))
22107 ((memq (car elem) org-element-greater-elements)
22108 (narrow-to-region
22109 (org-element-property :contents-begin elem)
22110 (org-element-property :contents-end elem)))
22112 (narrow-to-region
22113 (org-element-property :begin elem)
22114 (org-element-property :end elem))))))
22116 ;;;###autoload
22117 (defun org-transpose-element ()
22118 "Transpose current and previous elements, keeping blank lines between.
22119 Point is moved after both elements."
22120 (interactive)
22121 (org-skip-whitespace)
22122 (let ((end (org-element-property :end (org-element-at-point))))
22123 (org-drag-element-backward)
22124 (goto-char end)))
22126 ;;;###autoload
22127 (defun org-unindent-buffer ()
22128 "Un-indent the visible part of the buffer.
22129 Relative indentation (between items, inside blocks, etc.) isn't
22130 modified."
22131 (interactive)
22132 (unless (eq major-mode 'org-mode)
22133 (error "Cannot un-indent a buffer not in Org mode"))
22134 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22135 unindent-tree ; For byte-compiler.
22136 (unindent-tree
22137 (function
22138 (lambda (contents)
22139 (mapc
22140 (lambda (element)
22141 (if (memq (org-element-type element) '(headline section))
22142 (funcall unindent-tree (org-element-contents element))
22143 (save-excursion
22144 (save-restriction
22145 (narrow-to-region
22146 (org-element-property :begin element)
22147 (org-element-property :end element))
22148 (org-do-remove-indentation)))))
22149 (reverse contents))))))
22150 (funcall unindent-tree (org-element-contents parse-tree))))
22152 (defun org-show-subtree ()
22153 "Show everything after this heading at deeper levels."
22154 (interactive)
22155 (outline-flag-region
22156 (point)
22157 (save-excursion
22158 (org-end-of-subtree t t))
22159 nil))
22161 (defun org-show-entry ()
22162 "Show the body directly following this heading.
22163 Show the heading too, if it is currently invisible."
22164 (interactive)
22165 (save-excursion
22166 (condition-case nil
22167 (progn
22168 (org-back-to-heading t)
22169 (outline-flag-region
22170 (max (point-min) (1- (point)))
22171 (save-excursion
22172 (if (re-search-forward
22173 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22174 (match-beginning 1)
22175 (point-max)))
22176 nil)
22177 (org-cycle-hide-drawers 'children))
22178 (error nil))))
22180 (defun org-make-options-regexp (kwds &optional extra)
22181 "Make a regular expression for keyword lines."
22182 (concat
22183 "^#\\+\\("
22184 (mapconcat 'regexp-quote kwds "\\|")
22185 (if extra (concat "\\|" extra))
22186 "\\):[ \t]*\\(.*\\)"))
22188 ;; Make isearch reveal the necessary context
22189 (defun org-isearch-end ()
22190 "Reveal context after isearch exits."
22191 (when isearch-success ; only if search was successful
22192 (if (featurep 'xemacs)
22193 ;; Under XEmacs, the hook is run in the correct place,
22194 ;; we directly show the context.
22195 (org-show-context 'isearch)
22196 ;; In Emacs the hook runs *before* restoring the overlays.
22197 ;; So we have to use a one-time post-command-hook to do this.
22198 ;; (Emacs 22 has a special variable, see function `org-mode')
22199 (unless (and (boundp 'isearch-mode-end-hook-quit)
22200 isearch-mode-end-hook-quit)
22201 ;; Only when the isearch was not quitted.
22202 (org-add-hook 'post-command-hook 'org-isearch-post-command
22203 'append 'local)))))
22205 (defun org-isearch-post-command ()
22206 "Remove self from hook, and show context."
22207 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22208 (org-show-context 'isearch))
22211 ;;;; Integration with and fixes for other packages
22213 ;;; Imenu support
22215 (defvar org-imenu-markers nil
22216 "All markers currently used by Imenu.")
22217 (make-variable-buffer-local 'org-imenu-markers)
22219 (defun org-imenu-new-marker (&optional pos)
22220 "Return a new marker for use by Imenu, and remember the marker."
22221 (let ((m (make-marker)))
22222 (move-marker m (or pos (point)))
22223 (push m org-imenu-markers)
22226 (defun org-imenu-get-tree ()
22227 "Produce the index for Imenu."
22228 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22229 (setq org-imenu-markers nil)
22230 (let* ((n org-imenu-depth)
22231 (re (concat "^" (org-get-limited-outline-regexp)))
22232 (subs (make-vector (1+ n) nil))
22233 (last-level 0)
22234 m level head)
22235 (save-excursion
22236 (save-restriction
22237 (widen)
22238 (goto-char (point-max))
22239 (while (re-search-backward re nil t)
22240 (setq level (org-reduced-level (funcall outline-level)))
22241 (when (and (<= level n)
22242 (looking-at org-complex-heading-regexp))
22243 (setq head (org-link-display-format
22244 (org-match-string-no-properties 4))
22245 m (org-imenu-new-marker))
22246 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22247 (if (>= level last-level)
22248 (push (cons head m) (aref subs level))
22249 (push (cons head (aref subs (1+ level))) (aref subs level))
22250 (loop for i from (1+ level) to n do (aset subs i nil)))
22251 (setq last-level level)))))
22252 (aref subs 1)))
22254 (eval-after-load "imenu"
22255 '(progn
22256 (add-hook 'imenu-after-jump-hook
22257 (lambda ()
22258 (if (derived-mode-p 'org-mode)
22259 (org-show-context 'org-goto))))))
22261 (defun org-link-display-format (link)
22262 "Replace a link with either the description, or the link target
22263 if no description is present"
22264 (save-match-data
22265 (if (string-match org-bracket-link-analytic-regexp link)
22266 (replace-match (if (match-end 5)
22267 (match-string 5 link)
22268 (concat (match-string 1 link)
22269 (match-string 3 link)))
22270 nil t link)
22271 link)))
22273 (defun org-toggle-link-display ()
22274 "Toggle the literal or descriptive display of links."
22275 (interactive)
22276 (if org-descriptive-links
22277 (progn (org-remove-from-invisibility-spec '(org-link))
22278 (org-restart-font-lock)
22279 (setq org-descriptive-links nil))
22280 (progn (add-to-invisibility-spec '(org-link))
22281 (org-restart-font-lock)
22282 (setq org-descriptive-links t))))
22284 ;; Speedbar support
22286 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22287 "Overlay marking the agenda restriction line in speedbar.")
22288 (overlay-put org-speedbar-restriction-lock-overlay
22289 'face 'org-agenda-restriction-lock)
22290 (overlay-put org-speedbar-restriction-lock-overlay
22291 'help-echo "Agendas are currently limited to this item.")
22292 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22294 (defun org-speedbar-set-agenda-restriction ()
22295 "Restrict future agenda commands to the location at point in speedbar.
22296 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22297 (interactive)
22298 (require 'org-agenda)
22299 (let (p m tp np dir txt)
22300 (cond
22301 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22302 'org-imenu t))
22303 (setq m (get-text-property p 'org-imenu-marker))
22304 (with-current-buffer (marker-buffer m)
22305 (goto-char m)
22306 (org-agenda-set-restriction-lock 'subtree)))
22307 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22308 'speedbar-function 'speedbar-find-file))
22309 (setq tp (previous-single-property-change
22310 (1+ p) 'speedbar-function)
22311 np (next-single-property-change
22312 tp 'speedbar-function)
22313 dir (speedbar-line-directory)
22314 txt (buffer-substring-no-properties (or tp (point-min))
22315 (or np (point-max))))
22316 (with-current-buffer (find-file-noselect
22317 (let ((default-directory dir))
22318 (expand-file-name txt)))
22319 (unless (derived-mode-p 'org-mode)
22320 (error "Cannot restrict to non-Org-mode file"))
22321 (org-agenda-set-restriction-lock 'file)))
22322 (t (error "Don't know how to restrict Org-mode's agenda")))
22323 (move-overlay org-speedbar-restriction-lock-overlay
22324 (point-at-bol) (point-at-eol))
22325 (setq current-prefix-arg nil)
22326 (org-agenda-maybe-redo)))
22328 (eval-after-load "speedbar"
22329 '(progn
22330 (speedbar-add-supported-extension ".org")
22331 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22332 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22333 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22334 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22335 (add-hook 'speedbar-visiting-tag-hook
22336 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22338 ;;; Fixes and Hacks for problems with other packages
22340 ;; Make flyspell not check words in links, to not mess up our keymap
22341 (defun org-mode-flyspell-verify ()
22342 "Don't let flyspell put overlays at active buttons, or on
22343 {todo,all-time,additional-option-like}-keywords."
22344 (let ((pos (max (1- (point)) (point-min)))
22345 (word (thing-at-point 'word)))
22346 (and (not (get-text-property pos 'keymap))
22347 (not (get-text-property pos 'org-no-flyspell))
22348 (not (member word org-todo-keywords-1))
22349 (not (member word org-all-time-keywords))
22350 (not (member word org-options-keywords))
22351 (not (member word (mapcar 'car org-startup-options)))
22352 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22354 (defun org-remove-flyspell-overlays-in (beg end)
22355 "Remove flyspell overlays in region."
22356 (and (org-bound-and-true-p flyspell-mode)
22357 (fboundp 'flyspell-delete-region-overlays)
22358 (flyspell-delete-region-overlays beg end))
22359 (add-text-properties beg end '(org-no-flyspell t)))
22361 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22362 (eval-after-load "bookmark"
22363 '(if (boundp 'bookmark-after-jump-hook)
22364 ;; We can use the hook
22365 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22366 ;; Hook not available, use advice
22367 (defadvice bookmark-jump (after org-make-visible activate)
22368 "Make the position visible."
22369 (org-bookmark-jump-unhide))))
22371 ;; Make sure saveplace shows the location if it was hidden
22372 (eval-after-load "saveplace"
22373 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22374 "Make the position visible."
22375 (org-bookmark-jump-unhide)))
22377 ;; Make sure ecb shows the location if it was hidden
22378 (eval-after-load "ecb"
22379 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22380 "Make hierarchy visible when jumping into location from ECB tree buffer."
22381 (if (derived-mode-p 'org-mode)
22382 (org-show-context))))
22384 (defun org-bookmark-jump-unhide ()
22385 "Unhide the current position, to show the bookmark location."
22386 (and (derived-mode-p 'org-mode)
22387 (or (outline-invisible-p)
22388 (save-excursion (goto-char (max (point-min) (1- (point))))
22389 (outline-invisible-p)))
22390 (org-show-context 'bookmark-jump)))
22392 ;; Make session.el ignore our circular variable
22393 (eval-after-load "session"
22394 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22396 ;;;; Experimental code
22398 (defun org-closed-in-range ()
22399 "Sparse tree of items closed in a certain time range.
22400 Still experimental, may disappear in the future."
22401 (interactive)
22402 ;; Get the time interval from the user.
22403 (let* ((time1 (org-float-time
22404 (org-read-date nil 'to-time nil "Starting date: ")))
22405 (time2 (org-float-time
22406 (org-read-date nil 'to-time nil "End date:")))
22407 ;; callback function
22408 (callback (lambda ()
22409 (let ((time
22410 (org-float-time
22411 (apply 'encode-time
22412 (org-parse-time-string
22413 (match-string 1))))))
22414 ;; check if time in interval
22415 (and (>= time time1) (<= time time2))))))
22416 ;; make tree, check each match with the callback
22417 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22419 ;;;; Finish up
22421 (provide 'org)
22423 (run-hooks 'org-load-hook)
22425 ;;; org.el ends here