org.el: Option to get LaTeX preview in the same color as text face
[org-mode.git] / lisp / org.el
blobeaabeb3055f2e5298de462d33875c6db191e612f
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" ())
119 ;; load languages based on value of `org-babel-load-languages'
120 (defvar org-babel-load-languages)
121 ;;;###autoload
122 (defun org-babel-do-load-languages (sym value)
123 "Load the languages defined in `org-babel-load-languages'."
124 (set-default sym value)
125 (mapc (lambda (pair)
126 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
127 (if active
128 (progn
129 (require (intern (concat "ob-" lang))))
130 (progn
131 (funcall 'fmakunbound
132 (intern (concat "org-babel-execute:" lang)))
133 (funcall 'fmakunbound
134 (intern (concat "org-babel-expand-body:" lang)))))))
135 org-babel-load-languages))
137 (defcustom org-babel-load-languages '((emacs-lisp . t))
138 "Languages which can be evaluated in Org-mode buffers.
139 This list can be used to load support for any of the languages
140 below, note that each language will depend on a different set of
141 system executables and/or Emacs modes. When a language is
142 \"loaded\", then code blocks in that language can be evaluated
143 with `org-babel-execute-src-block' bound by default to C-c
144 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
145 be set to remove code block evaluation from the C-c C-c
146 keybinding. By default only Emacs Lisp (which has no
147 requirements) is loaded."
148 :group 'org-babel
149 :set 'org-babel-do-load-languages
150 :version "24.1"
151 :type '(alist :tag "Babel Languages"
152 :key-type
153 (choice
154 (const :tag "Awk" awk)
155 (const :tag "C" C)
156 (const :tag "R" R)
157 (const :tag "Asymptote" asymptote)
158 (const :tag "Calc" calc)
159 (const :tag "Clojure" clojure)
160 (const :tag "CSS" css)
161 (const :tag "Ditaa" ditaa)
162 (const :tag "Dot" dot)
163 (const :tag "Emacs Lisp" emacs-lisp)
164 (const :tag "Fortran" fortran)
165 (const :tag "Gnuplot" gnuplot)
166 (const :tag "Haskell" haskell)
167 (const :tag "IO" io)
168 (const :tag "Java" java)
169 (const :tag "Javascript" js)
170 (const :tag "LaTeX" latex)
171 (const :tag "Ledger" ledger)
172 (const :tag "Lilypond" lilypond)
173 (const :tag "Lisp" lisp)
174 (const :tag "Maxima" maxima)
175 (const :tag "Matlab" matlab)
176 (const :tag "Mscgen" mscgen)
177 (const :tag "Ocaml" ocaml)
178 (const :tag "Octave" octave)
179 (const :tag "Org" org)
180 (const :tag "Perl" perl)
181 (const :tag "Pico Lisp" picolisp)
182 (const :tag "PlantUML" plantuml)
183 (const :tag "Python" python)
184 (const :tag "Ruby" ruby)
185 (const :tag "Sass" sass)
186 (const :tag "Scala" scala)
187 (const :tag "Scheme" scheme)
188 (const :tag "Screen" screen)
189 (const :tag "Shell Script" sh)
190 (const :tag "Shen" shen)
191 (const :tag "Sql" sql)
192 (const :tag "Sqlite" sqlite))
193 :value-type (boolean :tag "Activate" :value t)))
195 ;;;; Customization variables
196 (defcustom org-clone-delete-id nil
197 "Remove ID property of clones of a subtree.
198 When non-nil, clones of a subtree don't inherit the ID property.
199 Otherwise they inherit the ID property with a new unique
200 identifier."
201 :type 'boolean
202 :version "24.1"
203 :group 'org-id)
205 ;;; Version
206 (require 'org-compat)
207 (org-check-version)
208 ;;;###autoload
209 (defun org-version (&optional here full message)
210 "Show the org-mode version in the echo area.
211 With prefix argument HERE, insert it at point.
212 When FULL is non-nil, use a verbose version string.
213 When MESSAGE is non-nil, display a message with the version."
214 (interactive "P")
215 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
216 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
217 (org-trash (or
218 (and (fboundp 'org-release) (fboundp 'org-git-version))
219 (load (concat org-dir "org-version.el")
220 'noerror 'nomessage 'nosuffix)))
221 (org-version (org-release))
222 (git-version (org-git-version))
223 (version (format "Org-mode version %s (%s @ %s)"
224 org-version
225 git-version
226 (if org-install-dir
227 (if (string= org-dir org-install-dir)
228 org-install-dir
229 (concat "mixed installation! " org-install-dir " and " org-dir))
230 "org-install.el can not be found!")))
231 (_version (if full version org-version)))
232 (if (org-called-interactively-p 'interactive)
233 (if here
234 (insert version)
235 (message version))
236 (if message (message _version))
237 _version)))
239 (defconst org-version (org-version))
241 ;;; Compatibility constants
243 ;;; The custom variables
245 (defgroup org nil
246 "Outline-based notes management and organizer."
247 :tag "Org"
248 :group 'outlines
249 :group 'calendar)
251 (defcustom org-mode-hook nil
252 "Mode hook for Org-mode, run after the mode was turned on."
253 :group 'org
254 :type 'hook)
256 (defcustom org-load-hook nil
257 "Hook that is run after org.el has been loaded."
258 :group 'org
259 :type 'hook)
261 (defcustom org-log-buffer-setup-hook nil
262 "Hook that is run after an Org log buffer is created."
263 :group 'org
264 :version "24.1"
265 :type 'hook)
267 (defvar org-modules) ; defined below
268 (defvar org-modules-loaded nil
269 "Have the modules been loaded already?")
271 (defun org-load-modules-maybe (&optional force)
272 "Load all extensions listed in `org-modules'."
273 (when (or force (not org-modules-loaded))
274 (mapc (lambda (ext)
275 (condition-case nil (require ext)
276 (error (message "Problems while trying to load feature `%s'" ext))))
277 org-modules)
278 (setq org-modules-loaded t)))
280 (defun org-set-modules (var value)
281 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
282 (set var value)
283 (when (featurep 'org)
284 (org-load-modules-maybe 'force)))
286 (when (org-bound-and-true-p org-modules)
287 (let ((a (member 'org-infojs org-modules)))
288 (and a (setcar a 'org-jsinfo))))
290 (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)
291 "Modules that should always be loaded together with org.el.
292 If a description starts with <C>, the file is not part of Emacs
293 and loading it will require that you have downloaded and properly installed
294 the org-mode distribution.
296 You can also use this system to load external packages (i.e. neither Org
297 core modules, nor modules from the CONTRIB directory). Just add symbols
298 to the end of the list. If the package is called org-xyz.el, then you need
299 to add the symbol `xyz', and the package must have a call to
301 (provide 'org-xyz)"
302 :group 'org
303 :set 'org-set-modules
304 :type
305 '(set :greedy t
306 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
307 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
308 (const :tag " crypt: Encryption of subtrees" org-crypt)
309 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
310 (const :tag " docview: Links to doc-view buffers" org-docview)
311 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
312 (const :tag " id: Global IDs for identifying entries" org-id)
313 (const :tag " info: Links to Info nodes" org-info)
314 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
315 (const :tag " habit: Track your consistency with habits" org-habit)
316 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
317 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
318 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
319 (const :tag " mew Links to Mew folders/messages" org-mew)
320 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
321 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
322 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
323 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
324 (const :tag " vm: Links to VM folders/messages" org-vm)
325 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
326 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
327 (const :tag " mouse: Additional mouse support" org-mouse)
328 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
330 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
331 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
332 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
333 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
334 (const :tag "C collector: Collect properties into tables" org-collector)
335 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
336 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
337 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
338 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
339 (const :tag "C eval: Include command output as text" org-eval)
340 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
341 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
342 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
343 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
344 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
346 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
348 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
349 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
350 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
351 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
352 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
353 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
354 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
355 (const :tag "C mtags: Support for muse-like tags" org-mtags)
356 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
357 (const :tag "C registry: A registry for Org-mode links" org-registry)
358 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
359 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
360 (const :tag "C secretary: Team management with org-mode" org-secretary)
361 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
362 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
363 (const :tag "C track: Keep up with Org-mode development" org-track)
364 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
365 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
366 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
368 (defcustom org-support-shift-select nil
369 "Non-nil means make shift-cursor commands select text when possible.
371 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
372 start selecting a region, or enlarge regions started in this way.
373 In Org-mode, in special contexts, these same keys are used for
374 other purposes, important enough to compete with shift selection.
375 Org tries to balance these needs by supporting `shift-select-mode'
376 outside these special contexts, under control of this variable.
378 The default of this variable is nil, to avoid confusing behavior. Shifted
379 cursor keys will then execute Org commands in the following contexts:
380 - on a headline, changing TODO state (left/right) and priority (up/down)
381 - on a time stamp, changing the time
382 - in a plain list item, changing the bullet type
383 - in a property definition line, switching between allowed values
384 - in the BEGIN line of a clock table (changing the time block).
385 Outside these contexts, the commands will throw an error.
387 When this variable is t and the cursor is not in a special
388 context, Org-mode will support shift-selection for making and
389 enlarging regions. To make this more effective, the bullet
390 cycling will no longer happen anywhere in an item line, but only
391 if the cursor is exactly on the bullet.
393 If you set this variable to the symbol `always', then the keys
394 will not be special in headlines, property lines, and item lines,
395 to make shift selection work there as well. If this is what you
396 want, you can use the following alternative commands: `C-c C-t'
397 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
398 can be used to switch TODO sets, `C-c -' to cycle item bullet
399 types, and properties can be edited by hand or in column view.
401 However, when the cursor is on a timestamp, shift-cursor commands
402 will still edit the time stamp - this is just too good to give up.
404 XEmacs user should have this variable set to nil, because
405 `shift-select-mode' is in Emacs 23 or later only."
406 :group 'org
407 :type '(choice
408 (const :tag "Never" nil)
409 (const :tag "When outside special context" t)
410 (const :tag "Everywhere except timestamps" always)))
412 (defcustom org-loop-over-headlines-in-active-region nil
413 "Shall some commands act upon headlines in the active region?
415 When set to `t', some commands will be performed in all headlines
416 within the active region.
418 When set to `start-level', some commands will be performed in all
419 headlines within the active region, provided that these headlines
420 are of the same level than the first one.
422 When set to a string, those commands will be performed on the
423 matching headlines within the active region. Such string must be
424 a tags/property/todo match as it is used in the agenda tags view.
426 The list of commands is: `org-schedule', `org-deadline',
427 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
428 `org-archive-to-archive-sibling'. The archiving commands skip
429 already archived entries."
430 :type '(choice (const :tag "Don't loop" nil)
431 (const :tag "All headlines in active region" t)
432 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
433 (string :tag "Tags/Property/Todo matcher"))
434 :version "24.1"
435 :group 'org-todo
436 :group 'org-archive)
438 (defgroup org-startup nil
439 "Options concerning startup of Org-mode."
440 :tag "Org Startup"
441 :group 'org)
443 (defcustom org-startup-folded t
444 "Non-nil means entering Org-mode will switch to OVERVIEW.
445 This can also be configured on a per-file basis by adding one of
446 the following lines anywhere in the buffer:
448 #+STARTUP: fold (or `overview', this is equivalent)
449 #+STARTUP: nofold (or `showall', this is equivalent)
450 #+STARTUP: content
451 #+STARTUP: showeverything"
452 :group 'org-startup
453 :type '(choice
454 (const :tag "nofold: show all" nil)
455 (const :tag "fold: overview" t)
456 (const :tag "content: all headlines" content)
457 (const :tag "show everything, even drawers" showeverything)))
459 (defcustom org-startup-truncated t
460 "Non-nil means entering Org-mode will set `truncate-lines'.
461 This is useful since some lines containing links can be very long and
462 uninteresting. Also tables look terrible when wrapped."
463 :group 'org-startup
464 :type 'boolean)
466 (defcustom org-startup-indented nil
467 "Non-nil means turn on `org-indent-mode' on startup.
468 This can also be configured on a per-file basis by adding one of
469 the following lines anywhere in the buffer:
471 #+STARTUP: indent
472 #+STARTUP: noindent"
473 :group 'org-structure
474 :type '(choice
475 (const :tag "Not" nil)
476 (const :tag "Globally (slow on startup in large files)" t)))
478 (defcustom org-use-sub-superscripts t
479 "Non-nil means interpret \"_\" and \"^\" for export.
480 When this option is turned on, you can use TeX-like syntax for sub- and
481 superscripts. Several characters after \"_\" or \"^\" will be
482 considered as a single item - so grouping with {} is normally not
483 needed. For example, the following things will be parsed as single
484 sub- or superscripts.
486 10^24 or 10^tau several digits will be considered 1 item.
487 10^-12 or 10^-tau a leading sign with digits or a word
488 x^2-y^3 will be read as x^2 - y^3, because items are
489 terminated by almost any nonword/nondigit char.
490 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
492 Still, ambiguity is possible - so when in doubt use {} to enclose the
493 sub/superscript. If you set this variable to the symbol `{}',
494 the braces are *required* in order to trigger interpretations as
495 sub/superscript. This can be helpful in documents that need \"_\"
496 frequently in plain text.
498 Not all export backends support this, but HTML does.
500 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
501 :group 'org-startup
502 :group 'org-export-translation
503 :version "24.1"
504 :type '(choice
505 (const :tag "Always interpret" t)
506 (const :tag "Only with braces" {})
507 (const :tag "Never interpret" nil)))
509 (if (fboundp 'defvaralias)
510 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
513 (defcustom org-startup-with-beamer-mode nil
514 "Non-nil means turn on `org-beamer-mode' on startup.
515 This can also be configured on a per-file basis by adding one of
516 the following lines anywhere in the buffer:
518 #+STARTUP: beamer"
519 :group 'org-startup
520 :version "24.1"
521 :type 'boolean)
523 (defcustom org-startup-align-all-tables nil
524 "Non-nil means align all tables when visiting a file.
525 This is useful when the column width in tables is forced with <N> cookies
526 in table fields. Such tables will look correct only after the first re-align.
527 This can also be configured on a per-file basis by adding one of
528 the following lines anywhere in the buffer:
529 #+STARTUP: align
530 #+STARTUP: noalign"
531 :group 'org-startup
532 :type 'boolean)
534 (defcustom org-startup-with-inline-images nil
535 "Non-nil means show inline images when loading a new Org file.
536 This can also be configured on a per-file basis by adding one of
537 the following lines anywhere in the buffer:
538 #+STARTUP: inlineimages
539 #+STARTUP: noinlineimages"
540 :group 'org-startup
541 :version "24.1"
542 :type 'boolean)
544 (defcustom org-insert-mode-line-in-empty-file nil
545 "Non-nil means insert the first line setting Org-mode in empty files.
546 When the function `org-mode' is called interactively in an empty file, this
547 normally means that the file name does not automatically trigger Org-mode.
548 To ensure that the file will always be in Org-mode in the future, a
549 line enforcing Org-mode will be inserted into the buffer, if this option
550 has been set."
551 :group 'org-startup
552 :type 'boolean)
554 (defcustom org-replace-disputed-keys nil
555 "Non-nil means use alternative key bindings for some keys.
556 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
557 These keys are also used by other packages like shift-selection-mode'
558 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
559 If you want to use Org-mode together with one of these other modes,
560 or more generally if you would like to move some Org-mode commands to
561 other keys, set this variable and configure the keys with the variable
562 `org-disputed-keys'.
564 This option is only relevant at load-time of Org-mode, and must be set
565 *before* org.el is loaded. Changing it requires a restart of Emacs to
566 become effective."
567 :group 'org-startup
568 :type 'boolean)
570 (defcustom org-use-extra-keys nil
571 "Non-nil means use extra key sequence definitions for certain commands.
572 This happens automatically if you run XEmacs or if `window-system'
573 is nil. This variable lets you do the same manually. You must
574 set it before loading org.
576 Example: on Carbon Emacs 22 running graphically, with an external
577 keyboard on a Powerbook, the default way of setting M-left might
578 not work for either Alt or ESC. Setting this variable will make
579 it work for ESC."
580 :group 'org-startup
581 :type 'boolean)
583 (if (fboundp 'defvaralias)
584 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
586 (defcustom org-disputed-keys
587 '(([(shift up)] . [(meta p)])
588 ([(shift down)] . [(meta n)])
589 ([(shift left)] . [(meta -)])
590 ([(shift right)] . [(meta +)])
591 ([(control shift right)] . [(meta shift +)])
592 ([(control shift left)] . [(meta shift -)]))
593 "Keys for which Org-mode and other modes compete.
594 This is an alist, cars are the default keys, second element specifies
595 the alternative to use when `org-replace-disputed-keys' is t.
597 Keys can be specified in any syntax supported by `define-key'.
598 The value of this option takes effect only at Org-mode's startup,
599 therefore you'll have to restart Emacs to apply it after changing."
600 :group 'org-startup
601 :type 'alist)
603 (defun org-key (key)
604 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
605 Or return the original if not disputed.
606 Also apply the translations defined in `org-xemacs-key-equivalents'."
607 (when org-replace-disputed-keys
608 (let* ((nkey (key-description key))
609 (x (org-find-if (lambda (x)
610 (equal (key-description (car x)) nkey))
611 org-disputed-keys)))
612 (setq key (if x (cdr x) key))))
613 (when (featurep 'xemacs)
614 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
615 key)
617 (defun org-find-if (predicate seq)
618 (catch 'exit
619 (while seq
620 (if (funcall predicate (car seq))
621 (throw 'exit (car seq))
622 (pop seq)))))
624 (defun org-defkey (keymap key def)
625 "Define a key, possibly translated, as returned by `org-key'."
626 (define-key keymap (org-key key) def))
628 (defcustom org-ellipsis nil
629 "The ellipsis to use in the Org-mode outline.
630 When nil, just use the standard three dots. When a string, use that instead,
631 When a face, use the standard 3 dots, but with the specified face.
632 The change affects only Org-mode (which will then use its own display table).
633 Changing this requires executing `M-x org-mode' in a buffer to become
634 effective."
635 :group 'org-startup
636 :type '(choice (const :tag "Default" nil)
637 (face :tag "Face" :value org-warning)
638 (string :tag "String" :value "...#")))
640 (defvar org-display-table nil
641 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
643 (defgroup org-keywords nil
644 "Keywords in Org-mode."
645 :tag "Org Keywords"
646 :group 'org)
648 (defcustom org-deadline-string "DEADLINE:"
649 "String to mark deadline entries.
650 A deadline is this string, followed by a time stamp. Should be a word,
651 terminated by a colon. You can insert a schedule keyword and
652 a timestamp with \\[org-deadline].
653 Changes become only effective after restarting Emacs."
654 :group 'org-keywords
655 :type 'string)
657 (defcustom org-scheduled-string "SCHEDULED:"
658 "String to mark scheduled TODO entries.
659 A schedule is this string, followed by a time stamp. Should be a word,
660 terminated by a colon. You can insert a schedule keyword and
661 a timestamp with \\[org-schedule].
662 Changes become only effective after restarting Emacs."
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-closed-string "CLOSED:"
667 "String used as the prefix for timestamps logging closing a TODO entry."
668 :group 'org-keywords
669 :type 'string)
671 (defcustom org-clock-string "CLOCK:"
672 "String used as prefix for timestamps clocking work hours on an item."
673 :group 'org-keywords
674 :type 'string)
676 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
677 org-scheduled-string "\\|"
678 org-deadline-string "\\|"
679 org-closed-string "\\|"
680 org-clock-string "\\)")
681 "Matches a line with planning or clock info.")
683 (defcustom org-comment-string "COMMENT"
684 "Entries starting with this keyword will never be exported.
685 An entry can be toggled between COMMENT and normal with
686 \\[org-toggle-comment].
687 Changes become only effective after restarting Emacs."
688 :group 'org-keywords
689 :type 'string)
691 (defcustom org-quote-string "QUOTE"
692 "Entries starting with this keyword will be exported in fixed-width font.
693 Quoting applies only to the text in the entry following the headline, and does
694 not extend beyond the next headline, even if that is lower level.
695 An entry can be toggled between QUOTE and normal with
696 \\[org-toggle-fixed-width-section]."
697 :group 'org-keywords
698 :type 'string)
700 (defconst org-repeat-re
701 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
702 "Regular expression for specifying repeated events.
703 After a match, group 1 contains the repeat expression.")
705 (defgroup org-structure nil
706 "Options concerning the general structure of Org-mode files."
707 :tag "Org Structure"
708 :group 'org)
710 (defgroup org-reveal-location nil
711 "Options about how to make context of a location visible."
712 :tag "Org Reveal Location"
713 :group 'org-structure)
715 (defconst org-context-choice
716 '(choice
717 (const :tag "Always" t)
718 (const :tag "Never" nil)
719 (repeat :greedy t :tag "Individual contexts"
720 (cons
721 (choice :tag "Context"
722 (const agenda)
723 (const org-goto)
724 (const occur-tree)
725 (const tags-tree)
726 (const link-search)
727 (const mark-goto)
728 (const bookmark-jump)
729 (const isearch)
730 (const default))
731 (boolean))))
732 "Contexts for the reveal options.")
734 (defcustom org-show-hierarchy-above '((default . t))
735 "Non-nil means show full hierarchy when revealing a location.
736 Org-mode often shows locations in an org-mode file which might have
737 been invisible before. When this is set, the hierarchy of headings
738 above the exposed location is shown.
739 Turning this off for example for sparse trees makes them very compact.
740 Instead of t, this can also be an alist specifying this option for different
741 contexts. Valid contexts are
742 agenda when exposing an entry from the agenda
743 org-goto when using the command `org-goto' on key C-c C-j
744 occur-tree when using the command `org-occur' on key C-c /
745 tags-tree when constructing a sparse tree based on tags matches
746 link-search when exposing search matches associated with a link
747 mark-goto when exposing the jump goal of a mark
748 bookmark-jump when exposing a bookmark location
749 isearch when exiting from an incremental search
750 default default for all contexts not set explicitly"
751 :group 'org-reveal-location
752 :type org-context-choice)
754 (defcustom org-show-following-heading '((default . nil))
755 "Non-nil means show following heading when revealing a location.
756 Org-mode often shows locations in an org-mode file which might have
757 been invisible before. When this is set, the heading following the
758 match is shown.
759 Turning this off for example for sparse trees makes them very compact,
760 but makes it harder to edit the location of the match. In such a case,
761 use the command \\[org-reveal] to show more context.
762 Instead of t, this can also be an alist specifying this option for different
763 contexts. See `org-show-hierarchy-above' for valid contexts."
764 :group 'org-reveal-location
765 :type org-context-choice)
767 (defcustom org-show-siblings '((default . nil) (isearch t))
768 "Non-nil means show all sibling heading when revealing a location.
769 Org-mode often shows locations in an org-mode file which might have
770 been invisible before. When this is set, the sibling of the current entry
771 heading are all made visible. If `org-show-hierarchy-above' is t,
772 the same happens on each level of the hierarchy above the current entry.
774 By default this is on for the isearch context, off for all other contexts.
775 Turning this off for example for sparse trees makes them very compact,
776 but makes it harder to edit the location of the match. In such a case,
777 use the command \\[org-reveal] to show more context.
778 Instead of t, this can also be an alist specifying this option for different
779 contexts. See `org-show-hierarchy-above' for valid contexts."
780 :group 'org-reveal-location
781 :type org-context-choice)
783 (defcustom org-show-entry-below '((default . nil))
784 "Non-nil means show the entry below a headline when revealing a location.
785 Org-mode often shows locations in an org-mode file which might have
786 been invisible before. When this is set, the text below the headline that is
787 exposed is also shown.
789 By default this is off for all contexts.
790 Instead of t, this can also be an alist specifying this option for different
791 contexts. See `org-show-hierarchy-above' for valid contexts."
792 :group 'org-reveal-location
793 :type org-context-choice)
795 (defcustom org-indirect-buffer-display 'other-window
796 "How should indirect tree buffers be displayed?
797 This applies to indirect buffers created with the commands
798 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
799 Valid values are:
800 current-window Display in the current window
801 other-window Just display in another window.
802 dedicated-frame Create one new frame, and re-use it each time.
803 new-frame Make a new frame each time. Note that in this case
804 previously-made indirect buffers are kept, and you need to
805 kill these buffers yourself."
806 :group 'org-structure
807 :group 'org-agenda-windows
808 :type '(choice
809 (const :tag "In current window" current-window)
810 (const :tag "In current frame, other window" other-window)
811 (const :tag "Each time a new frame" new-frame)
812 (const :tag "One dedicated frame" dedicated-frame)))
814 (defcustom org-use-speed-commands nil
815 "Non-nil means activate single letter commands at beginning of a headline.
816 This may also be a function to test for appropriate locations where speed
817 commands should be active."
818 :group 'org-structure
819 :type '(choice
820 (const :tag "Never" nil)
821 (const :tag "At beginning of headline stars" t)
822 (function)))
824 (defcustom org-speed-commands-user nil
825 "Alist of additional speed commands.
826 This list will be checked before `org-speed-commands-default'
827 when the variable `org-use-speed-commands' is non-nil
828 and when the cursor is at the beginning of a headline.
829 The car if each entry is a string with a single letter, which must
830 be assigned to `self-insert-command' in the global map.
831 The cdr is either a command to be called interactively, a function
832 to be called, or a form to be evaluated.
833 An entry that is just a list with a single string will be interpreted
834 as a descriptive headline that will be added when listing the speed
835 commands in the Help buffer using the `?' speed command."
836 :group 'org-structure
837 :type '(repeat :value ("k" . ignore)
838 (choice :value ("k" . ignore)
839 (list :tag "Descriptive Headline" (string :tag "Headline"))
840 (cons :tag "Letter and Command"
841 (string :tag "Command letter")
842 (choice
843 (function)
844 (sexp))))))
846 (defgroup org-cycle nil
847 "Options concerning visibility cycling in Org-mode."
848 :tag "Org Cycle"
849 :group 'org-structure)
851 (defcustom org-cycle-skip-children-state-if-no-children t
852 "Non-nil means skip CHILDREN state in entries that don't have any."
853 :group 'org-cycle
854 :type 'boolean)
856 (defcustom org-cycle-max-level nil
857 "Maximum level which should still be subject to visibility cycling.
858 Levels higher than this will, for cycling, be treated as text, not a headline.
859 When `org-odd-levels-only' is set, a value of N in this variable actually
860 means 2N-1 stars as the limiting headline.
861 When nil, cycle all levels.
862 Note that the limiting level of cycling is also influenced by
863 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
864 `org-inlinetask-min-level' is, cycling will be limited to levels one less
865 than its value."
866 :group 'org-cycle
867 :type '(choice
868 (const :tag "No limit" nil)
869 (integer :tag "Maximum level")))
871 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
872 "Names of drawers. Drawers are not opened by cycling on the headline above.
873 Drawers only open with a TAB on the drawer line itself. A drawer looks like
874 this:
875 :DRAWERNAME:
876 .....
877 :END:
878 The drawer \"PROPERTIES\" is special for capturing properties through
879 the property API.
881 Drawers can be defined on the per-file basis with a line like:
883 #+DRAWERS: HIDDEN STATE PROPERTIES"
884 :group 'org-structure
885 :group 'org-cycle
886 :type '(repeat (string :tag "Drawer Name")))
888 (defcustom org-hide-block-startup nil
889 "Non-nil means entering Org-mode will fold all blocks.
890 This can also be set in on a per-file basis with
892 #+STARTUP: hideblocks
893 #+STARTUP: showblocks"
894 :group 'org-startup
895 :group 'org-cycle
896 :type 'boolean)
898 (defcustom org-cycle-global-at-bob nil
899 "Cycle globally if cursor is at beginning of buffer and not at a headline.
900 This makes it possible to do global cycling without having to use S-TAB or
901 \\[universal-argument] TAB. For this special case to work, the first line \
902 of the buffer
903 must not be a headline - it may be empty or some other text. When used in
904 this way, `org-cycle-hook' is disables temporarily, to make sure the
905 cursor stays at the beginning of the buffer.
906 When this option is nil, don't do anything special at the beginning
907 of the buffer."
908 :group 'org-cycle
909 :type 'boolean)
911 (defcustom org-cycle-level-after-item/entry-creation t
912 "Non-nil means cycle entry level or item indentation in new empty entries.
914 When the cursor is at the end of an empty headline, i.e with only stars
915 and maybe a TODO keyword, TAB will then switch the entry to become a child,
916 and then all possible ancestor states, before returning to the original state.
917 This makes data entry extremely fast: M-RET to create a new headline,
918 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
920 When the cursor is at the end of an empty plain list item, one TAB will
921 make it a subitem, two or more tabs will back up to make this an item
922 higher up in the item hierarchy."
923 :group 'org-cycle
924 :type 'boolean)
926 (defcustom org-cycle-emulate-tab t
927 "Where should `org-cycle' emulate TAB.
928 nil Never
929 white Only in completely white lines
930 whitestart Only at the beginning of lines, before the first non-white char
931 t Everywhere except in headlines
932 exc-hl-bol Everywhere except at the start of a headline
933 If TAB is used in a place where it does not emulate TAB, the current subtree
934 visibility is cycled."
935 :group 'org-cycle
936 :type '(choice (const :tag "Never" nil)
937 (const :tag "Only in completely white lines" white)
938 (const :tag "Before first char in a line" whitestart)
939 (const :tag "Everywhere except in headlines" t)
940 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
943 (defcustom org-cycle-separator-lines 2
944 "Number of empty lines needed to keep an empty line between collapsed trees.
945 If you leave an empty line between the end of a subtree and the following
946 headline, this empty line is hidden when the subtree is folded.
947 Org-mode will leave (exactly) one empty line visible if the number of
948 empty lines is equal or larger to the number given in this variable.
949 So the default 2 means at least 2 empty lines after the end of a subtree
950 are needed to produce free space between a collapsed subtree and the
951 following headline.
953 If the number is negative, and the number of empty lines is at least -N,
954 all empty lines are shown.
956 Special case: when 0, never leave empty lines in collapsed view."
957 :group 'org-cycle
958 :type 'integer)
959 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
961 (defcustom org-pre-cycle-hook nil
962 "Hook that is run before visibility cycling is happening.
963 The function(s) in this hook must accept a single argument which indicates
964 the new state that will be set right after running this hook. The
965 argument is a symbol. Before a global state change, it can have the values
966 `overview', `content', or `all'. Before a local state change, it can have
967 the values `folded', `children', or `subtree'."
968 :group 'org-cycle
969 :type 'hook)
971 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
972 org-cycle-hide-drawers
973 org-cycle-show-empty-lines
974 org-optimize-window-after-visibility-change)
975 "Hook that is run after `org-cycle' has changed the buffer visibility.
976 The function(s) in this hook must accept a single argument which indicates
977 the new state that was set by the most recent `org-cycle' command. The
978 argument is a symbol. After a global state change, it can have the values
979 `overview', `content', or `all'. After a local state change, it can have
980 the values `folded', `children', or `subtree'."
981 :group 'org-cycle
982 :type 'hook)
984 (defgroup org-edit-structure nil
985 "Options concerning structure editing in Org-mode."
986 :tag "Org Edit Structure"
987 :group 'org-structure)
989 (defcustom org-odd-levels-only nil
990 "Non-nil means skip even levels and only use odd levels for the outline.
991 This has the effect that two stars are being added/taken away in
992 promotion/demotion commands. It also influences how levels are
993 handled by the exporters.
994 Changing it requires restart of `font-lock-mode' to become effective
995 for fontification also in regions already fontified.
996 You may also set this on a per-file basis by adding one of the following
997 lines to the buffer:
999 #+STARTUP: odd
1000 #+STARTUP: oddeven"
1001 :group 'org-edit-structure
1002 :group 'org-appearance
1003 :type 'boolean)
1005 (defcustom org-adapt-indentation t
1006 "Non-nil means adapt indentation to outline node level.
1008 When this variable is set, Org assumes that you write outlines by
1009 indenting text in each node to align with the headline (after the stars).
1010 The following issues are influenced by this variable:
1012 - When this is set and the *entire* text in an entry is indented, the
1013 indentation is increased by one space in a demotion command, and
1014 decreased by one in a promotion command. If any line in the entry
1015 body starts with text at column 0, indentation is not changed at all.
1017 - Property drawers and planning information is inserted indented when
1018 this variable s set. When nil, they will not be indented.
1020 - TAB indents a line relative to context. The lines below a headline
1021 will be indented when this variable is set.
1023 Note that this is all about true indentation, by adding and removing
1024 space characters. See also `org-indent.el' which does level-dependent
1025 indentation in a virtual way, i.e. at display time in Emacs."
1026 :group 'org-edit-structure
1027 :type 'boolean)
1029 (defcustom org-special-ctrl-a/e nil
1030 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1032 When t, `C-a' will bring back the cursor to the beginning of the
1033 headline text, i.e. after the stars and after a possible TODO
1034 keyword. In an item, this will be the position after bullet and
1035 check-box, if any. When the cursor is already at that position,
1036 another `C-a' will bring it to the beginning of the line.
1038 `C-e' will jump to the end of the headline, ignoring the presence
1039 of tags in the headline. A second `C-e' will then jump to the
1040 true end of the line, after any tags. This also means that, when
1041 this variable is non-nil, `C-e' also will never jump beyond the
1042 end of the heading of a folded section, i.e. not after the
1043 ellipses.
1045 When set to the symbol `reversed', the first `C-a' or `C-e' works
1046 normally, going to the true line boundary first. Only a directly
1047 following, identical keypress will bring the cursor to the
1048 special positions.
1050 This may also be a cons cell where the behavior for `C-a' and
1051 `C-e' is set separately."
1052 :group 'org-edit-structure
1053 :type '(choice
1054 (const :tag "off" nil)
1055 (const :tag "on: after stars/bullet and before tags first" t)
1056 (const :tag "reversed: true line boundary first" reversed)
1057 (cons :tag "Set C-a and C-e separately"
1058 (choice :tag "Special C-a"
1059 (const :tag "off" nil)
1060 (const :tag "on: after stars/bullet first" t)
1061 (const :tag "reversed: before stars/bullet first" reversed))
1062 (choice :tag "Special C-e"
1063 (const :tag "off" nil)
1064 (const :tag "on: before tags first" t)
1065 (const :tag "reversed: after tags first" reversed)))))
1066 (if (fboundp 'defvaralias)
1067 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1069 (defcustom org-special-ctrl-k nil
1070 "Non-nil means `C-k' will behave specially in headlines.
1071 When nil, `C-k' will call the default `kill-line' command.
1072 When t, the following will happen while the cursor is in the headline:
1074 - When the cursor is at the beginning of a headline, kill the entire
1075 line and possible the folded subtree below the line.
1076 - When in the middle of the headline text, kill the headline up to the tags.
1077 - When after the headline text, kill the tags."
1078 :group 'org-edit-structure
1079 :type 'boolean)
1081 (defcustom org-ctrl-k-protect-subtree nil
1082 "Non-nil means, do not delete a hidden subtree with C-k.
1083 When set to the symbol `error', simply throw an error when C-k is
1084 used to kill (part-of) a headline that has hidden text behind it.
1085 Any other non-nil value will result in a query to the user, if it is
1086 OK to kill that hidden subtree. When nil, kill without remorse."
1087 :group 'org-edit-structure
1088 :version "24.1"
1089 :type '(choice
1090 (const :tag "Do not protect hidden subtrees" nil)
1091 (const :tag "Protect hidden subtrees with a security query" t)
1092 (const :tag "Never kill a hidden subtree with C-k" error)))
1094 (defcustom org-catch-invisible-edits nil
1095 "Check if in invisible region before inserting or deleting a character.
1096 Valid values are:
1098 nil Do not check, so just do invisible edits.
1099 error Throw an error and do nothing.
1100 show Make point visible, and do the requested edit.
1101 show-and-error Make point visible, then throw an error and abort the edit.
1102 smart Make point visible, and do insertion/deletion if it is
1103 adjacent to visible text and the change feels predictable.
1104 Never delete a previously invisible character or add in the
1105 middle or right after an invisible region. Basically, this
1106 allows insertion and backward-delete right before ellipses.
1107 FIXME: maybe in this case we should not even show?"
1108 :group 'org-edit-structure
1109 :version "24.1"
1110 :type '(choice
1111 (const :tag "Do not check" nil)
1112 (const :tag "Throw error when trying to edit" error)
1113 (const :tag "Unhide, but do not do the edit" show-and-error)
1114 (const :tag "Show invisible part and do the edit" show)
1115 (const :tag "Be smart and do the right thing" smart)))
1117 (defcustom org-yank-folded-subtrees t
1118 "Non-nil means when yanking subtrees, fold them.
1119 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1120 it starts with a heading and all other headings in it are either children
1121 or siblings, then fold all the subtrees. However, do this only if no
1122 text after the yank would be swallowed into a folded tree by this action."
1123 :group 'org-edit-structure
1124 :type 'boolean)
1126 (defcustom org-yank-adjusted-subtrees nil
1127 "Non-nil means when yanking subtrees, adjust the level.
1128 With this setting, `org-paste-subtree' is used to insert the subtree, see
1129 this function for details."
1130 :group 'org-edit-structure
1131 :type 'boolean)
1133 (defcustom org-M-RET-may-split-line '((default . t))
1134 "Non-nil means M-RET will split the line at the cursor position.
1135 When nil, it will go to the end of the line before making a
1136 new line.
1137 You may also set this option in a different way for different
1138 contexts. Valid contexts are:
1140 headline when creating a new headline
1141 item when creating a new item
1142 table in a table field
1143 default the value to be used for all contexts not explicitly
1144 customized"
1145 :group 'org-structure
1146 :group 'org-table
1147 :type '(choice
1148 (const :tag "Always" t)
1149 (const :tag "Never" nil)
1150 (repeat :greedy t :tag "Individual contexts"
1151 (cons
1152 (choice :tag "Context"
1153 (const headline)
1154 (const item)
1155 (const table)
1156 (const default))
1157 (boolean)))))
1160 (defcustom org-insert-heading-respect-content nil
1161 "Non-nil means insert new headings after the current subtree.
1162 When nil, the new heading is created directly after the current line.
1163 The commands \\[org-insert-heading-respect-content] and
1164 \\[org-insert-todo-heading-respect-content] turn this variable on
1165 for the duration of the command."
1166 :group 'org-structure
1167 :type 'boolean)
1169 (defcustom org-blank-before-new-entry '((heading . auto)
1170 (plain-list-item . auto))
1171 "Should `org-insert-heading' leave a blank line before new heading/item?
1172 The value is an alist, with `heading' and `plain-list-item' as CAR,
1173 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1174 which case Org will look at the surrounding headings/items and try to
1175 make an intelligent decision whether to insert a blank line or not.
1177 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1178 set, the setting here is ignored and no empty line is inserted, to avoid
1179 breaking the list structure."
1180 :group 'org-edit-structure
1181 :type '(list
1182 (cons (const heading)
1183 (choice (const :tag "Never" nil)
1184 (const :tag "Always" t)
1185 (const :tag "Auto" auto)))
1186 (cons (const plain-list-item)
1187 (choice (const :tag "Never" nil)
1188 (const :tag "Always" t)
1189 (const :tag "Auto" auto)))))
1191 (defcustom org-insert-heading-hook nil
1192 "Hook being run after inserting a new heading."
1193 :group 'org-edit-structure
1194 :type 'hook)
1196 (defcustom org-enable-fixed-width-editor t
1197 "Non-nil means lines starting with \":\" are treated as fixed-width.
1198 This currently only means they are never auto-wrapped.
1199 When nil, such lines will be treated like ordinary lines.
1200 See also the QUOTE keyword."
1201 :group 'org-edit-structure
1202 :type 'boolean)
1204 (defcustom org-goto-auto-isearch t
1205 "Non-nil means typing characters in `org-goto' starts incremental search."
1206 :group 'org-edit-structure
1207 :type 'boolean)
1209 (defgroup org-sparse-trees nil
1210 "Options concerning sparse trees in Org-mode."
1211 :tag "Org Sparse Trees"
1212 :group 'org-structure)
1214 (defcustom org-highlight-sparse-tree-matches t
1215 "Non-nil means highlight all matches that define a sparse tree.
1216 The highlights will automatically disappear the next time the buffer is
1217 changed by an edit command."
1218 :group 'org-sparse-trees
1219 :type 'boolean)
1221 (defcustom org-remove-highlights-with-change t
1222 "Non-nil means any change to the buffer will remove temporary highlights.
1223 Such highlights are created by `org-occur' and `org-clock-display'.
1224 When nil, `C-c C-c needs to be used to get rid of the highlights.
1225 The highlights created by `org-preview-latex-fragment' always need
1226 `C-c C-c' to be removed."
1227 :group 'org-sparse-trees
1228 :group 'org-time
1229 :type 'boolean)
1232 (defcustom org-occur-hook '(org-first-headline-recenter)
1233 "Hook that is run after `org-occur' has constructed a sparse tree.
1234 This can be used to recenter the window to show as much of the structure
1235 as possible."
1236 :group 'org-sparse-trees
1237 :type 'hook)
1239 (defgroup org-imenu-and-speedbar nil
1240 "Options concerning imenu and speedbar in Org-mode."
1241 :tag "Org Imenu and Speedbar"
1242 :group 'org-structure)
1244 (defcustom org-imenu-depth 2
1245 "The maximum level for Imenu access to Org-mode headlines.
1246 This also applied for speedbar access."
1247 :group 'org-imenu-and-speedbar
1248 :type 'integer)
1250 (defgroup org-table nil
1251 "Options concerning tables in Org-mode."
1252 :tag "Org Table"
1253 :group 'org)
1255 (defcustom org-enable-table-editor 'optimized
1256 "Non-nil means lines starting with \"|\" are handled by the table editor.
1257 When nil, such lines will be treated like ordinary lines.
1259 When equal to the symbol `optimized', the table editor will be optimized to
1260 do the following:
1261 - Automatic overwrite mode in front of whitespace in table fields.
1262 This makes the structure of the table stay in tact as long as the edited
1263 field does not exceed the column width.
1264 - Minimize the number of realigns. Normally, the table is aligned each time
1265 TAB or RET are pressed to move to another field. With optimization this
1266 happens only if changes to a field might have changed the column width.
1267 Optimization requires replacing the functions `self-insert-command',
1268 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1269 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1270 very good at guessing when a re-align will be necessary, but you can always
1271 force one with \\[org-ctrl-c-ctrl-c].
1273 If you would like to use the optimized version in Org-mode, but the
1274 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1276 This variable can be used to turn on and off the table editor during a session,
1277 but in order to toggle optimization, a restart is required.
1279 See also the variable `org-table-auto-blank-field'."
1280 :group 'org-table
1281 :type '(choice
1282 (const :tag "off" nil)
1283 (const :tag "on" t)
1284 (const :tag "on, optimized" optimized)))
1286 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1287 (version<= emacs-version "24.1"))
1288 "Non-nil means cluster self-insert commands for undo when possible.
1289 If this is set, then, like in the Emacs command loop, 20 consecutive
1290 characters will be undone together.
1291 This is configurable, because there is some impact on typing performance."
1292 :group 'org-table
1293 :type 'boolean)
1295 (defcustom org-table-tab-recognizes-table.el t
1296 "Non-nil means TAB will automatically notice a table.el table.
1297 When it sees such a table, it moves point into it and - if necessary -
1298 calls `table-recognize-table'."
1299 :group 'org-table-editing
1300 :type 'boolean)
1302 (defgroup org-link nil
1303 "Options concerning links in Org-mode."
1304 :tag "Org Link"
1305 :group 'org)
1307 (defvar org-link-abbrev-alist-local nil
1308 "Buffer-local version of `org-link-abbrev-alist', which see.
1309 The value of this is taken from the #+LINK lines.")
1310 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1312 (defcustom org-link-abbrev-alist nil
1313 "Alist of link abbreviations.
1314 The car of each element is a string, to be replaced at the start of a link.
1315 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1316 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1318 [[linkkey:tag][description]]
1320 The 'linkkey' must be a word word, starting with a letter, followed
1321 by letters, numbers, '-' or '_'.
1323 If REPLACE is a string, the tag will simply be appended to create the link.
1324 If the string contains \"%s\", the tag will be inserted there. If the string
1325 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1326 at that point (see the function `url-hexify-string'). If the string contains
1327 the specifier \"%(my-function)\", then the custom function `my-function' will
1328 be invoked: this function takes the tag as its only argument and must return
1329 a string.
1331 REPLACE may also be a function that will be called with the tag as the
1332 only argument to create the link, which should be returned as a string.
1334 See the manual for examples."
1335 :group 'org-link
1336 :type '(repeat
1337 (cons
1338 (string :tag "Protocol")
1339 (choice
1340 (string :tag "Format")
1341 (function)))))
1343 (defcustom org-descriptive-links t
1344 "Non-nil means Org will display descriptive links.
1345 E.g. [[http://orgmode.org][Org website]] will be displayed as
1346 \"Org Website\", hiding the link itself and just displaying its
1347 description. When set to `nil', Org will display the full links
1348 literally.
1350 You can interactively set the value of this variable by calling
1351 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1352 :group 'org-link
1353 :type 'boolean)
1355 (defcustom org-link-file-path-type 'adaptive
1356 "How the path name in file links should be stored.
1357 Valid values are:
1359 relative Relative to the current directory, i.e. the directory of the file
1360 into which the link is being inserted.
1361 absolute Absolute path, if possible with ~ for home directory.
1362 noabbrev Absolute path, no abbreviation of home directory.
1363 adaptive Use relative path for files in the current directory and sub-
1364 directories of it. For other files, use an absolute path."
1365 :group 'org-link
1366 :type '(choice
1367 (const relative)
1368 (const absolute)
1369 (const noabbrev)
1370 (const adaptive)))
1372 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1373 "Types of links that should be activated in Org-mode files.
1374 This is a list of symbols, each leading to the activation of a certain link
1375 type. In principle, it does not hurt to turn on most link types - there may
1376 be a small gain when turning off unused link types. The types are:
1378 bracket The recommended [[link][description]] or [[link]] links with hiding.
1379 angle Links in angular brackets that may contain whitespace like
1380 <bbdb:Carsten Dominik>.
1381 plain Plain links in normal text, no whitespace, like http://google.com.
1382 radio Text that is matched by a radio target, see manual for details.
1383 tag Tag settings in a headline (link to tag search).
1384 date Time stamps (link to calendar).
1385 footnote Footnote labels.
1387 Changing this variable requires a restart of Emacs to become effective."
1388 :group 'org-link
1389 :type '(set :greedy t
1390 (const :tag "Double bracket links" bracket)
1391 (const :tag "Angular bracket links" angle)
1392 (const :tag "Plain text links" plain)
1393 (const :tag "Radio target matches" radio)
1394 (const :tag "Tags" tag)
1395 (const :tag "Timestamps" date)
1396 (const :tag "Footnotes" footnote)))
1398 (defcustom org-make-link-description-function nil
1399 "Function to use to generate link descriptions from links.
1400 If nil the link location will be used. This function must take
1401 two parameters; the first is the link and the second the
1402 description `org-insert-link' has generated, and should return the
1403 description to use."
1404 :group 'org-link
1405 :type 'function)
1407 (defgroup org-link-store nil
1408 "Options concerning storing links in Org-mode."
1409 :tag "Org Store Link"
1410 :group 'org-link)
1412 (defcustom org-url-hexify-p t
1413 "When non-nil, hexify URL when creating a link."
1414 :type 'boolean
1415 ;; :version "24.3"
1416 :group 'org-link-store)
1418 (defcustom org-email-link-description-format "Email %c: %.30s"
1419 "Format of the description part of a link to an email or usenet message.
1420 The following %-escapes will be replaced by corresponding information:
1422 %F full \"From\" field
1423 %f name, taken from \"From\" field, address if no name
1424 %T full \"To\" field
1425 %t first name in \"To\" field, address if no name
1426 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1427 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1428 %s subject
1429 %d date
1430 %m message-id.
1432 You may use normal field width specification between the % and the letter.
1433 This is for example useful to limit the length of the subject.
1435 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1436 :group 'org-link-store
1437 :type 'string)
1439 (defcustom org-from-is-user-regexp
1440 (let (r1 r2)
1441 (when (and user-mail-address (not (string= user-mail-address "")))
1442 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1443 (when (and user-full-name (not (string= user-full-name "")))
1444 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1445 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1446 "Regexp matched against the \"From:\" header of an email or usenet message.
1447 It should match if the message is from the user him/herself."
1448 :group 'org-link-store
1449 :type 'regexp)
1451 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1452 "Non-nil means storing a link to an Org file will use entry IDs.
1454 Note that before this variable is even considered, org-id must be loaded,
1455 so please customize `org-modules' and turn it on.
1457 The variable can have the following values:
1459 t Create an ID if needed to make a link to the current entry.
1461 create-if-interactive
1462 If `org-store-link' is called directly (interactively, as a user
1463 command), do create an ID to support the link. But when doing the
1464 job for remember, only use the ID if it already exists. The
1465 purpose of this setting is to avoid proliferation of unwanted
1466 IDs, just because you happen to be in an Org file when you
1467 call `org-capture' that automatically and preemptively creates a
1468 link. If you do want to get an ID link in a remember template to
1469 an entry not having an ID, create it first by explicitly creating
1470 a link to it, using `C-c C-l' first.
1472 create-if-interactive-and-no-custom-id
1473 Like create-if-interactive, but do not create an ID if there is
1474 a CUSTOM_ID property defined in the entry. This is the default.
1476 use-existing
1477 Use existing ID, do not create one.
1479 nil Never use an ID to make a link, instead link using a text search for
1480 the headline text."
1481 :group 'org-link-store
1482 :type '(choice
1483 (const :tag "Create ID to make link" t)
1484 (const :tag "Create if storing link interactively"
1485 create-if-interactive)
1486 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1487 create-if-interactive-and-no-custom-id)
1488 (const :tag "Only use existing" use-existing)
1489 (const :tag "Do not use ID to create link" nil)))
1491 (defcustom org-context-in-file-links t
1492 "Non-nil means file links from `org-store-link' contain context.
1493 A search string will be added to the file name with :: as separator and
1494 used to find the context when the link is activated by the command
1495 `org-open-at-point'. When this option is t, the entire active region
1496 will be placed in the search string of the file link. If set to a
1497 positive integer, only the first n lines of context will be stored.
1499 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1500 negates this setting for the duration of the command."
1501 :group 'org-link-store
1502 :type '(choice boolean integer))
1504 (defcustom org-keep-stored-link-after-insertion nil
1505 "Non-nil means keep link in list for entire session.
1507 The command `org-store-link' adds a link pointing to the current
1508 location to an internal list. These links accumulate during a session.
1509 The command `org-insert-link' can be used to insert links into any
1510 Org-mode file (offering completion for all stored links). When this
1511 option is nil, every link which has been inserted once using \\[org-insert-link]
1512 will be removed from the list, to make completing the unused links
1513 more efficient."
1514 :group 'org-link-store
1515 :type 'boolean)
1517 (defgroup org-link-follow nil
1518 "Options concerning following links in Org-mode."
1519 :tag "Org Follow Link"
1520 :group 'org-link)
1522 (defcustom org-link-translation-function nil
1523 "Function to translate links with different syntax to Org syntax.
1524 This can be used to translate links created for example by the Planner
1525 or emacs-wiki packages to Org syntax.
1526 The function must accept two parameters, a TYPE containing the link
1527 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1528 which is everything after the link protocol. It should return a cons
1529 with possibly modified values of type and path.
1530 Org contains a function for this, so if you set this variable to
1531 `org-translate-link-from-planner', you should be able follow many
1532 links created by planner."
1533 :group 'org-link-follow
1534 :type 'function)
1536 (defcustom org-follow-link-hook nil
1537 "Hook that is run after a link has been followed."
1538 :group 'org-link-follow
1539 :type 'hook)
1541 (defcustom org-tab-follows-link nil
1542 "Non-nil means on links TAB will follow the link.
1543 Needs to be set before org.el is loaded.
1544 This really should not be used, it does not make sense, and the
1545 implementation is bad."
1546 :group 'org-link-follow
1547 :type 'boolean)
1549 (defcustom org-return-follows-link nil
1550 "Non-nil means on links RET will follow the link."
1551 :group 'org-link-follow
1552 :type 'boolean)
1554 (defcustom org-mouse-1-follows-link
1555 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1556 "Non-nil means mouse-1 on a link will follow the link.
1557 A longer mouse click will still set point. Does not work on XEmacs.
1558 Needs to be set before org.el is loaded."
1559 :group 'org-link-follow
1560 :type 'boolean)
1562 (defcustom org-mark-ring-length 4
1563 "Number of different positions to be recorded in the ring.
1564 Changing this requires a restart of Emacs to work correctly."
1565 :group 'org-link-follow
1566 :type 'integer)
1568 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1569 "Non-nil means internal links in Org files must exactly match a headline.
1570 When nil, the link search tries to match a phrase with all words
1571 in the search text."
1572 :group 'org-link-follow
1573 :version "24.1"
1574 :type '(choice
1575 (const :tag "Use fuzzy text search" nil)
1576 (const :tag "Match only exact headline" t)
1577 (const :tag "Match exact headline or query to create it"
1578 query-to-create)))
1580 (defcustom org-link-frame-setup
1581 '((vm . vm-visit-folder-other-frame)
1582 (vm-imap . vm-visit-imap-folder-other-frame)
1583 (gnus . org-gnus-no-new-news)
1584 (file . find-file-other-window)
1585 (wl . wl-other-frame))
1586 "Setup the frame configuration for following links.
1587 When following a link with Emacs, it may often be useful to display
1588 this link in another window or frame. This variable can be used to
1589 set this up for the different types of links.
1590 For VM, use any of
1591 `vm-visit-folder'
1592 `vm-visit-folder-other-window'
1593 `vm-visit-folder-other-frame'
1594 For Gnus, use any of
1595 `gnus'
1596 `gnus-other-frame'
1597 `org-gnus-no-new-news'
1598 For FILE, use any of
1599 `find-file'
1600 `find-file-other-window'
1601 `find-file-other-frame'
1602 For Wanderlust use any of
1603 `wl'
1604 `wl-other-frame'
1605 For the calendar, use the variable `calendar-setup'.
1606 For BBDB, it is currently only possible to display the matches in
1607 another window."
1608 :group 'org-link-follow
1609 :type '(list
1610 (cons (const vm)
1611 (choice
1612 (const vm-visit-folder)
1613 (const vm-visit-folder-other-window)
1614 (const vm-visit-folder-other-frame)))
1615 (cons (const gnus)
1616 (choice
1617 (const gnus)
1618 (const gnus-other-frame)
1619 (const org-gnus-no-new-news)))
1620 (cons (const file)
1621 (choice
1622 (const find-file)
1623 (const find-file-other-window)
1624 (const find-file-other-frame)))
1625 (cons (const wl)
1626 (choice
1627 (const wl)
1628 (const wl-other-frame)))))
1630 (defcustom org-display-internal-link-with-indirect-buffer nil
1631 "Non-nil means use indirect buffer to display infile links.
1632 Activating internal links (from one location in a file to another location
1633 in the same file) normally just jumps to the location. When the link is
1634 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1635 is displayed in
1636 another window. When this option is set, the other window actually displays
1637 an indirect buffer clone of the current buffer, to avoid any visibility
1638 changes to the current buffer."
1639 :group 'org-link-follow
1640 :type 'boolean)
1642 (defcustom org-open-non-existing-files nil
1643 "Non-nil means `org-open-file' will open non-existing files.
1644 When nil, an error will be generated.
1645 This variable applies only to external applications because they
1646 might choke on non-existing files. If the link is to a file that
1647 will be opened in Emacs, the variable is ignored."
1648 :group 'org-link-follow
1649 :type 'boolean)
1651 (defcustom org-open-directory-means-index-dot-org nil
1652 "Non-nil means a link to a directory really means to index.org.
1653 When nil, following a directory link will run dired or open a finder/explorer
1654 window on that directory."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1659 "Function and arguments to call for following mailto links.
1660 This is a list with the first element being a Lisp function, and the
1661 remaining elements being arguments to the function. In string arguments,
1662 %a will be replaced by the address, and %s will be replaced by the subject
1663 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1664 :group 'org-link-follow
1665 :type '(choice
1666 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1667 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1668 (const :tag "message-mail" (message-mail "%a" "%s"))
1669 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1671 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1672 "Non-nil means ask for confirmation before executing shell links.
1673 Shell links can be dangerous: just think about a link
1675 [[shell:rm -rf ~/*][Google Search]]
1677 This link would show up in your Org-mode document as \"Google Search\",
1678 but really it would remove your entire home directory.
1679 Therefore we advise against setting this variable to nil.
1680 Just change it to `y-or-n-p' if you want to confirm with a
1681 single keystroke rather than having to type \"yes\"."
1682 :group 'org-link-follow
1683 :type '(choice
1684 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1685 (const :tag "with y-or-n (faster)" y-or-n-p)
1686 (const :tag "no confirmation (dangerous)" nil)))
1687 (put 'org-confirm-shell-link-function
1688 'safe-local-variable
1689 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1691 (defcustom org-confirm-shell-link-not-regexp ""
1692 "A regexp to skip confirmation for shell links."
1693 :group 'org-link-follow
1694 :version "24.1"
1695 :type 'regexp)
1697 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1698 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1699 Elisp links can be dangerous: just think about a link
1701 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1703 This link would show up in your Org-mode document as \"Google Search\",
1704 but really it would remove your entire home directory.
1705 Therefore we advise against setting this variable to nil.
1706 Just change it to `y-or-n-p' if you want to confirm with a
1707 single keystroke rather than having to type \"yes\"."
1708 :group 'org-link-follow
1709 :type '(choice
1710 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1711 (const :tag "with y-or-n (faster)" y-or-n-p)
1712 (const :tag "no confirmation (dangerous)" nil)))
1713 (put 'org-confirm-shell-link-function
1714 'safe-local-variable
1715 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1717 (defcustom org-confirm-elisp-link-not-regexp ""
1718 "A regexp to skip confirmation for Elisp links."
1719 :group 'org-link-follow
1720 :version "24.1"
1721 :type 'regexp)
1723 (defconst org-file-apps-defaults-gnu
1724 '((remote . emacs)
1725 (system . mailcap)
1726 (t . mailcap))
1727 "Default file applications on a UNIX or GNU/Linux system.
1728 See `org-file-apps'.")
1730 (defconst org-file-apps-defaults-macosx
1731 '((remote . emacs)
1732 (t . "open %s")
1733 (system . "open %s")
1734 ("ps.gz" . "gv %s")
1735 ("eps.gz" . "gv %s")
1736 ("dvi" . "xdvi %s")
1737 ("fig" . "xfig %s"))
1738 "Default file applications on a MacOS X system.
1739 The system \"open\" is known as a default, but we use X11 applications
1740 for some files for which the OS does not have a good default.
1741 See `org-file-apps'.")
1743 (defconst org-file-apps-defaults-windowsnt
1744 (list
1745 '(remote . emacs)
1746 (cons t
1747 (list (if (featurep 'xemacs)
1748 'mswindows-shell-execute
1749 'w32-shell-execute)
1750 "open" 'file))
1751 (cons 'system
1752 (list (if (featurep 'xemacs)
1753 'mswindows-shell-execute
1754 'w32-shell-execute)
1755 "open" 'file)))
1756 "Default file applications on a Windows NT system.
1757 The system \"open\" is used for most files.
1758 See `org-file-apps'.")
1760 (defcustom org-file-apps
1762 (auto-mode . emacs)
1763 ("\\.mm\\'" . default)
1764 ("\\.x?html?\\'" . default)
1765 ("\\.pdf\\'" . default)
1767 "External applications for opening `file:path' items in a document.
1768 Org-mode uses system defaults for different file types, but
1769 you can use this variable to set the application for a given file
1770 extension. The entries in this list are cons cells where the car identifies
1771 files and the cdr the corresponding command. Possible values for the
1772 file identifier are
1773 \"string\" A string as a file identifier can be interpreted in different
1774 ways, depending on its contents:
1776 - Alphanumeric characters only:
1777 Match links with this file extension.
1778 Example: (\"pdf\" . \"evince %s\")
1779 to open PDFs with evince.
1781 - Regular expression: Match links where the
1782 filename matches the regexp. If you want to
1783 use groups here, use shy groups.
1785 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1786 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1787 to open *.html and *.xhtml with firefox.
1789 - Regular expression which contains (non-shy) groups:
1790 Match links where the whole link, including \"::\", and
1791 anything after that, matches the regexp.
1792 In a custom command string, %1, %2, etc. are replaced with
1793 the parts of the link that were matched by the groups.
1794 For backwards compatibility, if a command string is given
1795 that does not use any of the group matches, this case is
1796 handled identically to the second one (i.e. match against
1797 file name only).
1798 In a custom lisp form, you can access the group matches with
1799 (match-string n link).
1801 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1802 to open [[file:document.pdf::5]] with evince at page 5.
1804 `directory' Matches a directory
1805 `remote' Matches a remote file, accessible through tramp or efs.
1806 Remote files most likely should be visited through Emacs
1807 because external applications cannot handle such paths.
1808 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1809 so all files Emacs knows how to handle. Using this with
1810 command `emacs' will open most files in Emacs. Beware that this
1811 will also open html files inside Emacs, unless you add
1812 (\"html\" . default) to the list as well.
1813 t Default for files not matched by any of the other options.
1814 `system' The system command to open files, like `open' on Windows
1815 and Mac OS X, and mailcap under GNU/Linux. This is the command
1816 that will be selected if you call `C-c C-o' with a double
1817 \\[universal-argument] \\[universal-argument] prefix.
1819 Possible values for the command are:
1820 `emacs' The file will be visited by the current Emacs process.
1821 `default' Use the default application for this file type, which is the
1822 association for t in the list, most likely in the system-specific
1823 part.
1824 This can be used to overrule an unwanted setting in the
1825 system-specific variable.
1826 `system' Use the system command for opening files, like \"open\".
1827 This command is specified by the entry whose car is `system'.
1828 Most likely, the system-specific version of this variable
1829 does define this command, but you can overrule/replace it
1830 here.
1831 string A command to be executed by a shell; %s will be replaced
1832 by the path to the file.
1833 sexp A Lisp form which will be evaluated. The file path will
1834 be available in the Lisp variable `file'.
1835 For more examples, see the system specific constants
1836 `org-file-apps-defaults-macosx'
1837 `org-file-apps-defaults-windowsnt'
1838 `org-file-apps-defaults-gnu'."
1839 :group 'org-link-follow
1840 :type '(repeat
1841 (cons (choice :value ""
1842 (string :tag "Extension")
1843 (const :tag "System command to open files" system)
1844 (const :tag "Default for unrecognized files" t)
1845 (const :tag "Remote file" remote)
1846 (const :tag "Links to a directory" directory)
1847 (const :tag "Any files that have Emacs modes"
1848 auto-mode))
1849 (choice :value ""
1850 (const :tag "Visit with Emacs" emacs)
1851 (const :tag "Use default" default)
1852 (const :tag "Use the system command" system)
1853 (string :tag "Command")
1854 (sexp :tag "Lisp form")))))
1856 (defcustom org-doi-server-url "http://dx.doi.org/"
1857 "The URL of the DOI server."
1858 :type 'string
1859 ;; :version "24.3"
1860 :group 'org-link-follow)
1862 (defgroup org-refile nil
1863 "Options concerning refiling entries in Org-mode."
1864 :tag "Org Refile"
1865 :group 'org)
1867 (defcustom org-directory "~/org"
1868 "Directory with org files.
1869 This is just a default location to look for Org files. There is no need
1870 at all to put your files into this directory. It is only used in the
1871 following situations:
1873 1. When a remember template specifies a target file that is not an
1874 absolute path. The path will then be interpreted relative to
1875 `org-directory'
1876 2. When a remember note is filed away in an interactive way (when exiting the
1877 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1878 with `org-directory' as the default path."
1879 :group 'org-refile
1880 :group 'org-remember
1881 :type 'directory)
1883 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1884 "Default target for storing notes.
1885 Used as a fall back file for org-remember.el and org-capture.el, for
1886 templates that do not specify a target file."
1887 :group 'org-refile
1888 :group 'org-remember
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-refile
1919 :type '(choice
1920 (const :tag "Reverse always" t)
1921 (const :tag "Reverse never" nil)
1922 (repeat :tag "By file name regexp"
1923 (cons regexp boolean))))
1925 (defcustom org-log-refile nil
1926 "Information to record when a task is refiled.
1928 Possible values are:
1930 nil Don't add anything
1931 time Add a time stamp to the task
1932 note Prompt for a note and add it with template `org-log-note-headings'
1934 This option can also be set with on a per-file-basis with
1936 #+STARTUP: nologrefile
1937 #+STARTUP: logrefile
1938 #+STARTUP: lognoterefile
1940 You can have local logging settings for a subtree by setting the LOGGING
1941 property to one or more of these keywords.
1943 When bulk-refiling from the agenda, the value `note' is forbidden and
1944 will temporarily be changed to `time'."
1945 :group 'org-refile
1946 :group 'org-progress
1947 :version "24.1"
1948 :type '(choice
1949 (const :tag "No logging" nil)
1950 (const :tag "Record timestamp" time)
1951 (const :tag "Record timestamp with note." note)))
1953 (defcustom org-refile-targets nil
1954 "Targets for refiling entries with \\[org-refile].
1955 This is a list of cons cells. Each cell contains:
1956 - a specification of the files to be considered, either a list of files,
1957 or a symbol whose function or variable value will be used to retrieve
1958 a file name or a list of file names. If you use `org-agenda-files' for
1959 that, all agenda files will be scanned for targets. Nil means consider
1960 headings in the current buffer.
1961 - A specification of how to find candidate refile targets. This may be
1962 any of:
1963 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1964 This tag has to be present in all target headlines, inheritance will
1965 not be considered.
1966 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1967 todo keyword.
1968 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1969 headlines that are refiling targets.
1970 - a cons cell (:level . N). Any headline of level N is considered a target.
1971 Note that, when `org-odd-levels-only' is set, level corresponds to
1972 order in hierarchy, not to the number of stars.
1973 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1974 Note that, when `org-odd-levels-only' is set, level corresponds to
1975 order in hierarchy, not to the number of stars.
1977 Each element of this list generates a set of possible targets.
1978 The union of these sets is presented (with completion) to
1979 the user by `org-refile'.
1981 You can set the variable `org-refile-target-verify-function' to a function
1982 to verify each headline found by the simple criteria above.
1984 When this variable is nil, all top-level headlines in the current buffer
1985 are used, equivalent to the value `((nil . (:level . 1))'."
1986 :group 'org-refile
1987 :type '(repeat
1988 (cons
1989 (choice :value org-agenda-files
1990 (const :tag "All agenda files" org-agenda-files)
1991 (const :tag "Current buffer" nil)
1992 (function) (variable) (file))
1993 (choice :tag "Identify target headline by"
1994 (cons :tag "Specific tag" (const :value :tag) (string))
1995 (cons :tag "TODO keyword" (const :value :todo) (string))
1996 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1997 (cons :tag "Level number" (const :value :level) (integer))
1998 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2000 (defcustom org-refile-target-verify-function nil
2001 "Function to verify if the headline at point should be a refile target.
2002 The function will be called without arguments, with point at the
2003 beginning of the headline. It should return t and leave point
2004 where it is if the headline is a valid target for refiling.
2006 If the target should not be selected, the function must return nil.
2007 In addition to this, it may move point to a place from where the search
2008 should be continued. For example, the function may decide that the entire
2009 subtree of the current entry should be excluded and move point to the end
2010 of the subtree."
2011 :group 'org-refile
2012 :type 'function)
2014 (defcustom org-refile-use-cache nil
2015 "Non-nil means cache refile targets to speed up the process.
2016 The cache for a particular file will be updated automatically when
2017 the buffer has been killed, or when any of the marker used for flagging
2018 refile targets no longer points at a live buffer.
2019 If you have added new entries to a buffer that might themselves be targets,
2020 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2021 find that easier, `C-u C-u C-u C-c C-w'."
2022 :group 'org-refile
2023 :version "24.1"
2024 :type 'boolean)
2026 (defcustom org-refile-use-outline-path nil
2027 "Non-nil means provide refile targets as paths.
2028 So a level 3 headline will be available as level1/level2/level3.
2030 When the value is `file', also include the file name (without directory)
2031 into the path. In this case, you can also stop the completion after
2032 the file name, to get entries inserted as top level in the file.
2034 When `full-file-path', include the full file path."
2035 :group 'org-refile
2036 :type '(choice
2037 (const :tag "Not" nil)
2038 (const :tag "Yes" t)
2039 (const :tag "Start with file name" file)
2040 (const :tag "Start with full file path" full-file-path)))
2042 (defcustom org-outline-path-complete-in-steps t
2043 "Non-nil means complete the outline path in hierarchical steps.
2044 When Org-mode uses the refile interface to select an outline path
2045 \(see variable `org-refile-use-outline-path'), the completion of
2046 the path can be done is a single go, or if can be done in steps down
2047 the headline hierarchy. Going in steps is probably the best if you
2048 do not use a special completion package like `ido' or `icicles'.
2049 However, when using these packages, going in one step can be very
2050 fast, while still showing the whole path to the entry."
2051 :group 'org-refile
2052 :type 'boolean)
2054 (defcustom org-refile-allow-creating-parent-nodes nil
2055 "Non-nil means allow to create new nodes as refile targets.
2056 New nodes are then created by adding \"/new node name\" to the completion
2057 of an existing node. When the value of this variable is `confirm',
2058 new node creation must be confirmed by the user (recommended)
2059 When nil, the completion must match an existing entry.
2061 Note that, if the new heading is not seen by the criteria
2062 listed in `org-refile-targets', multiple instances of the same
2063 heading would be created by trying again to file under the new
2064 heading."
2065 :group 'org-refile
2066 :type '(choice
2067 (const :tag "Never" nil)
2068 (const :tag "Always" t)
2069 (const :tag "Prompt for confirmation" confirm)))
2071 (defcustom org-refile-active-region-within-subtree nil
2072 "Non-nil means also refile active region within a subtree.
2074 By default `org-refile' doesn't allow refiling regions if they
2075 don't contain a set of subtrees, but it might be convenient to
2076 do so sometimes: in that case, the first line of the region is
2077 converted to a headline before refiling."
2078 :group 'org-refile
2079 :version "24.1"
2080 :type 'boolean)
2082 (defgroup org-todo nil
2083 "Options concerning TODO items in Org-mode."
2084 :tag "Org TODO"
2085 :group 'org)
2087 (defgroup org-progress nil
2088 "Options concerning Progress logging in Org-mode."
2089 :tag "Org Progress"
2090 :group 'org-time)
2092 (defvar org-todo-interpretation-widgets
2093 '((:tag "Sequence (cycling hits every state)" sequence)
2094 (:tag "Type (cycling directly to DONE)" type))
2095 "The available interpretation symbols for customizing `org-todo-keywords'.
2096 Interested libraries should add to this list.")
2098 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2099 "List of TODO entry keyword sequences and their interpretation.
2100 \\<org-mode-map>This is a list of sequences.
2102 Each sequence starts with a symbol, either `sequence' or `type',
2103 indicating if the keywords should be interpreted as a sequence of
2104 action steps, or as different types of TODO items. The first
2105 keywords are states requiring action - these states will select a headline
2106 for inclusion into the global TODO list Org-mode produces. If one of
2107 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2108 signify that no further action is necessary. If \"|\" is not found,
2109 the last keyword is treated as the only DONE state of the sequence.
2111 The command \\[org-todo] cycles an entry through these states, and one
2112 additional state where no keyword is present. For details about this
2113 cycling, see the manual.
2115 TODO keywords and interpretation can also be set on a per-file basis with
2116 the special #+SEQ_TODO and #+TYP_TODO lines.
2118 Each keyword can optionally specify a character for fast state selection
2119 \(in combination with the variable `org-use-fast-todo-selection')
2120 and specifiers for state change logging, using the same syntax that
2121 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2122 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2123 indicates to record a time stamp each time this state is selected.
2125 Each keyword may also specify if a timestamp or a note should be
2126 recorded when entering or leaving the state, by adding additional
2127 characters in the parenthesis after the keyword. This looks like this:
2128 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2129 record only the time of the state change. With X and Y being either
2130 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2131 Y when leaving the state if and only if the *target* state does not
2132 define X. You may omit any of the fast-selection key or X or /Y,
2133 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2135 For backward compatibility, this variable may also be just a list
2136 of keywords. In this case the interpretation (sequence or type) will be
2137 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2138 :group 'org-todo
2139 :group 'org-keywords
2140 :type '(choice
2141 (repeat :tag "Old syntax, just keywords"
2142 (string :tag "Keyword"))
2143 (repeat :tag "New syntax"
2144 (cons
2145 (choice
2146 :tag "Interpretation"
2147 ;;Quick and dirty way to see
2148 ;;`org-todo-interpretations'. This takes the
2149 ;;place of item arguments
2150 :convert-widget
2151 (lambda (widget)
2152 (widget-put widget
2153 :args (mapcar
2154 #'(lambda (x)
2155 (widget-convert
2156 (cons 'const x)))
2157 org-todo-interpretation-widgets))
2158 widget))
2159 (repeat
2160 (string :tag "Keyword"))))))
2162 (defvar org-todo-keywords-1 nil
2163 "All TODO and DONE keywords active in a buffer.")
2164 (make-variable-buffer-local 'org-todo-keywords-1)
2165 (defvar org-todo-keywords-for-agenda nil)
2166 (defvar org-done-keywords-for-agenda nil)
2167 (defvar org-drawers-for-agenda nil)
2168 (defvar org-todo-keyword-alist-for-agenda nil)
2169 (defvar org-tag-alist-for-agenda nil)
2170 (defvar org-agenda-contributing-files nil)
2171 (defvar org-not-done-keywords nil)
2172 (make-variable-buffer-local 'org-not-done-keywords)
2173 (defvar org-done-keywords nil)
2174 (make-variable-buffer-local 'org-done-keywords)
2175 (defvar org-todo-heads nil)
2176 (make-variable-buffer-local 'org-todo-heads)
2177 (defvar org-todo-sets nil)
2178 (make-variable-buffer-local 'org-todo-sets)
2179 (defvar org-todo-log-states nil)
2180 (make-variable-buffer-local 'org-todo-log-states)
2181 (defvar org-todo-kwd-alist nil)
2182 (make-variable-buffer-local 'org-todo-kwd-alist)
2183 (defvar org-todo-key-alist nil)
2184 (make-variable-buffer-local 'org-todo-key-alist)
2185 (defvar org-todo-key-trigger nil)
2186 (make-variable-buffer-local 'org-todo-key-trigger)
2188 (defcustom org-todo-interpretation 'sequence
2189 "Controls how TODO keywords are interpreted.
2190 This variable is in principle obsolete and is only used for
2191 backward compatibility, if the interpretation of todo keywords is
2192 not given already in `org-todo-keywords'. See that variable for
2193 more information."
2194 :group 'org-todo
2195 :group 'org-keywords
2196 :type '(choice (const sequence)
2197 (const type)))
2199 (defcustom org-use-fast-todo-selection t
2200 "Non-nil means use the fast todo selection scheme with C-c C-t.
2201 This variable describes if and under what circumstances the cycling
2202 mechanism for TODO keywords will be replaced by a single-key, direct
2203 selection scheme.
2205 When nil, fast selection is never used.
2207 When the symbol `prefix', it will be used when `org-todo' is called
2208 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2209 `C-u t' in an agenda buffer.
2211 When t, fast selection is used by default. In this case, the prefix
2212 argument forces cycling instead.
2214 In all cases, the special interface is only used if access keys have
2215 actually been assigned by the user, i.e. if keywords in the configuration
2216 are followed by a letter in parenthesis, like TODO(t)."
2217 :group 'org-todo
2218 :type '(choice
2219 (const :tag "Never" nil)
2220 (const :tag "By default" t)
2221 (const :tag "Only with C-u C-c C-t" prefix)))
2223 (defcustom org-provide-todo-statistics t
2224 "Non-nil means update todo statistics after insert and toggle.
2225 ALL-HEADLINES means update todo statistics by including headlines
2226 with no TODO keyword as well, counting them as not done.
2227 A list of TODO keywords means the same, but skip keywords that are
2228 not in this list.
2230 When this is set, todo statistics is updated in the parent of the
2231 current entry each time a todo state is changed."
2232 :group 'org-todo
2233 :type '(choice
2234 (const :tag "Yes, only for TODO entries" t)
2235 (const :tag "Yes, including all entries" 'all-headlines)
2236 (repeat :tag "Yes, for TODOs in this list"
2237 (string :tag "TODO keyword"))
2238 (other :tag "No TODO statistics" nil)))
2240 (defcustom org-hierarchical-todo-statistics t
2241 "Non-nil means TODO statistics covers just direct children.
2242 When nil, all entries in the subtree are considered.
2243 This has only an effect if `org-provide-todo-statistics' is set.
2244 To set this to nil for only a single subtree, use a COOKIE_DATA
2245 property and include the word \"recursive\" into the value."
2246 :group 'org-todo
2247 :type 'boolean)
2249 (defcustom org-after-todo-state-change-hook nil
2250 "Hook which is run after the state of a TODO item was changed.
2251 The new state (a string with a TODO keyword, or nil) is available in the
2252 Lisp variable `org-state'."
2253 :group 'org-todo
2254 :type 'hook)
2256 (defvar org-blocker-hook nil
2257 "Hook for functions that are allowed to block a state change.
2259 Each function gets as its single argument a property list, see
2260 `org-trigger-hook' for more information about this list.
2262 If any of the functions in this hook returns nil, the state change
2263 is blocked.")
2265 (defvar org-trigger-hook nil
2266 "Hook for functions that are triggered by a state change.
2268 Each function gets as its single argument a property list with at least
2269 the following elements:
2271 (:type type-of-change :position pos-at-entry-start
2272 :from old-state :to new-state)
2274 Depending on the type, more properties may be present.
2276 This mechanism is currently implemented for:
2278 TODO state changes
2279 ------------------
2280 :type todo-state-change
2281 :from previous state (keyword as a string), or nil, or a symbol
2282 'todo' or 'done', to indicate the general type of state.
2283 :to new state, like in :from")
2285 (defcustom org-enforce-todo-dependencies nil
2286 "Non-nil means undone TODO entries will block switching the parent to DONE.
2287 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2288 be blocked if any prior sibling is not yet done.
2289 Finally, if the parent is blocked because of ordered siblings of its own,
2290 the child will also be blocked."
2291 :set (lambda (var val)
2292 (set var val)
2293 (if val
2294 (add-hook 'org-blocker-hook
2295 'org-block-todo-from-children-or-siblings-or-parent)
2296 (remove-hook 'org-blocker-hook
2297 'org-block-todo-from-children-or-siblings-or-parent)))
2298 :group 'org-todo
2299 :type 'boolean)
2301 (defcustom org-enforce-todo-checkbox-dependencies nil
2302 "Non-nil means unchecked boxes will block switching the parent to DONE.
2303 When this is nil, checkboxes have no influence on switching TODO states.
2304 When non-nil, you first need to check off all check boxes before the TODO
2305 entry can be switched to DONE.
2306 This variable needs to be set before org.el is loaded, and you need to
2307 restart Emacs after a change to make the change effective. The only way
2308 to change is while Emacs is running is through the customize interface."
2309 :set (lambda (var val)
2310 (set var val)
2311 (if val
2312 (add-hook 'org-blocker-hook
2313 'org-block-todo-from-checkboxes)
2314 (remove-hook 'org-blocker-hook
2315 'org-block-todo-from-checkboxes)))
2316 :group 'org-todo
2317 :type 'boolean)
2319 (defcustom org-treat-insert-todo-heading-as-state-change nil
2320 "Non-nil means inserting a TODO heading is treated as state change.
2321 So when the command \\[org-insert-todo-heading] is used, state change
2322 logging will apply if appropriate. When nil, the new TODO item will
2323 be inserted directly, and no logging will take place."
2324 :group 'org-todo
2325 :type 'boolean)
2327 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2328 "Non-nil means switching TODO states with S-cursor counts as state change.
2329 This is the default behavior. However, setting this to nil allows a
2330 convenient way to select a TODO state and bypass any logging associated
2331 with that."
2332 :group 'org-todo
2333 :type 'boolean)
2335 (defcustom org-todo-state-tags-triggers nil
2336 "Tag changes that should be triggered by TODO state changes.
2337 This is a list. Each entry is
2339 (state-change (tag . flag) .......)
2341 State-change can be a string with a state, and empty string to indicate the
2342 state that has no TODO keyword, or it can be one of the symbols `todo'
2343 or `done', meaning any not-done or done state, respectively."
2344 :group 'org-todo
2345 :group 'org-tags
2346 :type '(repeat
2347 (cons (choice :tag "When changing to"
2348 (const :tag "Not-done state" todo)
2349 (const :tag "Done state" done)
2350 (string :tag "State"))
2351 (repeat
2352 (cons :tag "Tag action"
2353 (string :tag "Tag")
2354 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2356 (defcustom org-log-done nil
2357 "Information to record when a task moves to the DONE state.
2359 Possible values are:
2361 nil Don't add anything, just change the keyword
2362 time Add a time stamp to the task
2363 note Prompt for a note and add it with template `org-log-note-headings'
2365 This option can also be set with on a per-file-basis with
2367 #+STARTUP: nologdone
2368 #+STARTUP: logdone
2369 #+STARTUP: lognotedone
2371 You can have local logging settings for a subtree by setting the LOGGING
2372 property to one or more of these keywords."
2373 :group 'org-todo
2374 :group 'org-progress
2375 :type '(choice
2376 (const :tag "No logging" nil)
2377 (const :tag "Record CLOSED timestamp" time)
2378 (const :tag "Record CLOSED timestamp with note." note)))
2380 ;; Normalize old uses of org-log-done.
2381 (cond
2382 ((eq org-log-done t) (setq org-log-done 'time))
2383 ((and (listp org-log-done) (memq 'done org-log-done))
2384 (setq org-log-done 'note)))
2386 (defcustom org-log-reschedule nil
2387 "Information to record when the scheduling date of a tasks is modified.
2389 Possible values are:
2391 nil Don't add anything, just change the date
2392 time Add a time stamp to the task
2393 note Prompt for a note and add it with template `org-log-note-headings'
2395 This option can also be set with on a per-file-basis with
2397 #+STARTUP: nologreschedule
2398 #+STARTUP: logreschedule
2399 #+STARTUP: lognotereschedule"
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type '(choice
2403 (const :tag "No logging" nil)
2404 (const :tag "Record timestamp" time)
2405 (const :tag "Record timestamp with note." note)))
2407 (defcustom org-log-redeadline nil
2408 "Information to record when the deadline date of a tasks is modified.
2410 Possible values are:
2412 nil Don't add anything, just change the date
2413 time Add a time stamp to the task
2414 note Prompt for a note and add it with template `org-log-note-headings'
2416 This option can also be set with on a per-file-basis with
2418 #+STARTUP: nologredeadline
2419 #+STARTUP: logredeadline
2420 #+STARTUP: lognoteredeadline
2422 You can have local logging settings for a subtree by setting the LOGGING
2423 property to one or more of these keywords."
2424 :group 'org-todo
2425 :group 'org-progress
2426 :type '(choice
2427 (const :tag "No logging" nil)
2428 (const :tag "Record timestamp" time)
2429 (const :tag "Record timestamp with note." note)))
2431 (defcustom org-log-note-clock-out nil
2432 "Non-nil means record a note when clocking out of an item.
2433 This can also be configured on a per-file basis by adding one of
2434 the following lines anywhere in the buffer:
2436 #+STARTUP: lognoteclock-out
2437 #+STARTUP: nolognoteclock-out"
2438 :group 'org-todo
2439 :group 'org-progress
2440 :type 'boolean)
2442 (defcustom org-log-done-with-time t
2443 "Non-nil means the CLOSED time stamp will contain date and time.
2444 When nil, only the date will be recorded."
2445 :group 'org-progress
2446 :type 'boolean)
2448 (defcustom org-log-note-headings
2449 '((done . "CLOSING NOTE %t")
2450 (state . "State %-12s from %-12S %t")
2451 (note . "Note taken on %t")
2452 (reschedule . "Rescheduled from %S on %t")
2453 (delschedule . "Not scheduled, was %S on %t")
2454 (redeadline . "New deadline from %S on %t")
2455 (deldeadline . "Removed deadline, was %S on %t")
2456 (refile . "Refiled on %t")
2457 (clock-out . ""))
2458 "Headings for notes added to entries.
2459 The value is an alist, with the car being a symbol indicating the note
2460 context, and the cdr is the heading to be used. The heading may also be the
2461 empty string.
2462 %t in the heading will be replaced by a time stamp.
2463 %T will be an active time stamp instead the default inactive one
2464 %d will be replaced by a short-format time stamp.
2465 %D will be replaced by an active short-format time stamp.
2466 %s will be replaced by the new TODO state, in double quotes.
2467 %S will be replaced by the old TODO state, in double quotes.
2468 %u will be replaced by the user name.
2469 %U will be replaced by the full user name.
2471 In fact, it is not a good idea to change the `state' entry, because
2472 agenda log mode depends on the format of these entries."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(list :greedy t
2476 (cons (const :tag "Heading when closing an item" done) string)
2477 (cons (const :tag
2478 "Heading when changing todo state (todo sequence only)"
2479 state) string)
2480 (cons (const :tag "Heading when just taking a note" note) string)
2481 (cons (const :tag "Heading when clocking out" clock-out) string)
2482 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2483 (cons (const :tag "Heading when rescheduling" reschedule) string)
2484 (cons (const :tag "Heading when changing deadline" redeadline) string)
2485 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2486 (cons (const :tag "Heading when refiling" refile) string)))
2488 (unless (assq 'note org-log-note-headings)
2489 (push '(note . "%t") org-log-note-headings))
2491 (defcustom org-log-into-drawer nil
2492 "Non-nil means insert state change notes and time stamps into a drawer.
2493 When nil, state changes notes will be inserted after the headline and
2494 any scheduling and clock lines, but not inside a drawer.
2496 The value of this variable should be the name of the drawer to use.
2497 LOGBOOK is proposed as the default drawer for this purpose, you can
2498 also set this to a string to define the drawer of your choice.
2500 A value of t is also allowed, representing \"LOGBOOK\".
2502 If this variable is set, `org-log-state-notes-insert-after-drawers'
2503 will be ignored.
2505 You can set the property LOG_INTO_DRAWER to overrule this setting for
2506 a subtree."
2507 :group 'org-todo
2508 :group 'org-progress
2509 :type '(choice
2510 (const :tag "Not into a drawer" nil)
2511 (const :tag "LOGBOOK" t)
2512 (string :tag "Other")))
2514 (if (fboundp 'defvaralias)
2515 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2517 (defun org-log-into-drawer ()
2518 "Return the value of `org-log-into-drawer', but let properties overrule.
2519 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2520 used instead of the default value."
2521 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2522 (cond
2523 ((or (not p) (equal p "nil")) org-log-into-drawer)
2524 ((equal p "t") "LOGBOOK")
2525 (t p))))
2527 (defcustom org-log-state-notes-insert-after-drawers nil
2528 "Non-nil means insert state change notes after any drawers in entry.
2529 Only the drawers that *immediately* follow the headline and the
2530 deadline/scheduled line are skipped.
2531 When nil, insert notes right after the heading and perhaps the line
2532 with deadline/scheduling if present.
2534 This variable will have no effect if `org-log-into-drawer' is
2535 set."
2536 :group 'org-todo
2537 :group 'org-progress
2538 :type 'boolean)
2540 (defcustom org-log-states-order-reversed t
2541 "Non-nil means the latest state note will be directly after heading.
2542 When nil, the state change notes will be ordered according to time."
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type 'boolean)
2547 (defcustom org-todo-repeat-to-state nil
2548 "The TODO state to which a repeater should return the repeating task.
2549 By default this is the first task in a TODO sequence, or the previous state
2550 in a TODO_TYP set. But you can specify another task here.
2551 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2552 :group 'org-todo
2553 :version "24.1"
2554 :type '(choice (const :tag "Head of sequence" nil)
2555 (string :tag "Specific state")))
2557 (defcustom org-log-repeat 'time
2558 "Non-nil means record moving through the DONE state when triggering repeat.
2559 An auto-repeating task is immediately switched back to TODO when
2560 marked DONE. If you are not logging state changes (by adding \"@\"
2561 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2562 record a closing note, there will be no record of the task moving
2563 through DONE. This variable forces taking a note anyway.
2565 nil Don't force a record
2566 time Record a time stamp
2567 note Prompt for a note and add it with template `org-log-note-headings'
2569 This option can also be set with on a per-file-basis with
2571 #+STARTUP: nologrepeat
2572 #+STARTUP: logrepeat
2573 #+STARTUP: lognoterepeat
2575 You can have local logging settings for a subtree by setting the LOGGING
2576 property to one or more of these keywords."
2577 :group 'org-todo
2578 :group 'org-progress
2579 :type '(choice
2580 (const :tag "Don't force a record" nil)
2581 (const :tag "Force recording the DONE state" time)
2582 (const :tag "Force recording a note with the DONE state" note)))
2585 (defgroup org-priorities nil
2586 "Priorities in Org-mode."
2587 :tag "Org Priorities"
2588 :group 'org-todo)
2590 (defcustom org-enable-priority-commands t
2591 "Non-nil means priority commands are active.
2592 When nil, these commands will be disabled, so that you never accidentally
2593 set a priority."
2594 :group 'org-priorities
2595 :type 'boolean)
2597 (defcustom org-highest-priority ?A
2598 "The highest priority of TODO items. A character like ?A, ?B etc.
2599 Must have a smaller ASCII number than `org-lowest-priority'."
2600 :group 'org-priorities
2601 :type 'character)
2603 (defcustom org-lowest-priority ?C
2604 "The lowest priority of TODO items. A character like ?A, ?B etc.
2605 Must have a larger ASCII number than `org-highest-priority'."
2606 :group 'org-priorities
2607 :type 'character)
2609 (defcustom org-default-priority ?B
2610 "The default priority of TODO items.
2611 This is the priority an item gets if no explicit priority is given.
2612 When starting to cycle on an empty priority the first step in the cycle
2613 depends on `org-priority-start-cycle-with-default'. The resulting first
2614 step priority must not exceed the range from `org-highest-priority' to
2615 `org-lowest-priority' which means that `org-default-priority' has to be
2616 in this range exclusive or inclusive the range boundaries. Else the
2617 first step refuses to set the default and the second will fall back
2618 to (depending on the command used) the highest or lowest priority."
2619 :group 'org-priorities
2620 :type 'character)
2622 (defcustom org-priority-start-cycle-with-default t
2623 "Non-nil means start with default priority when starting to cycle.
2624 When this is nil, the first step in the cycle will be (depending on the
2625 command used) one higher or lower than the default priority.
2626 See also `org-default-priority'."
2627 :group 'org-priorities
2628 :type 'boolean)
2630 (defcustom org-get-priority-function nil
2631 "Function to extract the priority from a string.
2632 The string is normally the headline. If this is nil Org computes the
2633 priority from the priority cookie like [#A] in the headline. It returns
2634 an integer, increasing by 1000 for each priority level.
2635 The user can set a different function here, which should take a string
2636 as an argument and return the numeric priority."
2637 :group 'org-priorities
2638 :version "24.1"
2639 :type 'function)
2641 (defgroup org-time nil
2642 "Options concerning time stamps and deadlines in Org-mode."
2643 :tag "Org Time"
2644 :group 'org)
2646 (defcustom org-insert-labeled-timestamps-at-point nil
2647 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2648 When nil, these labeled time stamps are forces into the second line of an
2649 entry, just after the headline. When scheduling from the global TODO list,
2650 the time stamp will always be forced into the second line."
2651 :group 'org-time
2652 :type 'boolean)
2654 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2655 "Formats for `format-time-string' which are used for time stamps.
2656 It is not recommended to change this constant.")
2658 (defcustom org-time-stamp-rounding-minutes '(0 5)
2659 "Number of minutes to round time stamps to.
2660 These are two values, the first applies when first creating a time stamp.
2661 The second applies when changing it with the commands `S-up' and `S-down'.
2662 When changing the time stamp, this means that it will change in steps
2663 of N minutes, as given by the second value.
2665 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2666 numbers should be factors of 60, so for example 5, 10, 15.
2668 When this is larger than 1, you can still force an exact time stamp by using
2669 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2670 and by using a prefix arg to `S-up/down' to specify the exact number
2671 of minutes to shift."
2672 :group 'org-time
2673 :get #'(lambda (var) ; Make sure both elements are there
2674 (if (integerp (default-value var))
2675 (list (default-value var) 5)
2676 (default-value var)))
2677 :type '(list
2678 (integer :tag "when inserting times")
2679 (integer :tag "when modifying times")))
2681 ;; Normalize old customizations of this variable.
2682 (when (integerp org-time-stamp-rounding-minutes)
2683 (setq org-time-stamp-rounding-minutes
2684 (list org-time-stamp-rounding-minutes
2685 org-time-stamp-rounding-minutes)))
2687 (defcustom org-display-custom-times nil
2688 "Non-nil means overlay custom formats over all time stamps.
2689 The formats are defined through the variable `org-time-stamp-custom-formats'.
2690 To turn this on on a per-file basis, insert anywhere in the file:
2691 #+STARTUP: customtime"
2692 :group 'org-time
2693 :set 'set-default
2694 :type 'sexp)
2695 (make-variable-buffer-local 'org-display-custom-times)
2697 (defcustom org-time-stamp-custom-formats
2698 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2699 "Custom formats for time stamps. See `format-time-string' for the syntax.
2700 These are overlaid over the default ISO format if the variable
2701 `org-display-custom-times' is set. Time like %H:%M should be at the
2702 end of the second format. The custom formats are also honored by export
2703 commands, if custom time display is turned on at the time of export."
2704 :group 'org-time
2705 :type 'sexp)
2707 (defun org-time-stamp-format (&optional long inactive)
2708 "Get the right format for a time string."
2709 (let ((f (if long (cdr org-time-stamp-formats)
2710 (car org-time-stamp-formats))))
2711 (if inactive
2712 (concat "[" (substring f 1 -1) "]")
2713 f)))
2715 (defcustom org-time-clocksum-format "%d:%02d"
2716 "The format string used when creating CLOCKSUM lines.
2717 This is also used when org-mode generates a time duration."
2718 :group 'org-time
2719 :type 'string)
2721 (defcustom org-time-clocksum-use-fractional nil
2722 "If non-nil, \\[org-clock-display] uses fractional times.
2723 org-mode generates a time duration."
2724 :group 'org-time
2725 :type 'boolean)
2727 (defcustom org-time-clocksum-fractional-format "%.2f"
2728 "The format string used when creating CLOCKSUM lines, or when
2729 org-mode generates a time duration."
2730 :group 'org-time
2731 :type 'string)
2733 (defcustom org-deadline-warning-days 14
2734 "No. of days before expiration during which a deadline becomes active.
2735 This variable governs the display in sparse trees and in the agenda.
2736 When 0 or negative, it means use this number (the absolute value of it)
2737 even if a deadline has a different individual lead time specified.
2739 Custom commands can set this variable in the options section."
2740 :group 'org-time
2741 :group 'org-agenda-daily/weekly
2742 :type 'integer)
2744 (defcustom org-read-date-prefer-future t
2745 "Non-nil means assume future for incomplete date input from user.
2746 This affects the following situations:
2747 1. The user gives a month but not a year.
2748 For example, if it is April and you enter \"feb 2\", this will be read
2749 as Feb 2, *next* year. \"May 5\", however, will be this year.
2750 2. The user gives a day, but no month.
2751 For example, if today is the 15th, and you enter \"3\", Org-mode will
2752 read this as the third of *next* month. However, if you enter \"17\",
2753 it will be considered as *this* month.
2755 If you set this variable to the symbol `time', then also the following
2756 will work:
2758 3. If the user gives a time.
2759 If the time is before now, it will be interpreted as tomorrow.
2761 Currently none of this works for ISO week specifications.
2763 When this option is nil, the current day, month and year will always be
2764 used as defaults.
2766 See also `org-agenda-jump-prefer-future'."
2767 :group 'org-time
2768 :type '(choice
2769 (const :tag "Never" nil)
2770 (const :tag "Check month and day" t)
2771 (const :tag "Check month, day, and time" time)))
2773 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2774 "Should the agenda jump command prefer the future for incomplete dates?
2775 The default is to do the same as configured in `org-read-date-prefer-future'.
2776 But you can also set a deviating value here.
2777 This may t or nil, or the symbol `org-read-date-prefer-future'."
2778 :group 'org-agenda
2779 :group 'org-time
2780 :version "24.1"
2781 :type '(choice
2782 (const :tag "Use org-read-date-prefer-future"
2783 org-read-date-prefer-future)
2784 (const :tag "Never" nil)
2785 (const :tag "Always" t)))
2787 (defcustom org-read-date-force-compatible-dates t
2788 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2790 Depending on the system Emacs is running on, certain dates cannot
2791 be represented with the type used internally to represent time.
2792 Dates between 1970-1-1 and 2038-1-1 can always be represented
2793 correctly. Some systems allow for earlier dates, some for later,
2794 some for both. One way to find out it to insert any date into an
2795 Org buffer, putting the cursor on the year and hitting S-up and
2796 S-down to test the range.
2798 When this variable is set to t, the date/time prompt will not let
2799 you specify dates outside the 1970-2037 range, so it is certain that
2800 these dates will work in whatever version of Emacs you are
2801 running, and also that you can move a file from one Emacs implementation
2802 to another. WHenever Org is forcing the year for you, it will display
2803 a message and beep.
2805 When this variable is nil, Org will check if the date is
2806 representable in the specific Emacs implementation you are using.
2807 If not, it will force a year, usually the current year, and beep
2808 to remind you. Currently this setting is not recommended because
2809 the likelihood that you will open your Org files in an Emacs that
2810 has limited date range is not negligible.
2812 A workaround for this problem is to use diary sexp dates for time
2813 stamps outside of this range."
2814 :group 'org-time
2815 :version "24.1"
2816 :type 'boolean)
2818 (defcustom org-read-date-display-live t
2819 "Non-nil means display current interpretation of date prompt live.
2820 This display will be in an overlay, in the minibuffer."
2821 :group 'org-time
2822 :type 'boolean)
2824 (defcustom org-read-date-popup-calendar t
2825 "Non-nil means pop up a calendar when prompting for a date.
2826 In the calendar, the date can be selected with mouse-1. However, the
2827 minibuffer will also be active, and you can simply enter the date as well.
2828 When nil, only the minibuffer will be available."
2829 :group 'org-time
2830 :type 'boolean)
2831 (if (fboundp 'defvaralias)
2832 (defvaralias 'org-popup-calendar-for-date-prompt
2833 'org-read-date-popup-calendar))
2835 (defcustom org-read-date-minibuffer-setup-hook nil
2836 "Hook to be used to set up keys for the date/time interface.
2837 Add key definitions to `minibuffer-local-map', which will be a temporary
2838 copy."
2839 :group 'org-time
2840 :type 'hook)
2842 (defcustom org-extend-today-until 0
2843 "The hour when your day really ends. Must be an integer.
2844 This has influence for the following applications:
2845 - When switching the agenda to \"today\". It it is still earlier than
2846 the time given here, the day recognized as TODAY is actually yesterday.
2847 - When a date is read from the user and it is still before the time given
2848 here, the current date and time will be assumed to be yesterday, 23:59.
2849 Also, timestamps inserted in remember templates follow this rule.
2851 IMPORTANT: This is a feature whose implementation is and likely will
2852 remain incomplete. Really, it is only here because past midnight seems to
2853 be the favorite working time of John Wiegley :-)"
2854 :group 'org-time
2855 :type 'integer)
2857 (defcustom org-use-effective-time nil
2858 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2859 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2860 \"effective time\" of any timestamps between midnight and 8am will be
2861 23:59 of the previous day."
2862 :group 'org-time
2863 :version "24.1"
2864 :type 'boolean)
2866 (defcustom org-edit-timestamp-down-means-later nil
2867 "Non-nil means S-down will increase the time in a time stamp.
2868 When nil, S-up will increase."
2869 :group 'org-time
2870 :type 'boolean)
2872 (defcustom org-calendar-follow-timestamp-change t
2873 "Non-nil means make the calendar window follow timestamp changes.
2874 When a timestamp is modified and the calendar window is visible, it will be
2875 moved to the new date."
2876 :group 'org-time
2877 :type 'boolean)
2879 (defgroup org-tags nil
2880 "Options concerning tags in Org-mode."
2881 :tag "Org Tags"
2882 :group 'org)
2884 (defcustom org-tag-alist nil
2885 "List of tags allowed in Org-mode files.
2886 When this list is nil, Org-mode will base TAG input on what is already in the
2887 buffer.
2888 The value of this variable is an alist, the car of each entry must be a
2889 keyword as a string, the cdr may be a character that is used to select
2890 that tag through the fast-tag-selection interface.
2891 See the manual for details."
2892 :group 'org-tags
2893 :type '(repeat
2894 (choice
2895 (cons (string :tag "Tag name")
2896 (character :tag "Access char"))
2897 (list :tag "Start radio group"
2898 (const :startgroup)
2899 (option (string :tag "Group description")))
2900 (list :tag "End radio group"
2901 (const :endgroup)
2902 (option (string :tag "Group description")))
2903 (const :tag "New line" (:newline)))))
2905 (defcustom org-tag-persistent-alist nil
2906 "List of tags that will always appear in all Org-mode files.
2907 This is in addition to any in buffer settings or customizations
2908 of `org-tag-alist'.
2909 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2910 The value of this variable is an alist, the car of each entry must be a
2911 keyword as a string, the cdr may be a character that is used to select
2912 that tag through the fast-tag-selection interface.
2913 See the manual for details.
2914 To disable these tags on a per-file basis, insert anywhere in the file:
2915 #+STARTUP: noptag"
2916 :group 'org-tags
2917 :type '(repeat
2918 (choice
2919 (cons (string :tag "Tag name")
2920 (character :tag "Access char"))
2921 (const :tag "Start radio group" (:startgroup))
2922 (const :tag "End radio group" (:endgroup))
2923 (const :tag "New line" (:newline)))))
2925 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2926 "If non-nil, always offer completion for all tags of all agenda files.
2927 Instead of customizing this variable directly, you might want to
2928 set it locally for capture buffers, because there no list of
2929 tags in that file can be created dynamically (there are none).
2931 (add-hook 'org-capture-mode-hook
2932 (lambda ()
2933 (set (make-local-variable
2934 'org-complete-tags-always-offer-all-agenda-tags)
2935 t)))"
2936 :group 'org-tags
2937 :version "24.1"
2938 :type 'boolean)
2940 (defvar org-file-tags nil
2941 "List of tags that can be inherited by all entries in the file.
2942 The tags will be inherited if the variable `org-use-tag-inheritance'
2943 says they should be.
2944 This variable is populated from #+FILETAGS lines.")
2946 (defcustom org-use-fast-tag-selection 'auto
2947 "Non-nil means use fast tag selection scheme.
2948 This is a special interface to select and deselect tags with single keys.
2949 When nil, fast selection is never used.
2950 When the symbol `auto', fast selection is used if and only if selection
2951 characters for tags have been configured, either through the variable
2952 `org-tag-alist' or through a #+TAGS line in the buffer.
2953 When t, fast selection is always used and selection keys are assigned
2954 automatically if necessary."
2955 :group 'org-tags
2956 :type '(choice
2957 (const :tag "Always" t)
2958 (const :tag "Never" nil)
2959 (const :tag "When selection characters are configured" 'auto)))
2961 (defcustom org-fast-tag-selection-single-key nil
2962 "Non-nil means fast tag selection exits after first change.
2963 When nil, you have to press RET to exit it.
2964 During fast tag selection, you can toggle this flag with `C-c'.
2965 This variable can also have the value `expert'. In this case, the window
2966 displaying the tags menu is not even shown, until you press C-c again."
2967 :group 'org-tags
2968 :type '(choice
2969 (const :tag "No" nil)
2970 (const :tag "Yes" t)
2971 (const :tag "Expert" expert)))
2973 (defvar org-fast-tag-selection-include-todo nil
2974 "Non-nil means fast tags selection interface will also offer TODO states.
2975 This is an undocumented feature, you should not rely on it.")
2977 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2978 "The column to which tags should be indented in a headline.
2979 If this number is positive, it specifies the column. If it is negative,
2980 it means that the tags should be flushright to that column. For example,
2981 -80 works well for a normal 80 character screen.
2982 When 0, place tags directly after headline text, with only one space in
2983 between."
2984 :group 'org-tags
2985 :type 'integer)
2987 (defcustom org-auto-align-tags t
2988 "Non-nil keeps tags aligned when modifying headlines.
2989 Some operations (i.e. demoting) change the length of a headline and
2990 therefore shift the tags around. With this option turned on, after
2991 each such operation the tags are again aligned to `org-tags-column'."
2992 :group 'org-tags
2993 :type 'boolean)
2995 (defcustom org-use-tag-inheritance t
2996 "Non-nil means tags in levels apply also for sublevels.
2997 When nil, only the tags directly given in a specific line apply there.
2998 This may also be a list of tags that should be inherited, or a regexp that
2999 matches tags that should be inherited. Additional control is possible
3000 with the variable `org-tags-exclude-from-inheritance' which gives an
3001 explicit list of tags to be excluded from inheritance., even if the value of
3002 `org-use-tag-inheritance' would select it for inheritance.
3004 If this option is t, a match early-on in a tree can lead to a large
3005 number of matches in the subtree when constructing the agenda or creating
3006 a sparse tree. If you only want to see the first match in a tree during
3007 a search, check out the variable `org-tags-match-list-sublevels'."
3008 :group 'org-tags
3009 :type '(choice
3010 (const :tag "Not" nil)
3011 (const :tag "Always" t)
3012 (repeat :tag "Specific tags" (string :tag "Tag"))
3013 (regexp :tag "Tags matched by regexp")))
3015 (defcustom org-tags-exclude-from-inheritance nil
3016 "List of tags that should never be inherited.
3017 This is a way to exclude a few tags from inheritance. For way to do
3018 the opposite, to actively allow inheritance for selected tags,
3019 see the variable `org-use-tag-inheritance'."
3020 :group 'org-tags
3021 :type '(repeat (string :tag "Tag")))
3023 (defun org-tag-inherit-p (tag)
3024 "Check if TAG is one that should be inherited."
3025 (cond
3026 ((member tag org-tags-exclude-from-inheritance) nil)
3027 ((eq org-use-tag-inheritance t) t)
3028 ((not org-use-tag-inheritance) nil)
3029 ((stringp org-use-tag-inheritance)
3030 (string-match org-use-tag-inheritance tag))
3031 ((listp org-use-tag-inheritance)
3032 (member tag org-use-tag-inheritance))
3033 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3035 (defcustom org-tags-match-list-sublevels t
3036 "Non-nil means list also sublevels of headlines matching a search.
3037 This variable applies to tags/property searches, and also to stuck
3038 projects because this search is based on a tags match as well.
3040 When set to the symbol `indented', sublevels are indented with
3041 leading dots.
3043 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3044 the sublevels of a headline matching a tag search often also match
3045 the same search. Listing all of them can create very long lists.
3046 Setting this variable to nil causes subtrees of a match to be skipped.
3048 This variable is semi-obsolete and probably should always be true. It
3049 is better to limit inheritance to certain tags using the variables
3050 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3051 :group 'org-tags
3052 :type '(choice
3053 (const :tag "No, don't list them" nil)
3054 (const :tag "Yes, do list them" t)
3055 (const :tag "List them, indented with leading dots" indented)))
3057 (defcustom org-tags-sort-function nil
3058 "When set, tags are sorted using this function as a comparator."
3059 :group 'org-tags
3060 :type '(choice
3061 (const :tag "No sorting" nil)
3062 (const :tag "Alphabetical" string<)
3063 (const :tag "Reverse alphabetical" string>)
3064 (function :tag "Custom function" nil)))
3066 (defvar org-tags-history nil
3067 "History of minibuffer reads for tags.")
3068 (defvar org-last-tags-completion-table nil
3069 "The last used completion table for tags.")
3070 (defvar org-after-tags-change-hook nil
3071 "Hook that is run after the tags in a line have changed.")
3073 (defgroup org-properties nil
3074 "Options concerning properties in Org-mode."
3075 :tag "Org Properties"
3076 :group 'org)
3078 (defcustom org-property-format "%-10s %s"
3079 "How property key/value pairs should be formatted by `indent-line'.
3080 When `indent-line' hits a property definition, it will format the line
3081 according to this format, mainly to make sure that the values are
3082 lined-up with respect to each other."
3083 :group 'org-properties
3084 :type 'string)
3086 (defcustom org-properties-postprocess-alist nil
3087 "Alist of properties and functions to adjust inserted values.
3088 Elements of this alist must be of the form
3090 ([string] [function])
3092 where [string] must be a property name and [function] must be a
3093 lambda expression: this lambda expression must take one argument,
3094 the value to adjust, and return the new value as a string.
3096 For example, this element will allow the property \"Remaining\"
3097 to be updated wrt the relation between the \"Effort\" property
3098 and the clock summary:
3100 ((\"Remaining\" (lambda(value)
3101 (let ((clocksum (org-clock-sum-current-item))
3102 (effort (org-duration-string-to-minutes
3103 (org-entry-get (point) \"Effort\"))))
3104 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3105 :group 'org-properties
3106 :version "24.1"
3107 :type '(alist :key-type (string :tag "Property")
3108 :value-type (function :tag "Function")))
3110 (defcustom org-use-property-inheritance nil
3111 "Non-nil means properties apply also for sublevels.
3113 This setting is chiefly used during property searches. Turning it on can
3114 cause significant overhead when doing a search, which is why it is not
3115 on by default.
3117 When nil, only the properties directly given in the current entry count.
3118 When t, every property is inherited. The value may also be a list of
3119 properties that should have inheritance, or a regular expression matching
3120 properties that should be inherited.
3122 However, note that some special properties use inheritance under special
3123 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3124 and the properties ending in \"_ALL\" when they are used as descriptor
3125 for valid values of a property.
3127 Note for programmers:
3128 When querying an entry with `org-entry-get', you can control if inheritance
3129 should be used. By default, `org-entry-get' looks only at the local
3130 properties. You can request inheritance by setting the inherit argument
3131 to t (to force inheritance) or to `selective' (to respect the setting
3132 in this variable)."
3133 :group 'org-properties
3134 :type '(choice
3135 (const :tag "Not" nil)
3136 (const :tag "Always" t)
3137 (repeat :tag "Specific properties" (string :tag "Property"))
3138 (regexp :tag "Properties matched by regexp")))
3140 (defun org-property-inherit-p (property)
3141 "Check if PROPERTY is one that should be inherited."
3142 (cond
3143 ((eq org-use-property-inheritance t) t)
3144 ((not org-use-property-inheritance) nil)
3145 ((stringp org-use-property-inheritance)
3146 (string-match org-use-property-inheritance property))
3147 ((listp org-use-property-inheritance)
3148 (member property org-use-property-inheritance))
3149 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3151 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3152 "The default column format, if no other format has been defined.
3153 This variable can be set on the per-file basis by inserting a line
3155 #+COLUMNS: %25ITEM ....."
3156 :group 'org-properties
3157 :type 'string)
3159 (defcustom org-columns-ellipses ".."
3160 "The ellipses to be used when a field in column view is truncated.
3161 When this is the empty string, as many characters as possible are shown,
3162 but then there will be no visual indication that the field has been truncated.
3163 When this is a string of length N, the last N characters of a truncated
3164 field are replaced by this string. If the column is narrower than the
3165 ellipses string, only part of the ellipses string will be shown."
3166 :group 'org-properties
3167 :type 'string)
3169 (defcustom org-columns-modify-value-for-display-function nil
3170 "Function that modifies values for display in column view.
3171 For example, it can be used to cut out a certain part from a time stamp.
3172 The function must take 2 arguments:
3174 column-title The title of the column (*not* the property name)
3175 value The value that should be modified.
3177 The function should return the value that should be displayed,
3178 or nil if the normal value should be used."
3179 :group 'org-properties
3180 :type 'function)
3182 (defcustom org-effort-property "Effort"
3183 "The property that is being used to keep track of effort estimates.
3184 Effort estimates given in this property need to have the format H:MM."
3185 :group 'org-properties
3186 :group 'org-progress
3187 :type '(string :tag "Property"))
3189 (defconst org-global-properties-fixed
3190 '(("VISIBILITY_ALL" . "folded children content all")
3191 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3192 "List of property/value pairs that can be inherited by any entry.
3194 These are fixed values, for the preset properties. The user variable
3195 that can be used to add to this list is `org-global-properties'.
3197 The entries in this list are cons cells where the car is a property
3198 name and cdr is a string with the value. If the value represents
3199 multiple items like an \"_ALL\" property, separate the items by
3200 spaces.")
3202 (defcustom org-global-properties nil
3203 "List of property/value pairs that can be inherited by any entry.
3205 This list will be combined with the constant `org-global-properties-fixed'.
3207 The entries in this list are cons cells where the car is a property
3208 name and cdr is a string with the value.
3210 You can set buffer-local values for the same purpose in the variable
3211 `org-file-properties' this by adding lines like
3213 #+PROPERTY: NAME VALUE"
3214 :group 'org-properties
3215 :type '(repeat
3216 (cons (string :tag "Property")
3217 (string :tag "Value"))))
3219 (defvar org-file-properties nil
3220 "List of property/value pairs that can be inherited by any entry.
3221 Valid for the current buffer.
3222 This variable is populated from #+PROPERTY lines.")
3223 (make-variable-buffer-local 'org-file-properties)
3225 (defgroup org-agenda nil
3226 "Options concerning agenda views in Org-mode."
3227 :tag "Org Agenda"
3228 :group 'org)
3230 (defvar org-category nil
3231 "Variable used by org files to set a category for agenda display.
3232 Such files should use a file variable to set it, for example
3234 # -*- mode: org; org-category: \"ELisp\"
3236 or contain a special line
3238 #+CATEGORY: ELisp
3240 If the file does not specify a category, then file's base name
3241 is used instead.")
3242 (make-variable-buffer-local 'org-category)
3243 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3245 (defcustom org-agenda-files nil
3246 "The files to be used for agenda display.
3247 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3248 \\[org-remove-file]. You can also use customize to edit the list.
3250 If an entry is a directory, all files in that directory that are matched by
3251 `org-agenda-file-regexp' will be part of the file list.
3253 If the value of the variable is not a list but a single file name, then
3254 the list of agenda files is actually stored and maintained in that file, one
3255 agenda file per line. In this file paths can be given relative to
3256 `org-directory'. Tilde expansion and environment variable substitution
3257 are also made."
3258 :group 'org-agenda
3259 :type '(choice
3260 (repeat :tag "List of files and directories" file)
3261 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3263 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3264 "Regular expression to match files for `org-agenda-files'.
3265 If any element in the list in that variable contains a directory instead
3266 of a normal file, all files in that directory that are matched by this
3267 regular expression will be included."
3268 :group 'org-agenda
3269 :type 'regexp)
3271 (defcustom org-agenda-text-search-extra-files nil
3272 "List of extra files to be searched by text search commands.
3273 These files will be search in addition to the agenda files by the
3274 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3275 Note that these files will only be searched for text search commands,
3276 not for the other agenda views like todo lists, tag searches or the weekly
3277 agenda. This variable is intended to list notes and possibly archive files
3278 that should also be searched by these two commands.
3279 In fact, if the first element in the list is the symbol `agenda-archives',
3280 than all archive files of all agenda files will be added to the search
3281 scope."
3282 :group 'org-agenda
3283 :type '(set :greedy t
3284 (const :tag "Agenda Archives" agenda-archives)
3285 (repeat :inline t (file))))
3287 (if (fboundp 'defvaralias)
3288 (defvaralias 'org-agenda-multi-occur-extra-files
3289 'org-agenda-text-search-extra-files))
3291 (defcustom org-agenda-skip-unavailable-files nil
3292 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3293 A nil value means to remove them, after a query, from the list."
3294 :group 'org-agenda
3295 :type 'boolean)
3297 (defcustom org-calendar-to-agenda-key [?c]
3298 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3299 The command `org-calendar-goto-agenda' will be bound to this key. The
3300 default is the character `c' because then `c' can be used to switch back and
3301 forth between agenda and calendar."
3302 :group 'org-agenda
3303 :type 'sexp)
3305 (defcustom org-calendar-agenda-action-key [?k]
3306 "The key to be installed in `calendar-mode-map' for agenda-action.
3307 The command `org-agenda-action' will be bound to this key. The
3308 default is the character `k' because we use the same key in the agenda."
3309 :group 'org-agenda
3310 :type 'sexp)
3312 (defcustom org-calendar-insert-diary-entry-key [?i]
3313 "The key to be installed in `calendar-mode-map' for adding diary entries.
3314 This option is irrelevant until `org-agenda-diary-file' has been configured
3315 to point to an Org-mode file. When that is the case, the command
3316 `org-agenda-diary-entry' will be bound to the key given here, by default
3317 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3318 if you want to continue doing this, you need to change this to a different
3319 key."
3320 :group 'org-agenda
3321 :type 'sexp)
3323 (defcustom org-agenda-diary-file 'diary-file
3324 "File to which to add new entries with the `i' key in agenda and calendar.
3325 When this is the symbol `diary-file', the functionality in the Emacs
3326 calendar will be used to add entries to the `diary-file'. But when this
3327 points to a file, `org-agenda-diary-entry' will be used instead."
3328 :group 'org-agenda
3329 :type '(choice
3330 (const :tag "The standard Emacs diary file" diary-file)
3331 (file :tag "Special Org file diary entries")))
3333 (eval-after-load "calendar"
3334 '(progn
3335 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3336 'org-calendar-goto-agenda)
3337 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3338 'org-agenda-action)
3339 (add-hook 'calendar-mode-hook
3340 (lambda ()
3341 (unless (eq org-agenda-diary-file 'diary-file)
3342 (define-key calendar-mode-map
3343 org-calendar-insert-diary-entry-key
3344 'org-agenda-diary-entry))))))
3346 (defgroup org-latex nil
3347 "Options for embedding LaTeX code into Org-mode."
3348 :tag "Org LaTeX"
3349 :group 'org)
3351 (defcustom org-format-latex-options
3352 '(:foreground default :background default :scale 1.0
3353 :html-foreground "Black" :html-background "Transparent"
3354 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3355 "Options for creating images from LaTeX fragments.
3356 This is a property list with the following properties:
3357 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3358 `default' means use the foreground of the default face.
3359 `auto' means use the foreground from the text face.
3360 :background the background color, or \"Transparent\".
3361 `default' means use the background of the default face.
3362 `auto' means use the background from the text face.
3363 :scale a scaling factor for the size of the images, to get more pixels
3364 :html-foreground, :html-background, :html-scale
3365 the same numbers for HTML export.
3366 :matchers a list indicating which matchers should be used to
3367 find LaTeX fragments. Valid members of this list are:
3368 \"begin\" find environments
3369 \"$1\" find single characters surrounded by $.$
3370 \"$\" find math expressions surrounded by $...$
3371 \"$$\" find math expressions surrounded by $$....$$
3372 \"\\(\" find math expressions surrounded by \\(...\\)
3373 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3374 :group 'org-latex
3375 :type 'plist)
3377 (defcustom org-format-latex-signal-error t
3378 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3379 When nil, just push out a message."
3380 :group 'org-latex
3381 :version "24.1"
3382 :type 'boolean)
3384 (defcustom org-latex-to-mathml-jar-file nil
3385 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3386 Use this to specify additional executable file say a jar file.
3388 When using MathToWeb as the converter, specify the full-path to
3389 your mathtoweb.jar file."
3390 :group 'org-latex
3391 :version "24.1"
3392 :type '(choice
3393 (const :tag "None" nil)
3394 (file :tag "JAR file" :must-match t)))
3396 (defcustom org-latex-to-mathml-convert-command nil
3397 "Command to convert LaTeX fragments to MathML.
3398 Replace format-specifiers in the command as noted below and use
3399 `shell-command' to convert LaTeX to MathML.
3400 %j: Executable file in fully expanded form as specified by
3401 `org-latex-to-mathml-jar-file'.
3402 %I: Input LaTeX file in fully expanded form
3403 %o: Output MathML file
3404 This command is used by `org-create-math-formula'.
3406 When using MathToWeb as the converter, set this to
3407 \"java -jar %j -unicode -force -df %o %I\"."
3408 :group 'org-latex
3409 :version "24.1"
3410 :type '(choice
3411 (const :tag "None" nil)
3412 (string :tag "\nShell command")))
3414 (defcustom org-latex-create-formula-image-program 'dvipng
3415 "Program to convert LaTeX fragments with.
3417 dvipng Process the LaTeX fragments to dvi file, then convert
3418 dvi files to png files using dvipng.
3419 This will also include processing of non-math environments.
3420 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3421 to convert pdf files to png files"
3422 :group 'org-latex
3423 :version "24.1"
3424 :type '(choice
3425 (const :tag "dvipng" dvipng)
3426 (const :tag "imagemagick" imagemagick)))
3428 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3429 "Path to store latex preview images. A relative path here creates many
3430 directories relative to the processed org files paths. An absolute path
3431 puts all preview images at the same place."
3432 :group 'org-latex
3433 ;; :version "24.3"
3434 :type 'string)
3436 (defun org-format-latex-mathml-available-p ()
3437 "Return t if `org-latex-to-mathml-convert-command' is usable."
3438 (save-match-data
3439 (when (and (boundp 'org-latex-to-mathml-convert-command)
3440 org-latex-to-mathml-convert-command)
3441 (let ((executable (car (split-string
3442 org-latex-to-mathml-convert-command))))
3443 (when (executable-find executable)
3444 (if (string-match
3445 "%j" org-latex-to-mathml-convert-command)
3446 (file-readable-p org-latex-to-mathml-jar-file)
3447 t))))))
3449 (defcustom org-format-latex-header "\\documentclass{article}
3450 \\usepackage[usenames]{color}
3451 \\usepackage{amsmath}
3452 \\usepackage[mathscr]{eucal}
3453 \\pagestyle{empty} % do not remove
3454 \[PACKAGES]
3455 \[DEFAULT-PACKAGES]
3456 % The settings below are copied from fullpage.sty
3457 \\setlength{\\textwidth}{\\paperwidth}
3458 \\addtolength{\\textwidth}{-3cm}
3459 \\setlength{\\oddsidemargin}{1.5cm}
3460 \\addtolength{\\oddsidemargin}{-2.54cm}
3461 \\setlength{\\evensidemargin}{\\oddsidemargin}
3462 \\setlength{\\textheight}{\\paperheight}
3463 \\addtolength{\\textheight}{-\\headheight}
3464 \\addtolength{\\textheight}{-\\headsep}
3465 \\addtolength{\\textheight}{-\\footskip}
3466 \\addtolength{\\textheight}{-3cm}
3467 \\setlength{\\topmargin}{1.5cm}
3468 \\addtolength{\\topmargin}{-2.54cm}"
3469 "The document header used for processing LaTeX fragments.
3470 It is imperative that this header make sure that no page number
3471 appears on the page. The package defined in the variables
3472 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3473 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3474 will be appended."
3475 :group 'org-latex
3476 :type 'string)
3478 (defvar org-format-latex-header-extra nil)
3480 (defun org-set-packages-alist (var val)
3481 "Set the packages alist and make sure it has 3 elements per entry."
3482 (set var (mapcar (lambda (x)
3483 (if (and (consp x) (= (length x) 2))
3484 (list (car x) (nth 1 x) t)
3486 val)))
3488 (defun org-get-packages-alist (var)
3490 "Get the packages alist and make sure it has 3 elements per entry."
3491 (mapcar (lambda (x)
3492 (if (and (consp x) (= (length x) 2))
3493 (list (car x) (nth 1 x) t)
3495 (default-value var)))
3497 ;; The following variables are defined here because is it also used
3498 ;; when formatting latex fragments. Originally it was part of the
3499 ;; LaTeX exporter, which is why the name includes "export".
3500 (defcustom org-export-latex-default-packages-alist
3501 '(("AUTO" "inputenc" t)
3502 ("T1" "fontenc" t)
3503 ("" "fixltx2e" nil)
3504 ("" "graphicx" t)
3505 ("" "longtable" nil)
3506 ("" "float" nil)
3507 ("" "wrapfig" nil)
3508 ("" "soul" t)
3509 ("" "textcomp" t)
3510 ("" "marvosym" t)
3511 ("" "wasysym" t)
3512 ("" "latexsym" t)
3513 ("" "amssymb" t)
3514 ("" "hyperref" nil)
3515 "\\tolerance=1000"
3517 "Alist of default packages to be inserted in the header.
3518 Change this only if one of the packages here causes an incompatibility
3519 with another package you are using.
3520 The packages in this list are needed by one part or another of Org-mode
3521 to function properly.
3523 - inputenc, fontenc: for basic font and character selection
3524 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3525 for interpreting the entities in `org-entities'. You can skip some of these
3526 packages if you don't use any of the symbols in it.
3527 - graphicx: for including images
3528 - float, wrapfig: for figure placement
3529 - longtable: for long tables
3530 - hyperref: for cross references
3532 Therefore you should not modify this variable unless you know what you
3533 are doing. The one reason to change it anyway is that you might be loading
3534 some other package that conflicts with one of the default packages.
3535 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3536 If SNIPPET-FLAG is t, the package also needs to be included when
3537 compiling LaTeX snippets into images for inclusion into HTML."
3538 :group 'org-export-latex
3539 :set 'org-set-packages-alist
3540 :get 'org-get-packages-alist
3541 :version "24.1"
3542 :type '(repeat
3543 (choice
3544 (list :tag "options/package pair"
3545 (string :tag "options")
3546 (string :tag "package")
3547 (boolean :tag "Snippet"))
3548 (string :tag "A line of LaTeX"))))
3550 (defcustom org-export-latex-packages-alist nil
3551 "Alist of packages to be inserted in every LaTeX header.
3552 These will be inserted after `org-export-latex-default-packages-alist'.
3553 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3554 SNIPPET-FLAG, when t, indicates that this package is also needed when
3555 turning LaTeX snippets into images for inclusion into HTML.
3556 Make sure that you only list packages here which:
3557 - you want in every file
3558 - do not conflict with the default packages in
3559 `org-export-latex-default-packages-alist'
3560 - do not conflict with the setup in `org-format-latex-header'."
3561 :group 'org-export-latex
3562 :set 'org-set-packages-alist
3563 :get 'org-get-packages-alist
3564 :type '(repeat
3565 (choice
3566 (list :tag "options/package pair"
3567 (string :tag "options")
3568 (string :tag "package")
3569 (boolean :tag "Snippet"))
3570 (string :tag "A line of LaTeX"))))
3573 (defgroup org-appearance nil
3574 "Settings for Org-mode appearance."
3575 :tag "Org Appearance"
3576 :group 'org)
3578 (defcustom org-level-color-stars-only nil
3579 "Non-nil means fontify only the stars in each headline.
3580 When nil, the entire headline is fontified.
3581 Changing it requires restart of `font-lock-mode' to become effective
3582 also in regions already fontified."
3583 :group 'org-appearance
3584 :type 'boolean)
3586 (defcustom org-hide-leading-stars nil
3587 "Non-nil means hide the first N-1 stars in a headline.
3588 This works by using the face `org-hide' for these stars. This
3589 face is white for a light background, and black for a dark
3590 background. You may have to customize the face `org-hide' to
3591 make this work.
3592 Changing it requires restart of `font-lock-mode' to become effective
3593 also in regions already fontified.
3594 You may also set this on a per-file basis by adding one of the following
3595 lines to the buffer:
3597 #+STARTUP: hidestars
3598 #+STARTUP: showstars"
3599 :group 'org-appearance
3600 :type 'boolean)
3602 (defcustom org-hidden-keywords nil
3603 "List of symbols corresponding to keywords to be hidden the org buffer.
3604 For example, a value '(title) for this list will make the document's title
3605 appear in the buffer without the initial #+TITLE: keyword."
3606 :group 'org-appearance
3607 :version "24.1"
3608 :type '(set (const :tag "#+AUTHOR" author)
3609 (const :tag "#+DATE" date)
3610 (const :tag "#+EMAIL" email)
3611 (const :tag "#+TITLE" title)))
3613 (defcustom org-custom-properties nil
3614 "List of properties (as strings) with a special meaning.
3615 The default use of these custom properties is to let the user
3616 hide them with `org-toggle-custom-properties-visibility'."
3617 :group 'org-properties
3618 :group 'org-appearance
3619 ;; :version "24.3"
3620 :type '(repeat (string :tag "Property Name")))
3622 (defcustom org-fontify-done-headline nil
3623 "Non-nil means change the face of a headline if it is marked DONE.
3624 Normally, only the TODO/DONE keyword indicates the state of a headline.
3625 When this is non-nil, the headline after the keyword is set to the
3626 `org-headline-done' as an additional indication."
3627 :group 'org-appearance
3628 :type 'boolean)
3630 (defcustom org-fontify-emphasized-text t
3631 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3632 Changing this variable requires a restart of Emacs to take effect."
3633 :group 'org-appearance
3634 :type 'boolean)
3636 (defcustom org-fontify-whole-heading-line nil
3637 "Non-nil means fontify the whole line for headings.
3638 This is useful when setting a background color for the
3639 org-level-* faces."
3640 :group 'org-appearance
3641 :type 'boolean)
3643 (defcustom org-highlight-latex-fragments-and-specials nil
3644 "Non-nil means fontify what is treated specially by the exporters."
3645 :group 'org-appearance
3646 :type 'boolean)
3648 (defcustom org-hide-emphasis-markers nil
3649 "Non-nil mean font-lock should hide the emphasis marker characters."
3650 :group 'org-appearance
3651 :type 'boolean)
3653 (defcustom org-pretty-entities nil
3654 "Non-nil means show entities as UTF8 characters.
3655 When nil, the \\name form remains in the buffer."
3656 :group 'org-appearance
3657 :version "24.1"
3658 :type 'boolean)
3660 (defcustom org-pretty-entities-include-sub-superscripts t
3661 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3662 :group 'org-appearance
3663 :version "24.1"
3664 :type 'boolean)
3666 (defvar org-emph-re nil
3667 "Regular expression for matching emphasis.
3668 After a match, the match groups contain these elements:
3669 0 The match of the full regular expression, including the characters
3670 before and after the proper match
3671 1 The character before the proper match, or empty at beginning of line
3672 2 The proper match, including the leading and trailing markers
3673 3 The leading marker like * or /, indicating the type of highlighting
3674 4 The text between the emphasis markers, not including the markers
3675 5 The character after the match, empty at the end of a line")
3676 (defvar org-verbatim-re nil
3677 "Regular expression for matching verbatim text.")
3678 (defvar org-emphasis-regexp-components) ; defined just below
3679 (defvar org-emphasis-alist) ; defined just below
3680 (defun org-set-emph-re (var val)
3681 "Set variable and compute the emphasis regular expression."
3682 (set var val)
3683 (when (and (boundp 'org-emphasis-alist)
3684 (boundp 'org-emphasis-regexp-components)
3685 org-emphasis-alist org-emphasis-regexp-components)
3686 (let* ((e org-emphasis-regexp-components)
3687 (pre (car e))
3688 (post (nth 1 e))
3689 (border (nth 2 e))
3690 (body (nth 3 e))
3691 (nl (nth 4 e))
3692 (body1 (concat body "*?"))
3693 (markers (mapconcat 'car org-emphasis-alist ""))
3694 (vmarkers (mapconcat
3695 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3696 org-emphasis-alist "")))
3697 ;; make sure special characters appear at the right position in the class
3698 (if (string-match "\\^" markers)
3699 (setq markers (concat (replace-match "" t t markers) "^")))
3700 (if (string-match "-" markers)
3701 (setq markers (concat (replace-match "" t t markers) "-")))
3702 (if (string-match "\\^" vmarkers)
3703 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3704 (if (string-match "-" vmarkers)
3705 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3706 (if (> nl 0)
3707 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3708 (int-to-string nl) "\\}")))
3709 ;; Make the regexp
3710 (setq org-emph-re
3711 (concat "\\([" pre "]\\|^\\)"
3712 "\\("
3713 "\\([" markers "]\\)"
3714 "\\("
3715 "[^" border "]\\|"
3716 "[^" border "]"
3717 body1
3718 "[^" border "]"
3719 "\\)"
3720 "\\3\\)"
3721 "\\([" post "]\\|$\\)"))
3722 (setq org-verbatim-re
3723 (concat "\\([" pre "]\\|^\\)"
3724 "\\("
3725 "\\([" vmarkers "]\\)"
3726 "\\("
3727 "[^" border "]\\|"
3728 "[^" border "]"
3729 body1
3730 "[^" border "]"
3731 "\\)"
3732 "\\3\\)"
3733 "\\([" post "]\\|$\\)")))))
3735 (defcustom org-emphasis-regexp-components
3736 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3737 "Components used to build the regular expression for emphasis.
3738 This is a list with five entries. Terminology: In an emphasis string
3739 like \" *strong word* \", we call the initial space PREMATCH, the final
3740 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3741 and \"trong wor\" is the body. The different components in this variable
3742 specify what is allowed/forbidden in each part:
3744 pre Chars allowed as prematch. Beginning of line will be allowed too.
3745 post Chars allowed as postmatch. End of line will be allowed too.
3746 border The chars *forbidden* as border characters.
3747 body-regexp A regexp like \".\" to match a body character. Don't use
3748 non-shy groups here, and don't allow newline here.
3749 newline The maximum number of newlines allowed in an emphasis exp.
3751 Use customize to modify this, or restart Emacs after changing it."
3752 :group 'org-appearance
3753 :set 'org-set-emph-re
3754 :type '(list
3755 (sexp :tag "Allowed chars in pre ")
3756 (sexp :tag "Allowed chars in post ")
3757 (sexp :tag "Forbidden chars in border ")
3758 (sexp :tag "Regexp for body ")
3759 (integer :tag "number of newlines allowed")
3760 (option (boolean :tag "Please ignore this button"))))
3762 (defcustom org-emphasis-alist
3763 `(("*" bold "<b>" "</b>")
3764 ("/" italic "<i>" "</i>")
3765 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3766 ("=" org-code "<code>" "</code>" verbatim)
3767 ("~" org-verbatim "<code>" "</code>" verbatim)
3768 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3769 "<del>" "</del>")
3771 "Special syntax for emphasized text.
3772 Text starting and ending with a special character will be emphasized, for
3773 example *bold*, _underlined_ and /italic/. This variable sets the marker
3774 characters, the face to be used by font-lock for highlighting in Org-mode
3775 Emacs buffers, and the HTML tags to be used for this.
3776 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3777 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3778 Use customize to modify this, or restart Emacs after changing it."
3779 :group 'org-appearance
3780 :set 'org-set-emph-re
3781 :type '(repeat
3782 (list
3783 (string :tag "Marker character")
3784 (choice
3785 (face :tag "Font-lock-face")
3786 (plist :tag "Face property list"))
3787 (string :tag "HTML start tag")
3788 (string :tag "HTML end tag")
3789 (option (const verbatim)))))
3791 (defvar org-protecting-blocks
3792 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3793 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3794 This is needed for font-lock setup.")
3796 ;;; Miscellaneous options
3798 (defgroup org-completion nil
3799 "Completion in Org-mode."
3800 :tag "Org Completion"
3801 :group 'org)
3803 (defcustom org-completion-use-ido nil
3804 "Non-nil means use ido completion wherever possible.
3805 Note that `ido-mode' must be active for this variable to be relevant.
3806 If you decide to turn this variable on, you might well want to turn off
3807 `org-outline-path-complete-in-steps'.
3808 See also `org-completion-use-iswitchb'."
3809 :group 'org-completion
3810 :type 'boolean)
3812 (defcustom org-completion-use-iswitchb nil
3813 "Non-nil means use iswitchb completion wherever possible.
3814 Note that `iswitchb-mode' must be active for this variable to be relevant.
3815 If you decide to turn this variable on, you might well want to turn off
3816 `org-outline-path-complete-in-steps'.
3817 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3818 :group 'org-completion
3819 :type 'boolean)
3821 (defcustom org-completion-fallback-command 'hippie-expand
3822 "The expansion command called by \\[pcomplete] in normal context.
3823 Normal means, no org-mode-specific context."
3824 :group 'org-completion
3825 :type 'function)
3827 ;;; Functions and variables from their packages
3828 ;; Declared here to avoid compiler warnings
3830 ;; XEmacs only
3831 (defvar outline-mode-menu-heading)
3832 (defvar outline-mode-menu-show)
3833 (defvar outline-mode-menu-hide)
3834 (defvar zmacs-regions) ; XEmacs regions
3836 ;; Emacs only
3837 (defvar mark-active)
3839 ;; Various packages
3840 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3841 (declare-function calendar-forward-day "cal-move" (arg))
3842 (declare-function calendar-goto-date "cal-move" (date))
3843 (declare-function calendar-goto-today "cal-move" ())
3844 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3845 (defvar calc-embedded-close-formula)
3846 (defvar calc-embedded-open-formula)
3847 (declare-function cdlatex-tab "ext:cdlatex" ())
3848 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3849 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3850 (defvar font-lock-unfontify-region-function)
3851 (declare-function iswitchb-read-buffer "iswitchb"
3852 (prompt &optional default require-match start matches-set))
3853 (defvar iswitchb-temp-buflist)
3854 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3855 (defvar org-agenda-tags-todo-honor-ignore-options)
3856 (declare-function org-agenda-skip "org-agenda" ())
3857 (declare-function
3858 org-agenda-format-item "org-agenda"
3859 (extra txt &optional category tags dotime noprefix remove-re habitp))
3860 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3861 (declare-function org-agenda-change-all-lines "org-agenda"
3862 (newhead hdmarker &optional fixface just-this))
3863 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3864 (declare-function org-agenda-maybe-redo "org-agenda" ())
3865 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3866 (beg end))
3867 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3868 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3869 "org-agenda" (&optional end))
3870 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3871 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3872 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3873 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3874 (declare-function org-indent-mode "org-indent" (&optional arg))
3875 (declare-function parse-time-string "parse-time" (string))
3876 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3877 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3878 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3879 (defvar remember-data-file)
3880 (defvar texmathp-why)
3881 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3882 (declare-function table--at-cell-p "table" (position &optional object at-column))
3884 (defvar w3m-current-url)
3885 (defvar w3m-current-title)
3887 (defvar org-latex-regexps)
3889 ;;; Autoload and prepare some org modules
3891 ;; Some table stuff that needs to be defined here, because it is used
3892 ;; by the functions setting up org-mode or checking for table context.
3894 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3895 "Detect an org-type or table-type table.")
3896 (defconst org-table-line-regexp "^[ \t]*|"
3897 "Detect an org-type table line.")
3898 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3899 "Detect an org-type table line.")
3900 (defconst org-table-hline-regexp "^[ \t]*|-"
3901 "Detect an org-type table hline.")
3902 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3903 "Detect a table-type table hline.")
3904 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3905 "Detect the first line outside a table when searching from within it.
3906 This works for both table types.")
3908 ;; Autoload the functions in org-table.el that are needed by functions here.
3910 (eval-and-compile
3911 (org-autoload "org-table"
3912 '(org-table-align org-table-begin org-table-blank-field
3913 org-table-convert org-table-convert-region org-table-copy-down
3914 org-table-copy-region org-table-create
3915 org-table-create-or-convert-from-region
3916 org-table-create-with-table.el org-table-current-dline
3917 org-table-cut-region org-table-delete-column org-table-edit-field
3918 org-table-edit-formulas org-table-end org-table-eval-formula
3919 org-table-export org-table-field-info
3920 org-table-get-stored-formulas org-table-goto-column
3921 org-table-hline-and-move org-table-import org-table-insert-column
3922 org-table-insert-hline org-table-insert-row org-table-iterate
3923 org-table-justify-field-maybe org-table-kill-row
3924 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3925 org-table-move-column org-table-move-column-left
3926 org-table-move-column-right org-table-move-row
3927 org-table-move-row-down org-table-move-row-up
3928 org-table-next-field org-table-next-row org-table-paste-rectangle
3929 org-table-previous-field org-table-recalculate
3930 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3931 org-table-toggle-coordinate-overlays
3932 org-table-toggle-formula-debugger org-table-wrap-region
3933 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3934 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3935 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3937 (defun org-at-table-p (&optional table-type)
3938 "Return t if the cursor is inside an org-type table.
3939 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3940 (if org-enable-table-editor
3941 (save-excursion
3942 (beginning-of-line 1)
3943 (looking-at (if table-type org-table-any-line-regexp
3944 org-table-line-regexp)))
3945 nil))
3946 (defsubst org-table-p () (org-at-table-p))
3948 (defun org-at-table.el-p ()
3949 "Return t if and only if we are at a table.el table."
3950 (and (org-at-table-p 'any)
3951 (save-excursion
3952 (goto-char (org-table-begin 'any))
3953 (looking-at org-table1-hline-regexp))))
3954 (defun org-table-recognize-table.el ()
3955 "If there is a table.el table nearby, recognize it and move into it."
3956 (if org-table-tab-recognizes-table.el
3957 (if (org-at-table.el-p)
3958 (progn
3959 (beginning-of-line 1)
3960 (if (looking-at org-table-dataline-regexp)
3962 (if (looking-at org-table1-hline-regexp)
3963 (progn
3964 (beginning-of-line 2)
3965 (if (looking-at org-table-any-border-regexp)
3966 (beginning-of-line -1)))))
3967 (if (re-search-forward "|" (org-table-end t) t)
3968 (progn
3969 (require 'table)
3970 (if (table--at-cell-p (point))
3972 (message "recognizing table.el table...")
3973 (table-recognize-table)
3974 (message "recognizing table.el table...done")))
3975 (error "This should not happen"))
3977 nil)
3978 nil))
3980 (defun org-at-table-hline-p ()
3981 "Return t if the cursor is inside a hline in a table."
3982 (if org-enable-table-editor
3983 (save-excursion
3984 (beginning-of-line 1)
3985 (looking-at org-table-hline-regexp))
3986 nil))
3988 (defvar org-table-clean-did-remove-column nil)
3990 (defun org-table-map-tables (function &optional quietly)
3991 "Apply FUNCTION to the start of all tables in the buffer."
3992 (save-excursion
3993 (save-restriction
3994 (widen)
3995 (goto-char (point-min))
3996 (while (re-search-forward org-table-any-line-regexp nil t)
3997 (unless quietly
3998 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3999 (beginning-of-line 1)
4000 (when (and (looking-at org-table-line-regexp)
4001 ;; Exclude tables in src/example/verbatim/clocktable blocks
4002 (not (org-in-block-p '("src" "example"))))
4003 (save-excursion (funcall function))
4004 (or (looking-at org-table-line-regexp)
4005 (forward-char 1)))
4006 (re-search-forward org-table-any-border-regexp nil 1))))
4007 (unless quietly (message "Mapping tables: done")))
4009 ;; Declare and autoload functions from org-exp.el & Co
4011 (declare-function org-default-export-plist "org-exp")
4012 (declare-function org-infile-export-plist "org-exp")
4013 (declare-function org-get-current-options "org-exp")
4014 (eval-and-compile
4015 (org-autoload "org-exp"
4016 '(org-export org-export-visible
4017 org-insert-export-options-template
4018 org-table-clean-before-export))
4019 (org-autoload "org-ascii"
4020 '(org-export-as-ascii org-export-ascii-preprocess
4021 org-export-as-ascii-to-buffer org-replace-region-by-ascii
4022 org-export-region-as-ascii))
4023 (org-autoload "org-latex"
4024 '(org-export-as-latex-batch org-export-as-latex-to-buffer
4025 org-replace-region-by-latex org-export-region-as-latex
4026 org-export-as-latex org-export-as-pdf
4027 org-export-as-pdf-and-open))
4028 (org-autoload "org-html"
4029 '(org-export-as-html-and-open
4030 org-export-as-html-batch org-export-as-html-to-buffer
4031 org-replace-region-by-html org-export-region-as-html
4032 org-export-as-html))
4033 (org-autoload "org-docbook"
4034 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
4035 org-replace-region-by-docbook org-export-region-as-docbook
4036 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
4037 org-export-as-docbook))
4038 (org-autoload "org-icalendar"
4039 '(org-export-icalendar-this-file
4040 org-export-icalendar-all-agenda-files
4041 org-export-icalendar-combine-agenda-files))
4042 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4043 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4045 ;; Declare and autoload functions from org-agenda.el
4047 (eval-and-compile
4048 (org-autoload "org-agenda"
4049 '(org-agenda org-agenda-list org-search-view
4050 org-todo-list org-tags-view org-agenda-list-stuck-projects
4051 org-diary org-agenda-to-appt
4052 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4054 ;; Autoload org-remember
4056 (eval-and-compile
4057 (org-autoload "org-remember"
4058 '(org-remember-insinuate org-remember-annotation
4059 org-remember-apply-template org-remember org-remember-handler)))
4061 (eval-and-compile
4062 (org-autoload "org-capture"
4063 '(org-capture org-capture-insert-template-here
4064 org-capture-import-remember-templates)))
4066 ;; Autoload org-clock.el
4068 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4069 (beg end))
4070 (declare-function org-clock-update-mode-line "org-clock" ())
4071 (declare-function org-resolve-clocks "org-clock"
4072 (&optional also-non-dangling-p prompt last-valid))
4073 (defvar org-clock-start-time)
4074 (defvar org-clock-marker (make-marker)
4075 "Marker recording the last clock-in.")
4076 (defvar org-clock-hd-marker (make-marker)
4077 "Marker recording the last clock-in, but the headline position.")
4078 (defvar org-clock-heading ""
4079 "The heading of the current clock entry.")
4080 (defun org-clock-is-active ()
4081 "Return non-nil if clock is currently running.
4082 The return value is actually the clock marker."
4083 (marker-buffer org-clock-marker))
4085 (eval-and-compile
4086 (org-autoload
4087 "org-clock"
4088 '(org-clock-in org-clock-out org-clock-cancel
4089 org-clock-goto org-clock-sum org-clock-display
4090 org-clock-remove-overlays org-clock-report
4091 org-clocktable-shift org-dblock-write:clocktable
4092 org-get-clocktable org-resolve-clocks)))
4094 (defun org-clock-update-time-maybe ()
4095 "If this is a CLOCK line, update it and return t.
4096 Otherwise, return nil."
4097 (interactive)
4098 (save-excursion
4099 (beginning-of-line 1)
4100 (skip-chars-forward " \t")
4101 (when (looking-at org-clock-string)
4102 (let ((re (concat "[ \t]*" org-clock-string
4103 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4104 "\\([ \t]*=>.*\\)?\\)?"))
4105 ts te h m s neg)
4106 (cond
4107 ((not (looking-at re))
4108 nil)
4109 ((not (match-end 2))
4110 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4111 (> org-clock-marker (point))
4112 (<= org-clock-marker (point-at-eol)))
4113 ;; The clock is running here
4114 (setq org-clock-start-time
4115 (apply 'encode-time
4116 (org-parse-time-string (match-string 1))))
4117 (org-clock-update-mode-line)))
4119 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4120 (end-of-line 1)
4121 (setq ts (match-string 1)
4122 te (match-string 3))
4123 (setq s (- (org-float-time
4124 (apply 'encode-time (org-parse-time-string te)))
4125 (org-float-time
4126 (apply 'encode-time (org-parse-time-string ts))))
4127 neg (< s 0)
4128 s (abs s)
4129 h (floor (/ s 3600))
4130 s (- s (* 3600 h))
4131 m (floor (/ s 60))
4132 s (- s (* 60 s)))
4133 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4134 t))))))
4136 (defun org-check-running-clock ()
4137 "Check if the current buffer contains the running clock.
4138 If yes, offer to stop it and to save the buffer with the changes."
4139 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4140 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4141 (buffer-name))))
4142 (org-clock-out)
4143 (when (y-or-n-p "Save changed buffer?")
4144 (save-buffer))))
4146 (defun org-clocktable-try-shift (dir n)
4147 "Check if this line starts a clock table, if yes, shift the time block."
4148 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4149 (org-clocktable-shift dir n)))
4151 ;; Autoload org-timer.el
4153 (eval-and-compile
4154 (org-autoload
4155 "org-timer"
4156 '(org-timer-start org-timer org-timer-item
4157 org-timer-change-times-in-region
4158 org-timer-set-timer
4159 org-timer-reset-timers
4160 org-timer-show-remaining-time)))
4162 ;; Autoload org-feed.el
4164 (eval-and-compile
4165 (org-autoload
4166 "org-feed"
4167 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4170 ;; Autoload org-indent.el
4172 ;; Define the variable already here, to make sure we have it.
4173 (defvar org-indent-mode nil
4174 "Non-nil if Org-Indent mode is enabled.
4175 Use the command `org-indent-mode' to change this variable.")
4177 (eval-and-compile
4178 (org-autoload
4179 "org-indent"
4180 '(org-indent-mode)))
4182 ;; Autoload org-mobile.el
4184 (eval-and-compile
4185 (org-autoload
4186 "org-mobile"
4187 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4189 ;; Autoload archiving code
4190 ;; The stuff that is needed for cycling and tags has to be defined here.
4192 (defgroup org-archive nil
4193 "Options concerning archiving in Org-mode."
4194 :tag "Org Archive"
4195 :group 'org-structure)
4197 (defcustom org-archive-location "%s_archive::"
4198 "The location where subtrees should be archived.
4200 The value of this variable is a string, consisting of two parts,
4201 separated by a double-colon. The first part is a filename and
4202 the second part is a headline.
4204 When the filename is omitted, archiving happens in the same file.
4205 %s in the filename will be replaced by the current file
4206 name (without the directory part). Archiving to a different file
4207 is useful to keep archived entries from contributing to the
4208 Org-mode Agenda.
4210 The archived entries will be filed as subtrees of the specified
4211 headline. When the headline is omitted, the subtrees are simply
4212 filed away at the end of the file, as top-level entries. Also in
4213 the heading you can use %s to represent the file name, this can be
4214 useful when using the same archive for a number of different files.
4216 Here are a few examples:
4217 \"%s_archive::\"
4218 If the current file is Projects.org, archive in file
4219 Projects.org_archive, as top-level trees. This is the default.
4221 \"::* Archived Tasks\"
4222 Archive in the current file, under the top-level headline
4223 \"* Archived Tasks\".
4225 \"~/org/archive.org::\"
4226 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4228 \"~/org/archive.org::* From %s\"
4229 Archive in file ~/org/archive.org (absolute path), under headlines
4230 \"From FILENAME\" where file name is the current file name.
4232 \"~/org/datetree.org::datetree/* Finished Tasks\"
4233 The \"datetree/\" string is special, signifying to archive
4234 items to the datetree. Items are placed in either the CLOSED
4235 date of the item, or the current date if there is no CLOSED date.
4236 The heading will be a subentry to the current date. There doesn't
4237 need to be a heading, but there always needs to be a slash after
4238 datetree. For example, to store archived items directly in the
4239 datetree, use \"~/org/datetree.org::datetree/\".
4241 \"basement::** Finished Tasks\"
4242 Archive in file ./basement (relative path), as level 3 trees
4243 below the level 2 heading \"** Finished Tasks\".
4245 You may set this option on a per-file basis by adding to the buffer a
4246 line like
4248 #+ARCHIVE: basement::** Finished Tasks
4250 You may also define it locally for a subtree by setting an ARCHIVE property
4251 in the entry. If such a property is found in an entry, or anywhere up
4252 the hierarchy, it will be used."
4253 :group 'org-archive
4254 :type 'string)
4256 (defcustom org-archive-tag "ARCHIVE"
4257 "The tag that marks a subtree as archived.
4258 An archived subtree does not open during visibility cycling, and does
4259 not contribute to the agenda listings.
4260 After changing this, font-lock must be restarted in the relevant buffers to
4261 get the proper fontification."
4262 :group 'org-archive
4263 :group 'org-keywords
4264 :type 'string)
4266 (defcustom org-agenda-skip-archived-trees t
4267 "Non-nil means the agenda will skip any items located in archived trees.
4268 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4269 variable is no longer recommended, you should leave it at the value t.
4270 Instead, use the key `v' to cycle the archives-mode in the agenda."
4271 :group 'org-archive
4272 :group 'org-agenda-skip
4273 :type 'boolean)
4275 (defcustom org-columns-skip-archived-trees t
4276 "Non-nil means ignore archived trees when creating column view."
4277 :group 'org-archive
4278 :group 'org-properties
4279 :type 'boolean)
4281 (defcustom org-cycle-open-archived-trees nil
4282 "Non-nil means `org-cycle' will open archived trees.
4283 An archived tree is a tree marked with the tag ARCHIVE.
4284 When nil, archived trees will stay folded. You can still open them with
4285 normal outline commands like `show-all', but not with the cycling commands."
4286 :group 'org-archive
4287 :group 'org-cycle
4288 :type 'boolean)
4290 (defcustom org-sparse-tree-open-archived-trees nil
4291 "Non-nil means sparse tree construction shows matches in archived trees.
4292 When nil, matches in these trees are highlighted, but the trees are kept in
4293 collapsed state."
4294 :group 'org-archive
4295 :group 'org-sparse-trees
4296 :type 'boolean)
4298 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4299 "The default date type when building a sparse tree.
4300 When this is nil, a date is a scheduled or a deadline timestamp.
4301 Otherwise, these types are allowed:
4303 all: all timestamps
4304 active: only active timestamps (<...>)
4305 inactive: only inactive timestamps (<...)
4306 scheduled: only scheduled timestamps
4307 deadline: only deadline timestamps"
4308 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4309 (const :tag "All timestamps" all)
4310 (const :tag "Only active timestamps" active)
4311 (const :tag "Only inactive timestamps" inactive)
4312 (const :tag "Only scheduled timestamps" scheduled)
4313 (const :tag "Only deadline timestamps" deadline))
4314 ;; :version "24.3"
4315 :group 'org-sparse-trees)
4317 (defun org-cycle-hide-archived-subtrees (state)
4318 "Re-hide all archived subtrees after a visibility state change."
4319 (when (and (not org-cycle-open-archived-trees)
4320 (not (memq state '(overview folded))))
4321 (save-excursion
4322 (let* ((globalp (memq state '(contents all)))
4323 (beg (if globalp (point-min) (point)))
4324 (end (if globalp (point-max) (org-end-of-subtree t))))
4325 (org-hide-archived-subtrees beg end)
4326 (goto-char beg)
4327 (if (looking-at (concat ".*:" org-archive-tag ":"))
4328 (message "%s" (substitute-command-keys
4329 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4331 (defun org-force-cycle-archived ()
4332 "Cycle subtree even if it is archived."
4333 (interactive)
4334 (setq this-command 'org-cycle)
4335 (let ((org-cycle-open-archived-trees t))
4336 (call-interactively 'org-cycle)))
4338 (defun org-hide-archived-subtrees (beg end)
4339 "Re-hide all archived subtrees after a visibility state change."
4340 (save-excursion
4341 (let* ((re (concat ":" org-archive-tag ":")))
4342 (goto-char beg)
4343 (while (re-search-forward re end t)
4344 (when (org-at-heading-p)
4345 (org-flag-subtree t)
4346 (org-end-of-subtree t))))))
4348 (declare-function outline-end-of-heading "outline" ())
4349 (declare-function outline-flag-region "outline" (from to flag))
4350 (defun org-flag-subtree (flag)
4351 (save-excursion
4352 (org-back-to-heading t)
4353 (outline-end-of-heading)
4354 (outline-flag-region (point)
4355 (progn (org-end-of-subtree t) (point))
4356 flag)))
4358 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4360 (eval-and-compile
4361 (org-autoload "org-archive"
4362 '(org-add-archive-files org-archive-subtree
4363 org-archive-to-archive-sibling org-toggle-archive-tag
4364 org-archive-subtree-default
4365 org-archive-subtree-default-with-confirmation)))
4367 ;; Autoload Column View Code
4369 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4370 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4371 (declare-function org-columns-compute "org-colview" (property))
4373 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4374 '(org-columns-number-to-string org-columns-get-format-and-top-level
4375 org-columns-compute org-agenda-columns org-columns-remove-overlays
4376 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4378 ;; Autoload ID code
4380 (declare-function org-id-store-link "org-id")
4381 (declare-function org-id-locations-load "org-id")
4382 (declare-function org-id-locations-save "org-id")
4383 (defvar org-id-track-globally)
4384 (org-autoload "org-id"
4385 '(org-id-get-create org-id-new org-id-copy org-id-get
4386 org-id-get-with-outline-path-completion
4387 org-id-get-with-outline-drilling org-id-store-link
4388 org-id-goto org-id-find org-id-store-link))
4390 ;; Autoload Plotting Code
4392 (org-autoload "org-plot"
4393 '(org-plot/gnuplot))
4395 ;;; Variables for pre-computed regular expressions, all buffer local
4397 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4398 "Matches first line of a hidden block.")
4399 (make-variable-buffer-local 'org-drawer-regexp)
4400 (defvar org-todo-regexp nil
4401 "Matches any of the TODO state keywords.")
4402 (make-variable-buffer-local 'org-todo-regexp)
4403 (defvar org-not-done-regexp nil
4404 "Matches any of the TODO state keywords except the last one.")
4405 (make-variable-buffer-local 'org-not-done-regexp)
4406 (defvar org-not-done-heading-regexp nil
4407 "Matches a TODO headline that is not done.")
4408 (make-variable-buffer-local 'org-not-done-regexp)
4409 (defvar org-todo-line-regexp nil
4410 "Matches a headline and puts TODO state into group 2 if present.")
4411 (make-variable-buffer-local 'org-todo-line-regexp)
4412 (defvar org-complex-heading-regexp nil
4413 "Matches a headline and puts everything into groups:
4414 group 1: the stars
4415 group 2: The todo keyword, maybe
4416 group 3: Priority cookie
4417 group 4: True headline
4418 group 5: Tags")
4419 (make-variable-buffer-local 'org-complex-heading-regexp)
4420 (defvar org-complex-heading-regexp-format nil
4421 "Printf format to make regexp to match an exact headline.
4422 This regexp will match the headline of any node which has the
4423 exact headline text that is put into the format, but may have any
4424 TODO state, priority and tags.")
4425 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4426 (defvar org-todo-line-tags-regexp nil
4427 "Matches a headline and puts TODO state into group 2 if present.
4428 Also put tags into group 4 if tags are present.")
4429 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4430 (defvar org-ds-keyword-length 12
4431 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4432 (make-variable-buffer-local 'org-ds-keyword-length)
4433 (defvar org-deadline-regexp nil
4434 "Matches the DEADLINE keyword.")
4435 (make-variable-buffer-local 'org-deadline-regexp)
4436 (defvar org-deadline-time-regexp nil
4437 "Matches the DEADLINE keyword together with a time stamp.")
4438 (make-variable-buffer-local 'org-deadline-time-regexp)
4439 (defvar org-deadline-line-regexp nil
4440 "Matches the DEADLINE keyword and the rest of the line.")
4441 (make-variable-buffer-local 'org-deadline-line-regexp)
4442 (defvar org-scheduled-regexp nil
4443 "Matches the SCHEDULED keyword.")
4444 (make-variable-buffer-local 'org-scheduled-regexp)
4445 (defvar org-scheduled-time-regexp nil
4446 "Matches the SCHEDULED keyword together with a time stamp.")
4447 (make-variable-buffer-local 'org-scheduled-time-regexp)
4448 (defvar org-closed-time-regexp nil
4449 "Matches the CLOSED keyword together with a time stamp.")
4450 (make-variable-buffer-local 'org-closed-time-regexp)
4452 (defvar org-keyword-time-regexp nil
4453 "Matches any of the 4 keywords, together with the time stamp.")
4454 (make-variable-buffer-local 'org-keyword-time-regexp)
4455 (defvar org-keyword-time-not-clock-regexp nil
4456 "Matches any of the 3 keywords, together with the time stamp.")
4457 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4458 (defvar org-maybe-keyword-time-regexp nil
4459 "Matches a timestamp, possibly preceded by a keyword.")
4460 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4461 (defvar org-all-time-keywords nil
4462 "List of time keywords.")
4463 (make-variable-buffer-local 'org-all-time-keywords)
4465 (defconst org-plain-time-of-day-regexp
4466 (concat
4467 "\\(\\<[012]?[0-9]"
4468 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4469 "\\(--?"
4470 "\\(\\<[012]?[0-9]"
4471 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4472 "\\)?")
4473 "Regular expression to match a plain time or time range.
4474 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4475 groups carry important information:
4476 0 the full match
4477 1 the first time, range or not
4478 8 the second time, if it is a range.")
4480 (defconst org-plain-time-extension-regexp
4481 (concat
4482 "\\(\\<[012]?[0-9]"
4483 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4484 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4485 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4486 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4487 groups carry important information:
4488 0 the full match
4489 7 hours of duration
4490 9 minutes of duration")
4492 (defconst org-stamp-time-of-day-regexp
4493 (concat
4494 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4495 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4496 "\\(--?"
4497 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4498 "Regular expression to match a timestamp time or time range.
4499 After a match, the following groups carry important information:
4500 0 the full match
4501 1 date plus weekday, for back referencing to make sure both times are on the same day
4502 2 the first time, range or not
4503 4 the second time, if it is a range.")
4505 (defconst org-startup-options
4506 '(("fold" org-startup-folded t)
4507 ("overview" org-startup-folded t)
4508 ("nofold" org-startup-folded nil)
4509 ("showall" org-startup-folded nil)
4510 ("showeverything" org-startup-folded showeverything)
4511 ("content" org-startup-folded content)
4512 ("indent" org-startup-indented t)
4513 ("noindent" org-startup-indented nil)
4514 ("hidestars" org-hide-leading-stars t)
4515 ("showstars" org-hide-leading-stars nil)
4516 ("odd" org-odd-levels-only t)
4517 ("oddeven" org-odd-levels-only nil)
4518 ("align" org-startup-align-all-tables t)
4519 ("noalign" org-startup-align-all-tables nil)
4520 ("inlineimages" org-startup-with-inline-images t)
4521 ("noinlineimages" org-startup-with-inline-images nil)
4522 ("customtime" org-display-custom-times t)
4523 ("logdone" org-log-done time)
4524 ("lognotedone" org-log-done note)
4525 ("nologdone" org-log-done nil)
4526 ("lognoteclock-out" org-log-note-clock-out t)
4527 ("nolognoteclock-out" org-log-note-clock-out nil)
4528 ("logrepeat" org-log-repeat state)
4529 ("lognoterepeat" org-log-repeat note)
4530 ("nologrepeat" org-log-repeat nil)
4531 ("logreschedule" org-log-reschedule time)
4532 ("lognotereschedule" org-log-reschedule note)
4533 ("nologreschedule" org-log-reschedule nil)
4534 ("logredeadline" org-log-redeadline time)
4535 ("lognoteredeadline" org-log-redeadline note)
4536 ("nologredeadline" org-log-redeadline nil)
4537 ("logrefile" org-log-refile time)
4538 ("lognoterefile" org-log-refile note)
4539 ("nologrefile" org-log-refile nil)
4540 ("fninline" org-footnote-define-inline t)
4541 ("nofninline" org-footnote-define-inline nil)
4542 ("fnlocal" org-footnote-section nil)
4543 ("fnauto" org-footnote-auto-label t)
4544 ("fnprompt" org-footnote-auto-label nil)
4545 ("fnconfirm" org-footnote-auto-label confirm)
4546 ("fnplain" org-footnote-auto-label plain)
4547 ("fnadjust" org-footnote-auto-adjust t)
4548 ("nofnadjust" org-footnote-auto-adjust nil)
4549 ("constcgs" constants-unit-system cgs)
4550 ("constSI" constants-unit-system SI)
4551 ("noptag" org-tag-persistent-alist nil)
4552 ("hideblocks" org-hide-block-startup t)
4553 ("nohideblocks" org-hide-block-startup nil)
4554 ("beamer" org-startup-with-beamer-mode t)
4555 ("entitiespretty" org-pretty-entities t)
4556 ("entitiesplain" org-pretty-entities nil))
4557 "Variable associated with STARTUP options for org-mode.
4558 Each element is a list of three items: the startup options (as written
4559 in the #+STARTUP line), the corresponding variable, and the value to set
4560 this variable to if the option is found. An optional forth element PUSH
4561 means to push this value onto the list in the variable.")
4563 (defun org-update-property-plist (key val props)
4564 "Update PROPS with KEY and VAL."
4565 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4566 (key (if appending (substring key 0 (- (length key) 1)) key))
4567 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4568 (previous (cdr (assoc key props))))
4569 (if appending
4570 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4571 (cons (cons key val) remainder))))
4573 (defconst org-block-regexp
4574 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4575 "Regular expression for hiding blocks.")
4576 (defconst org-heading-keyword-regexp-format
4577 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4578 "Printf format for a regexp matching an headline with some keyword.
4579 This regexp will match the headline of any node which has the
4580 exact keyword that is put into the format. The keyword isn't in
4581 any group by default, but the stars and the body are.")
4582 (defconst org-heading-keyword-maybe-regexp-format
4583 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4584 "Printf format for a regexp matching an headline, possibly with some keyword.
4585 This regexp can match any headline with the specified keyword, or
4586 without a keyword. The keyword isn't in any group by default,
4587 but the stars and the body are.")
4589 (defun org-set-regexps-and-options ()
4590 "Precompute regular expressions for current buffer."
4591 (when (derived-mode-p 'org-mode)
4592 (org-set-local 'org-todo-kwd-alist nil)
4593 (org-set-local 'org-todo-key-alist nil)
4594 (org-set-local 'org-todo-key-trigger nil)
4595 (org-set-local 'org-todo-keywords-1 nil)
4596 (org-set-local 'org-done-keywords nil)
4597 (org-set-local 'org-todo-heads nil)
4598 (org-set-local 'org-todo-sets nil)
4599 (org-set-local 'org-todo-log-states nil)
4600 (org-set-local 'org-file-properties nil)
4601 (org-set-local 'org-file-tags nil)
4602 (let ((re (org-make-options-regexp
4603 '("CATEGORY" "TODO" "COLUMNS"
4604 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4605 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4606 "OPTIONS")
4607 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4608 (splitre "[ \t]+")
4609 (scripts org-use-sub-superscripts)
4610 kwds kws0 kwsa key log value cat arch tags const links hw dws
4611 tail sep kws1 prio props ftags drawers beamer-p
4612 ext-setup-or-nil setup-contents (start 0))
4613 (save-excursion
4614 (save-restriction
4615 (widen)
4616 (goto-char (point-min))
4617 (while (or (and ext-setup-or-nil
4618 (string-match re ext-setup-or-nil start)
4619 (setq start (match-end 0)))
4620 (and (setq ext-setup-or-nil nil start 0)
4621 (re-search-forward re nil t)))
4622 (setq key (upcase (match-string 1 ext-setup-or-nil))
4623 value (org-match-string-no-properties 2 ext-setup-or-nil))
4624 (if (stringp value) (setq value (org-trim value)))
4625 (cond
4626 ((equal key "CATEGORY")
4627 (setq cat value))
4628 ((member key '("SEQ_TODO" "TODO"))
4629 (push (cons 'sequence (org-split-string value splitre)) kwds))
4630 ((equal key "TYP_TODO")
4631 (push (cons 'type (org-split-string value splitre)) kwds))
4632 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4633 ;; general TODO-like setup
4634 (push (cons (intern (downcase (match-string 1 key)))
4635 (org-split-string value splitre)) kwds))
4636 ((equal key "TAGS")
4637 (setq tags (append tags (if tags '("\\n") nil)
4638 (org-split-string value splitre))))
4639 ((equal key "COLUMNS")
4640 (org-set-local 'org-columns-default-format value))
4641 ((equal key "LINK")
4642 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4643 (push (cons (match-string 1 value)
4644 (org-trim (match-string 2 value)))
4645 links)))
4646 ((equal key "PRIORITIES")
4647 (setq prio (org-split-string value " +")))
4648 ((equal key "PROPERTY")
4649 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4650 (setq props (org-update-property-plist (match-string 1 value)
4651 (match-string 2 value)
4652 props))))
4653 ((equal key "FILETAGS")
4654 (when (string-match "\\S-" value)
4655 (setq ftags
4656 (append
4657 ftags
4658 (apply 'append
4659 (mapcar (lambda (x) (org-split-string x ":"))
4660 (org-split-string value)))))))
4661 ((equal key "DRAWERS")
4662 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4663 ((equal key "CONSTANTS")
4664 (setq const (append const (org-split-string value splitre))))
4665 ((equal key "STARTUP")
4666 (let ((opts (org-split-string value splitre))
4667 l var val)
4668 (while (setq l (pop opts))
4669 (when (setq l (assoc l org-startup-options))
4670 (setq var (nth 1 l) val (nth 2 l))
4671 (if (not (nth 3 l))
4672 (set (make-local-variable var) val)
4673 (if (not (listp (symbol-value var)))
4674 (set (make-local-variable var) nil))
4675 (set (make-local-variable var) (symbol-value var))
4676 (add-to-list var val))))))
4677 ((equal key "ARCHIVE")
4678 (setq arch value)
4679 (remove-text-properties 0 (length arch)
4680 '(face t fontified t) arch))
4681 ((equal key "LATEX_CLASS")
4682 (setq beamer-p (equal value "beamer")))
4683 ((equal key "OPTIONS")
4684 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4685 (setq scripts (read (match-string 2 value)))))
4686 ((equal key "SETUPFILE")
4687 (setq setup-contents (org-file-contents
4688 (expand-file-name
4689 (org-remove-double-quotes value))
4690 'noerror))
4691 (if (not ext-setup-or-nil)
4692 (setq ext-setup-or-nil setup-contents start 0)
4693 (setq ext-setup-or-nil
4694 (concat (substring ext-setup-or-nil 0 start)
4695 "\n" setup-contents "\n"
4696 (substring ext-setup-or-nil start)))))))
4697 ;; search for property blocks
4698 (goto-char (point-min))
4699 (while (re-search-forward org-block-regexp nil t)
4700 (when (equal "PROPERTY" (upcase (match-string 1)))
4701 (setq value (replace-regexp-in-string
4702 "[\n\r]" " " (match-string 4)))
4703 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4704 (setq props (org-update-property-plist (match-string 1 value)
4705 (match-string 2 value)
4706 props)))))))
4707 (org-set-local 'org-use-sub-superscripts scripts)
4708 (when cat
4709 (org-set-local 'org-category (intern cat))
4710 (push (cons "CATEGORY" cat) props))
4711 (when prio
4712 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4713 (setq prio (mapcar 'string-to-char prio))
4714 (org-set-local 'org-highest-priority (nth 0 prio))
4715 (org-set-local 'org-lowest-priority (nth 1 prio))
4716 (org-set-local 'org-default-priority (nth 2 prio)))
4717 (and props (org-set-local 'org-file-properties (nreverse props)))
4718 (and ftags (org-set-local 'org-file-tags
4719 (mapcar 'org-add-prop-inherited ftags)))
4720 (and drawers (org-set-local 'org-drawers drawers))
4721 (and arch (org-set-local 'org-archive-location arch))
4722 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4723 ;; Process the TODO keywords
4724 (unless kwds
4725 ;; Use the global values as if they had been given locally.
4726 (setq kwds (default-value 'org-todo-keywords))
4727 (if (stringp (car kwds))
4728 (setq kwds (list (cons org-todo-interpretation
4729 (default-value 'org-todo-keywords)))))
4730 (setq kwds (reverse kwds)))
4731 (setq kwds (nreverse kwds))
4732 (let (inter kws kw)
4733 (while (setq kws (pop kwds))
4734 (let ((kws (or
4735 (run-hook-with-args-until-success
4736 'org-todo-setup-filter-hook kws)
4737 kws)))
4738 (setq inter (pop kws) sep (member "|" kws)
4739 kws0 (delete "|" (copy-sequence kws))
4740 kwsa nil
4741 kws1 (mapcar
4742 (lambda (x)
4743 ;; 1 2
4744 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4745 (progn
4746 (setq kw (match-string 1 x)
4747 key (and (match-end 2) (match-string 2 x))
4748 log (org-extract-log-state-settings x))
4749 (push (cons kw (and key (string-to-char key))) kwsa)
4750 (and log (push log org-todo-log-states))
4752 (error "Invalid TODO keyword %s" x)))
4753 kws0)
4754 kwsa (if kwsa (append '((:startgroup))
4755 (nreverse kwsa)
4756 '((:endgroup))))
4757 hw (car kws1)
4758 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4759 tail (list inter hw (car dws) (org-last dws))))
4760 (add-to-list 'org-todo-heads hw 'append)
4761 (push kws1 org-todo-sets)
4762 (setq org-done-keywords (append org-done-keywords dws nil))
4763 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4764 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4765 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4766 (setq org-todo-sets (nreverse org-todo-sets)
4767 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4768 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4769 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4770 ;; Process the constants
4771 (when const
4772 (let (e cst)
4773 (while (setq e (pop const))
4774 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4775 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4776 (setq org-table-formula-constants-local cst)))
4778 ;; Process the tags.
4779 (when tags
4780 (let (e tgs)
4781 (while (setq e (pop tags))
4782 (cond
4783 ((equal e "{") (push '(:startgroup) tgs))
4784 ((equal e "}") (push '(:endgroup) tgs))
4785 ((equal e "\\n") (push '(:newline) tgs))
4786 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4787 (push (cons (match-string 1 e)
4788 (string-to-char (match-string 2 e)))
4789 tgs))
4790 (t (push (list e) tgs))))
4791 (org-set-local 'org-tag-alist nil)
4792 (while (setq e (pop tgs))
4793 (or (and (stringp (car e))
4794 (assoc (car e) org-tag-alist))
4795 (push e org-tag-alist)))))
4797 ;; Compute the regular expressions and other local variables.
4798 ;; Using `org-outline-regexp-bol' would complicate them much,
4799 ;; because of the fixed white space at the end of that string.
4800 (if (not org-done-keywords)
4801 (setq org-done-keywords (and org-todo-keywords-1
4802 (list (org-last org-todo-keywords-1)))))
4803 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4804 (length org-scheduled-string)
4805 (length org-clock-string)
4806 (length org-closed-string)))
4807 org-drawer-regexp
4808 (concat "^[ \t]*:\\("
4809 (mapconcat 'regexp-quote org-drawers "\\|")
4810 "\\):[ \t]*$")
4811 org-not-done-keywords
4812 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4813 org-todo-regexp
4814 (concat "\\("
4815 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4816 "\\)")
4817 org-not-done-regexp
4818 (concat "\\("
4819 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4820 "\\)")
4821 org-not-done-heading-regexp
4822 (format org-heading-keyword-regexp-format org-not-done-regexp)
4823 org-todo-line-regexp
4824 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4825 org-complex-heading-regexp
4826 (concat "^\\(\\*+\\)"
4827 "\\(?: +" org-todo-regexp "\\)?"
4828 "\\(?: +\\(\\[#.\\]\\)\\)?"
4829 "\\(?: +\\(.*?\\)\\)??"
4830 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4831 "[ \t]*$")
4832 org-complex-heading-regexp-format
4833 (concat "^\\(\\*+\\)"
4834 "\\(?: +" org-todo-regexp "\\)?"
4835 "\\(?: +\\(\\[#.\\]\\)\\)?"
4836 "\\(?: +"
4837 ;; Stats cookies can be stuck to body.
4838 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4839 "\\(%s\\)"
4840 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4841 "\\)"
4842 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4843 "[ \t]*$")
4844 org-todo-line-tags-regexp
4845 (concat "^\\(\\*+\\)"
4846 "\\(?: +" org-todo-regexp "\\)?"
4847 "\\(?: +\\(.*?\\)\\)??"
4848 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4849 "[ \t]*$")
4850 org-deadline-regexp (concat "\\<" org-deadline-string)
4851 org-deadline-time-regexp
4852 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4853 org-deadline-line-regexp
4854 (concat "\\<\\(" org-deadline-string "\\).*")
4855 org-scheduled-regexp
4856 (concat "\\<" org-scheduled-string)
4857 org-scheduled-time-regexp
4858 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4859 org-closed-time-regexp
4860 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4861 org-keyword-time-regexp
4862 (concat "\\<\\(" org-scheduled-string
4863 "\\|" org-deadline-string
4864 "\\|" org-closed-string
4865 "\\|" org-clock-string "\\)"
4866 " *[[<]\\([^]>]+\\)[]>]")
4867 org-keyword-time-not-clock-regexp
4868 (concat "\\<\\(" org-scheduled-string
4869 "\\|" org-deadline-string
4870 "\\|" org-closed-string
4871 "\\)"
4872 " *[[<]\\([^]>]+\\)[]>]")
4873 org-maybe-keyword-time-regexp
4874 (concat "\\(\\<\\(" org-scheduled-string
4875 "\\|" org-deadline-string
4876 "\\|" org-closed-string
4877 "\\|" org-clock-string "\\)\\)?"
4878 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4879 org-all-time-keywords
4880 (mapcar (lambda (w) (substring w 0 -1))
4881 (list org-scheduled-string org-deadline-string
4882 org-clock-string org-closed-string))
4884 (org-compute-latex-and-specials-regexp)
4885 (org-set-font-lock-defaults))))
4887 (defun org-file-contents (file &optional noerror)
4888 "Return the contents of FILE, as a string."
4889 (if (or (not file)
4890 (not (file-readable-p file)))
4891 (if noerror
4892 (progn
4893 (message "Cannot read file \"%s\"" file)
4894 (ding) (sit-for 2)
4896 (error "Cannot read file \"%s\"" file))
4897 (with-temp-buffer
4898 (insert-file-contents file)
4899 (buffer-string))))
4901 (defun org-extract-log-state-settings (x)
4902 "Extract the log state setting from a TODO keyword string.
4903 This will extract info from a string like \"WAIT(w@/!)\"."
4904 (let (kw key log1 log2)
4905 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4906 (setq kw (match-string 1 x)
4907 key (and (match-end 2) (match-string 2 x))
4908 log1 (and (match-end 3) (match-string 3 x))
4909 log2 (and (match-end 4) (match-string 4 x)))
4910 (and (or log1 log2)
4911 (list kw
4912 (and log1 (if (equal log1 "!") 'time 'note))
4913 (and log2 (if (equal log2 "!") 'time 'note)))))))
4915 (defun org-remove-keyword-keys (list)
4916 "Remove a pair of parenthesis at the end of each string in LIST."
4917 (mapcar (lambda (x)
4918 (if (string-match "(.*)$" x)
4919 (substring x 0 (match-beginning 0))
4921 list))
4923 (defun org-assign-fast-keys (alist)
4924 "Assign fast keys to a keyword-key alist.
4925 Respect keys that are already there."
4926 (let (new e (alt ?0))
4927 (while (setq e (pop alist))
4928 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4929 (cdr e)) ;; Key already assigned.
4930 (push e new)
4931 (let ((clist (string-to-list (downcase (car e))))
4932 (used (append new alist)))
4933 (when (= (car clist) ?@)
4934 (pop clist))
4935 (while (and clist (rassoc (car clist) used))
4936 (pop clist))
4937 (unless clist
4938 (while (rassoc alt used)
4939 (incf alt)))
4940 (push (cons (car e) (or (car clist) alt)) new))))
4941 (nreverse new)))
4943 ;;; Some variables used in various places
4945 (defvar org-window-configuration nil
4946 "Used in various places to store a window configuration.")
4947 (defvar org-selected-window nil
4948 "Used in various places to store a window configuration.")
4949 (defvar org-finish-function nil
4950 "Function to be called when `C-c C-c' is used.
4951 This is for getting out of special buffers like remember.")
4954 ;; FIXME: Occasionally check by commenting these, to make sure
4955 ;; no other functions uses these, forgetting to let-bind them.
4956 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4957 (defvar org-last-state)
4958 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4960 ;; Defined somewhere in this file, but used before definition.
4961 (defvar org-entities) ;; defined in org-entities.el
4962 (defvar org-struct-menu)
4963 (defvar org-org-menu)
4964 (defvar org-tbl-menu)
4966 ;;;; Define the Org-mode
4968 ;; We use a before-change function to check if a table might need
4969 ;; an update.
4970 (defvar org-table-may-need-update t
4971 "Indicates that a table might need an update.
4972 This variable is set by `org-before-change-function'.
4973 `org-table-align' sets it back to nil.")
4974 (defun org-before-change-function (beg end)
4975 "Every change indicates that a table might need an update."
4976 (setq org-table-may-need-update t))
4977 (defvar org-mode-map)
4978 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4979 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4980 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4981 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4982 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4983 (defvar org-table-buffer-is-an nil)
4985 (defvar bidi-paragraph-direction)
4986 (defvar buffer-face-mode-face)
4988 (require 'outline)
4989 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4990 (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"))
4991 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4993 ;; Other stuff we need.
4994 (require 'time-date)
4995 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4996 (require 'easymenu)
4997 (require 'overlay)
4999 (require 'org-macs)
5000 (require 'org-entities)
5001 ;; (require 'org-compat) moved higher up in the file before it is first used
5002 (require 'org-faces)
5003 (require 'org-list)
5004 (require 'org-pcomplete)
5005 (require 'org-src)
5006 (require 'org-footnote)
5008 ;; babel
5009 (require 'ob)
5010 (require 'ob-table)
5011 (require 'ob-lob)
5012 (require 'ob-ref)
5013 (require 'ob-tangle)
5014 (require 'ob-comint)
5015 (require 'ob-keys)
5017 ;;;###autoload
5018 (define-derived-mode org-mode outline-mode "Org"
5019 "Outline-based notes management and organizer, alias
5020 \"Carsten's outline-mode for keeping track of everything.\"
5022 Org-mode develops organizational tasks around a NOTES file which
5023 contains information about projects as plain text. Org-mode is
5024 implemented on top of outline-mode, which is ideal to keep the content
5025 of large files well structured. It supports ToDo items, deadlines and
5026 time stamps, which magically appear in the diary listing of the Emacs
5027 calendar. Tables are easily created with a built-in table editor.
5028 Plain text URL-like links connect to websites, emails (VM), Usenet
5029 messages (Gnus), BBDB entries, and any files related to the project.
5030 For printing and sharing of notes, an Org-mode file (or a part of it)
5031 can be exported as a structured ASCII or HTML file.
5033 The following commands are available:
5035 \\{org-mode-map}"
5037 ;; Get rid of Outline menus, they are not needed
5038 ;; Need to do this here because define-derived-mode sets up
5039 ;; the keymap so late. Still, it is a waste to call this each time
5040 ;; we switch another buffer into org-mode.
5041 (if (featurep 'xemacs)
5042 (when (boundp 'outline-mode-menu-heading)
5043 ;; Assume this is Greg's port, it uses easymenu
5044 (easy-menu-remove outline-mode-menu-heading)
5045 (easy-menu-remove outline-mode-menu-show)
5046 (easy-menu-remove outline-mode-menu-hide))
5047 (define-key org-mode-map [menu-bar headings] 'undefined)
5048 (define-key org-mode-map [menu-bar hide] 'undefined)
5049 (define-key org-mode-map [menu-bar show] 'undefined))
5051 (org-load-modules-maybe)
5052 (easy-menu-add org-org-menu)
5053 (easy-menu-add org-tbl-menu)
5054 (org-install-agenda-files-menu)
5055 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5056 (add-to-invisibility-spec '(org-cwidth))
5057 (add-to-invisibility-spec '(org-hide-block . t))
5058 (when (featurep 'xemacs)
5059 (org-set-local 'line-move-ignore-invisible t))
5060 (org-set-local 'outline-regexp org-outline-regexp)
5061 (org-set-local 'outline-level 'org-outline-level)
5062 (setq bidi-paragraph-direction 'left-to-right)
5063 (when (and org-ellipsis
5064 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5065 (fboundp 'make-glyph-code))
5066 (unless org-display-table
5067 (setq org-display-table (make-display-table)))
5068 (set-display-table-slot
5069 org-display-table 4
5070 (vconcat (mapcar
5071 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5072 org-ellipsis)))
5073 (if (stringp org-ellipsis) org-ellipsis "..."))))
5074 (setq buffer-display-table org-display-table))
5075 (org-set-regexps-and-options)
5076 (when (and org-tag-faces (not org-tags-special-faces-re))
5077 ;; tag faces set outside customize.... force initialization.
5078 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5079 ;; Calc embedded
5080 (org-set-local 'calc-embedded-open-mode "# ")
5081 (modify-syntax-entry ?@ "w")
5082 (modify-syntax-entry ?\" "\"")
5083 (if org-startup-truncated (setq truncate-lines t))
5084 (org-set-local 'font-lock-unfontify-region-function
5085 'org-unfontify-region)
5086 ;; Activate before-change-function
5087 (org-set-local 'org-table-may-need-update t)
5088 (org-add-hook 'before-change-functions 'org-before-change-function nil
5089 'local)
5090 ;; Check for running clock before killing a buffer
5091 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5092 ;; Initialize macros templates.
5093 (org-macro-initialize-templates)
5094 ;; Initialize radio targets.
5095 (org-update-radio-target-regexp)
5096 ;; Indentation.
5097 (org-set-local 'indent-line-function 'org-indent-line)
5098 (org-set-local 'indent-region-function 'org-indent-region)
5099 ;; Filling and auto-filling.
5100 (org-setup-filling)
5101 ;; Comments.
5102 (org-setup-comments-handling)
5103 ;; Beginning/end of defun
5104 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5105 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5106 ;; Next error for sparse trees
5107 (org-set-local 'next-error-function 'org-occur-next-match)
5108 ;; Make sure dependence stuff works reliably, even for users who set it
5109 ;; too late :-(
5110 (if org-enforce-todo-dependencies
5111 (add-hook 'org-blocker-hook
5112 'org-block-todo-from-children-or-siblings-or-parent)
5113 (remove-hook 'org-blocker-hook
5114 'org-block-todo-from-children-or-siblings-or-parent))
5115 (if org-enforce-todo-checkbox-dependencies
5116 (add-hook 'org-blocker-hook
5117 'org-block-todo-from-checkboxes)
5118 (remove-hook 'org-blocker-hook
5119 'org-block-todo-from-checkboxes))
5121 ;; Align options lines
5122 (org-set-local
5123 'align-mode-rules-list
5124 '((org-in-buffer-settings
5125 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5126 (modes . '(org-mode)))))
5128 ;; Imenu
5129 (org-set-local 'imenu-create-index-function
5130 'org-imenu-get-tree)
5132 ;; Make isearch reveal context
5133 (if (or (featurep 'xemacs)
5134 (not (boundp 'outline-isearch-open-invisible-function)))
5135 ;; Emacs 21 and XEmacs make use of the hook
5136 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5137 ;; Emacs 22 deals with this through a special variable
5138 (org-set-local 'outline-isearch-open-invisible-function
5139 (lambda (&rest ignore) (org-show-context 'isearch))))
5141 ;; Turn on org-beamer-mode?
5142 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5144 ;; Setup the pcomplete hooks
5145 (set (make-local-variable 'pcomplete-command-completion-function)
5146 'org-pcomplete-initial)
5147 (set (make-local-variable 'pcomplete-command-name-function)
5148 'org-command-at-point)
5149 (set (make-local-variable 'pcomplete-default-completion-function)
5150 'ignore)
5151 (set (make-local-variable 'pcomplete-parse-arguments-function)
5152 'org-parse-arguments)
5153 (set (make-local-variable 'pcomplete-termination-string) "")
5154 (when (>= emacs-major-version 23)
5155 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5157 ;; If empty file that did not turn on org-mode automatically, make it to.
5158 (if (and org-insert-mode-line-in-empty-file
5159 (org-called-interactively-p 'any)
5160 (= (point-min) (point-max)))
5161 (insert "# -*- mode: org -*-\n\n"))
5162 (unless org-inhibit-startup
5163 (when org-startup-align-all-tables
5164 (let ((bmp (buffer-modified-p)))
5165 (org-table-map-tables 'org-table-align 'quietly)
5166 (set-buffer-modified-p bmp)))
5167 (when org-startup-with-inline-images
5168 (org-display-inline-images))
5169 (when org-startup-indented
5170 (require 'org-indent)
5171 (org-indent-mode 1))
5172 (unless org-inhibit-startup-visibility-stuff
5173 (org-set-startup-visibility))))
5175 (when (fboundp 'abbrev-table-put)
5176 (abbrev-table-put org-mode-abbrev-table
5177 :parents (list text-mode-abbrev-table)))
5179 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5181 (defun org-current-time ()
5182 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5183 (if (> (car org-time-stamp-rounding-minutes) 1)
5184 (let ((r (car org-time-stamp-rounding-minutes))
5185 (time (decode-time)))
5186 (apply 'encode-time
5187 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5188 (nthcdr 2 time))))
5189 (current-time)))
5191 (defun org-today ()
5192 "Return today date, considering `org-extend-today-until'."
5193 (time-to-days
5194 (time-subtract (current-time)
5195 (list 0 (* 3600 org-extend-today-until) 0))))
5197 ;;;; Font-Lock stuff, including the activators
5199 (defvar org-mouse-map (make-sparse-keymap))
5200 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5201 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5202 (when org-mouse-1-follows-link
5203 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5204 (when org-tab-follows-link
5205 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5206 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5208 (require 'font-lock)
5210 (defconst org-non-link-chars "]\t\n\r<>")
5211 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5212 "shell" "elisp" "doi" "message"))
5213 (defvar org-link-types-re nil
5214 "Matches a link that has a url-like prefix like \"http:\"")
5215 (defvar org-link-re-with-space nil
5216 "Matches a link with spaces, optional angular brackets around it.")
5217 (defvar org-link-re-with-space2 nil
5218 "Matches a link with spaces, optional angular brackets around it.")
5219 (defvar org-link-re-with-space3 nil
5220 "Matches a link with spaces, only for internal part in bracket links.")
5221 (defvar org-angle-link-re nil
5222 "Matches link with angular brackets, spaces are allowed.")
5223 (defvar org-plain-link-re nil
5224 "Matches plain link, without spaces.")
5225 (defvar org-bracket-link-regexp nil
5226 "Matches a link in double brackets.")
5227 (defvar org-bracket-link-analytic-regexp nil
5228 "Regular expression used to analyze links.
5229 Here is what the match groups contain after a match:
5230 1: http:
5231 2: http
5232 3: path
5233 4: [desc]
5234 5: desc")
5235 (defvar org-bracket-link-analytic-regexp++ nil
5236 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5237 (defvar org-any-link-re nil
5238 "Regular expression matching any link.")
5240 (defcustom org-match-sexp-depth 3
5241 "Number of stacked braces for sub/superscript matching.
5242 This has to be set before loading org.el to be effective."
5243 :group 'org-export-translation ; ??????????????????????????/
5244 :type 'integer)
5246 (defun org-create-multibrace-regexp (left right n)
5247 "Create a regular expression which will match a balanced sexp.
5248 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5249 as single character strings.
5250 The regexp returned will match the entire expression including the
5251 delimiters. It will also define a single group which contains the
5252 match except for the outermost delimiters. The maximum depth of
5253 stacked delimiters is N. Escaping delimiters is not possible."
5254 (let* ((nothing (concat "[^" left right "]*?"))
5255 (or "\\|")
5256 (re nothing)
5257 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5258 (while (> n 1)
5259 (setq n (1- n)
5260 re (concat re or next)
5261 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5262 (concat left "\\(" re "\\)" right)))
5264 (defvar org-match-substring-regexp
5265 (concat
5266 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5267 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5268 "\\|"
5269 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5270 "\\|"
5271 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5272 "The regular expression matching a sub- or superscript.")
5274 (defvar org-match-substring-with-braces-regexp
5275 (concat
5276 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5277 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5278 "\\)")
5279 "The regular expression matching a sub- or superscript, forcing braces.")
5281 (defun org-make-link-regexps ()
5282 "Update the link regular expressions.
5283 This should be called after the variable `org-link-types' has changed."
5284 (setq org-link-types-re
5285 (concat
5286 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5287 org-link-re-with-space
5288 (concat
5289 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5290 "\\([^" org-non-link-chars " ]"
5291 "[^" org-non-link-chars "]*"
5292 "[^" org-non-link-chars " ]\\)>?")
5293 org-link-re-with-space2
5294 (concat
5295 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5296 "\\([^" org-non-link-chars " ]"
5297 "[^\t\n\r]*"
5298 "[^" org-non-link-chars " ]\\)>?")
5299 org-link-re-with-space3
5300 (concat
5301 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5302 "\\([^" org-non-link-chars " ]"
5303 "[^\t\n\r]*\\)")
5304 org-angle-link-re
5305 (concat
5306 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5307 "\\([^" org-non-link-chars " ]"
5308 "[^" org-non-link-chars "]*"
5309 "\\)>")
5310 org-plain-link-re
5311 (concat
5312 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5313 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5314 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5315 org-bracket-link-regexp
5316 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5317 org-bracket-link-analytic-regexp
5318 (concat
5319 "\\[\\["
5320 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5321 "\\([^]]+\\)"
5322 "\\]"
5323 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5324 "\\]")
5325 org-bracket-link-analytic-regexp++
5326 (concat
5327 "\\[\\["
5328 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5329 "\\([^]]+\\)"
5330 "\\]"
5331 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5332 "\\]")
5333 org-any-link-re
5334 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5335 org-angle-link-re "\\)\\|\\("
5336 org-plain-link-re "\\)")))
5338 (org-make-link-regexps)
5340 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5341 "Regular expression for fast time stamp matching.")
5342 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5343 "Regular expression for fast time stamp matching.")
5344 (defconst org-ts-regexp0
5345 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5346 "Regular expression matching time strings for analysis.
5347 This one does not require the space after the date, so it can be used
5348 on a string that terminates immediately after the date.")
5349 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5350 "Regular expression matching time strings for analysis.")
5351 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5352 "Regular expression matching time stamps, with groups.")
5353 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5354 "Regular expression matching time stamps (also [..]), with groups.")
5355 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5356 "Regular expression matching a time stamp range.")
5357 (defconst org-tr-regexp-both
5358 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5359 "Regular expression matching a time stamp range.")
5360 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5361 org-ts-regexp "\\)?")
5362 "Regular expression matching a time stamp or time stamp range.")
5363 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5364 org-ts-regexp-both "\\)?")
5365 "Regular expression matching a time stamp or time stamp range.
5366 The time stamps may be either active or inactive.")
5368 (defvar org-emph-face nil)
5370 (defun org-do-emphasis-faces (limit)
5371 "Run through the buffer and add overlays to emphasized strings."
5372 (let (rtn a)
5373 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5374 (if (not (= (char-after (match-beginning 3))
5375 (char-after (match-beginning 4))))
5376 (progn
5377 (setq rtn t)
5378 (setq a (assoc (match-string 3) org-emphasis-alist))
5379 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5380 'face
5381 (nth 1 a))
5382 (and (nth 4 a)
5383 (org-remove-flyspell-overlays-in
5384 (match-beginning 0) (match-end 0)))
5385 (add-text-properties (match-beginning 2) (match-end 2)
5386 '(font-lock-multiline t org-emphasis t))
5387 (when org-hide-emphasis-markers
5388 (add-text-properties (match-end 4) (match-beginning 5)
5389 '(invisible org-link))
5390 (add-text-properties (match-beginning 3) (match-end 3)
5391 '(invisible org-link)))))
5392 (backward-char 1))
5393 rtn))
5395 (defun org-emphasize (&optional char)
5396 "Insert or change an emphasis, i.e. a font like bold or italic.
5397 If there is an active region, change that region to a new emphasis.
5398 If there is no region, just insert the marker characters and position
5399 the cursor between them.
5400 CHAR should be either the marker character, or the first character of the
5401 HTML tag associated with that emphasis. If CHAR is a space, the means
5402 to remove the emphasis of the selected region.
5403 If char is not given (for example in an interactive call) it
5404 will be prompted for."
5405 (interactive)
5406 (let ((eal org-emphasis-alist) e det
5407 (erc org-emphasis-regexp-components)
5408 (prompt "")
5409 (string "") beg end move tag c s)
5410 (if (org-region-active-p)
5411 (setq beg (region-beginning) end (region-end)
5412 string (buffer-substring beg end))
5413 (setq move t))
5415 (while (setq e (pop eal))
5416 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5417 c (aref tag 0))
5418 (push (cons c (string-to-char (car e))) det)
5419 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5420 (substring tag 1)))))
5421 (setq det (nreverse det))
5422 (unless char
5423 (message "%s" (concat "Emphasis marker or tag:" prompt))
5424 (setq char (read-char-exclusive)))
5425 (setq char (or (cdr (assoc char det)) char))
5426 (if (equal char ?\ )
5427 (setq s "" move nil)
5428 (unless (assoc (char-to-string char) org-emphasis-alist)
5429 (error "No such emphasis marker: \"%c\"" char))
5430 (setq s (char-to-string char)))
5431 (while (and (> (length string) 1)
5432 (equal (substring string 0 1) (substring string -1))
5433 (assoc (substring string 0 1) org-emphasis-alist))
5434 (setq string (substring string 1 -1)))
5435 (setq string (concat s string s))
5436 (if beg (delete-region beg end))
5437 (unless (or (bolp)
5438 (string-match (concat "[" (nth 0 erc) "\n]")
5439 (char-to-string (char-before (point)))))
5440 (insert " "))
5441 (unless (or (eobp)
5442 (string-match (concat "[" (nth 1 erc) "\n]")
5443 (char-to-string (char-after (point)))))
5444 (insert " ") (backward-char 1))
5445 (insert string)
5446 (and move (backward-char 1))))
5448 (defconst org-nonsticky-props
5449 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5451 (defsubst org-rear-nonsticky-at (pos)
5452 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5454 (defun org-activate-plain-links (limit)
5455 "Run through the buffer and add overlays to links."
5456 (catch 'exit
5457 (let (f)
5458 (if (and (re-search-forward (concat org-plain-link-re) limit t)
5459 (or (not (member 'bracket org-activate-links))
5460 (save-excursion
5461 (save-match-data
5462 (goto-char (match-beginning 0))
5463 (not (looking-back "\\[\\["))))))
5464 (progn
5465 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5466 (setq f (get-text-property (match-beginning 0) 'face))
5467 (if (or (eq f 'org-tag)
5468 (and (listp f) (memq 'org-tag f)))
5470 (add-text-properties (match-beginning 0) (match-end 0)
5471 (list 'mouse-face 'highlight
5472 'face 'org-link
5473 'keymap org-mouse-map))
5474 (org-rear-nonsticky-at (match-end 0)))
5475 t)))))
5477 (defun org-activate-code (limit)
5478 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5479 (progn
5480 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5481 (remove-text-properties (match-beginning 0) (match-end 0)
5482 '(display t invisible t intangible t))
5483 t)))
5485 (defcustom org-src-fontify-natively nil
5486 "When non-nil, fontify code in code blocks."
5487 :type 'boolean
5488 :version "24.1"
5489 :group 'org-appearance
5490 :group 'org-babel)
5492 (defcustom org-allow-promoting-top-level-subtree nil
5493 "When non-nil, allow promoting a top level subtree.
5494 The leading star of the top level headline will be replaced
5495 by a #."
5496 :type 'boolean
5497 :version "24.1"
5498 :group 'org-appearance)
5500 (defun org-fontify-meta-lines-and-blocks (limit)
5501 (condition-case nil
5502 (org-fontify-meta-lines-and-blocks-1 limit)
5503 (error (message "org-mode fontification error"))))
5505 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5506 "Fontify #+ lines and blocks, in the correct ways."
5507 (let ((case-fold-search t))
5508 (if (re-search-forward
5509 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5510 limit t)
5511 (let ((beg (match-beginning 0))
5512 (block-start (match-end 0))
5513 (block-end nil)
5514 (lang (match-string 7))
5515 (beg1 (line-beginning-position 2))
5516 (dc1 (downcase (match-string 2)))
5517 (dc3 (downcase (match-string 3)))
5518 end end1 quoting block-type ovl)
5519 (cond
5520 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5521 ;; a single line of backend-specific content
5522 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5523 (remove-text-properties (match-beginning 0) (match-end 0)
5524 '(display t invisible t intangible t))
5525 (add-text-properties (match-beginning 1) (match-end 3)
5526 '(font-lock-fontified t face org-meta-line))
5527 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5528 '(font-lock-fontified t face org-block))
5529 ; for backend-specific code
5531 ((and (match-end 4) (equal dc3 "+begin"))
5532 ;; Truly a block
5533 (setq block-type (downcase (match-string 5))
5534 quoting (member block-type org-protecting-blocks))
5535 (when (re-search-forward
5536 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5537 nil t) ;; on purpose, we look further than LIMIT
5538 (setq end (min (point-max) (match-end 0))
5539 end1 (min (point-max) (1- (match-beginning 0))))
5540 (setq block-end (match-beginning 0))
5541 (when quoting
5542 (remove-text-properties beg end
5543 '(display t invisible t intangible t)))
5544 (add-text-properties
5545 beg end
5546 '(font-lock-fontified t font-lock-multiline t))
5547 (add-text-properties beg beg1 '(face org-meta-line))
5548 (add-text-properties end1 (min (point-max) (1+ end))
5549 '(face org-meta-line)) ; for end_src
5550 (cond
5551 ((and lang (not (string= lang "")) org-src-fontify-natively)
5552 (org-src-font-lock-fontify-block lang block-start block-end)
5553 ;; remove old background overlays
5554 (mapc (lambda (ov)
5555 (if (eq (overlay-get ov 'face) 'org-block-background)
5556 (delete-overlay ov)))
5557 (overlays-at (/ (+ beg1 block-end) 2)))
5558 ;; add a background overlay
5559 (setq ovl (make-overlay beg1 block-end))
5560 (overlay-put ovl 'face 'org-block-background)
5561 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5562 (quoting
5563 (add-text-properties beg1 (min (point-max) (1+ end1))
5564 '(face org-block))) ; end of source block
5565 ((not org-fontify-quote-and-verse-blocks))
5566 ((string= block-type "quote")
5567 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5568 ((string= block-type "verse")
5569 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5570 (add-text-properties beg beg1 '(face org-block-begin-line))
5571 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5572 '(face org-block-end-line))
5574 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5575 (add-text-properties
5576 beg (match-end 3)
5577 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5578 '(font-lock-fontified t invisible t)
5579 '(font-lock-fontified t face org-document-info-keyword)))
5580 (add-text-properties
5581 (match-beginning 6) (match-end 6)
5582 (if (string-equal dc1 "+title:")
5583 '(font-lock-fontified t face org-document-title)
5584 '(font-lock-fontified t face org-document-info))))
5585 ((or (equal dc1 "+results")
5586 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5587 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5588 "+call:" "+header:" "+headers:" "+name:"))
5589 (and (match-end 4) (equal dc3 "+attr")))
5590 (add-text-properties
5591 beg (match-end 0)
5592 '(font-lock-fontified t face org-meta-line))
5594 ((member dc3 '(" " ""))
5595 (add-text-properties
5596 beg (match-end 0)
5597 '(font-lock-fontified t face font-lock-comment-face)))
5598 ((not (member (char-after beg) '(?\ ?\t)))
5599 ;; just any other in-buffer setting, but not indented
5600 (add-text-properties
5601 beg (match-end 0)
5602 '(font-lock-fontified t face org-meta-line))
5604 (t nil))))))
5606 (defun org-strip-protective-commas (beg end)
5607 "Strip protective commas between BEG and END in the current buffer."
5608 (interactive "r")
5609 (save-excursion
5610 (save-match-data
5611 (goto-char beg)
5612 (let ((front-line (save-excursion
5613 (re-search-forward
5614 "[^[:space:]]" end t)
5615 (goto-char (match-beginning 0))
5616 (current-column))))
5617 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5618 (goto-char (match-beginning 1))
5619 (when (= (current-column) front-line)
5620 (replace-match "" nil nil nil 1)))))))
5622 (defun org-activate-angle-links (limit)
5623 "Run through the buffer and add overlays to links."
5624 (if (re-search-forward org-angle-link-re limit t)
5625 (progn
5626 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5627 (add-text-properties (match-beginning 0) (match-end 0)
5628 (list 'mouse-face 'highlight
5629 'keymap org-mouse-map))
5630 (org-rear-nonsticky-at (match-end 0))
5631 t)))
5633 (defun org-activate-footnote-links (limit)
5634 "Run through the buffer and add overlays to footnotes."
5635 (let ((fn (org-footnote-next-reference-or-definition limit)))
5636 (when fn
5637 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5638 (org-remove-flyspell-overlays-in beg end)
5639 (add-text-properties beg end
5640 (list 'mouse-face 'highlight
5641 'keymap org-mouse-map
5642 'help-echo
5643 (if (= (point-at-bol) beg)
5644 "Footnote definition"
5645 "Footnote reference")
5646 'font-lock-fontified t
5647 'font-lock-multiline t
5648 'face 'org-footnote))))))
5650 (defun org-activate-bracket-links (limit)
5651 "Run through the buffer and add overlays to bracketed links."
5652 (if (re-search-forward org-bracket-link-regexp limit t)
5653 (let* ((help (concat "LINK: "
5654 (org-match-string-no-properties 1)))
5655 ;; FIXME: above we should remove the escapes.
5656 ;; but that requires another match, protecting match data,
5657 ;; a lot of overhead for font-lock.
5658 (ip (org-maybe-intangible
5659 (list 'invisible 'org-link
5660 'keymap org-mouse-map 'mouse-face 'highlight
5661 'font-lock-multiline t 'help-echo help)))
5662 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5663 'font-lock-multiline t 'help-echo help)))
5664 ;; We need to remove the invisible property here. Table narrowing
5665 ;; may have made some of this invisible.
5666 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5667 (remove-text-properties (match-beginning 0) (match-end 0)
5668 '(invisible nil))
5669 (if (match-end 3)
5670 (progn
5671 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5672 (org-rear-nonsticky-at (match-beginning 3))
5673 (add-text-properties (match-beginning 3) (match-end 3) vp)
5674 (org-rear-nonsticky-at (match-end 3))
5675 (add-text-properties (match-end 3) (match-end 0) ip)
5676 (org-rear-nonsticky-at (match-end 0)))
5677 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5678 (org-rear-nonsticky-at (match-beginning 1))
5679 (add-text-properties (match-beginning 1) (match-end 1) vp)
5680 (org-rear-nonsticky-at (match-end 1))
5681 (add-text-properties (match-end 1) (match-end 0) ip)
5682 (org-rear-nonsticky-at (match-end 0)))
5683 t)))
5685 (defun org-activate-dates (limit)
5686 "Run through the buffer and add overlays to dates."
5687 (if (re-search-forward org-tsr-regexp-both limit t)
5688 (progn
5689 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5690 (add-text-properties (match-beginning 0) (match-end 0)
5691 (list 'mouse-face 'highlight
5692 'keymap org-mouse-map))
5693 (org-rear-nonsticky-at (match-end 0))
5694 (when org-display-custom-times
5695 (if (match-end 3)
5696 (org-display-custom-time (match-beginning 3) (match-end 3)))
5697 (org-display-custom-time (match-beginning 1) (match-end 1)))
5698 t)))
5700 (defvar org-target-link-regexp nil
5701 "Regular expression matching radio targets in plain text.")
5702 (make-variable-buffer-local 'org-target-link-regexp)
5703 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5704 "Regular expression matching a link target.")
5705 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5706 "Regular expression matching a radio target.")
5707 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5708 "Regular expression matching any target.")
5710 (defun org-activate-target-links (limit)
5711 "Run through the buffer and add overlays to target matches."
5712 (when org-target-link-regexp
5713 (let ((case-fold-search t))
5714 (if (re-search-forward org-target-link-regexp limit t)
5715 (progn
5716 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5717 (add-text-properties (match-beginning 0) (match-end 0)
5718 (list 'mouse-face 'highlight
5719 'keymap org-mouse-map
5720 'help-echo "Radio target link"
5721 'org-linked-text t))
5722 (org-rear-nonsticky-at (match-end 0))
5723 t)))))
5725 (defun org-update-radio-target-regexp ()
5726 "Find all radio targets in this file and update the regular expression."
5727 (interactive)
5728 (when (memq 'radio org-activate-links)
5729 (setq org-target-link-regexp
5730 (org-make-target-link-regexp (org-all-targets 'radio)))
5731 (org-restart-font-lock)))
5733 (defun org-hide-wide-columns (limit)
5734 (let (s e)
5735 (setq s (text-property-any (point) (or limit (point-max))
5736 'org-cwidth t))
5737 (when s
5738 (setq e (next-single-property-change s 'org-cwidth))
5739 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5740 (goto-char e)
5741 t)))
5743 (defvar org-latex-and-specials-regexp nil
5744 "Regular expression for highlighting export special stuff.")
5745 (defvar org-match-substring-regexp)
5746 (defvar org-match-substring-with-braces-regexp)
5748 ;; This should be with the exporter code, but we also use if for font-locking
5749 (defconst org-export-html-special-string-regexps
5750 '(("\\\\-" . "&shy;")
5751 ("---\\([^-]\\)" . "&mdash;\\1")
5752 ("--\\([^-]\\)" . "&ndash;\\1")
5753 ("\\.\\.\\." . "&hellip;"))
5754 "Regular expressions for special string conversion.")
5757 (defun org-compute-latex-and-specials-regexp ()
5758 "Compute regular expression for stuff treated specially by exporters."
5759 (if (not org-highlight-latex-fragments-and-specials)
5760 (org-set-local 'org-latex-and-specials-regexp nil)
5761 (require 'org-exp)
5762 (let*
5763 ((matchers (plist-get org-format-latex-options :matchers))
5764 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5765 org-latex-regexps)))
5766 (org-export-allow-BIND nil)
5767 (options (org-combine-plists (org-default-export-plist)
5768 (org-infile-export-plist)))
5769 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5770 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5771 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5772 (org-export-html-expand (plist-get options :expand-quoted-html))
5773 (org-export-with-special-strings (plist-get options :special-strings))
5774 (re-sub
5775 (cond
5776 ((equal org-export-with-sub-superscripts '{})
5777 (list org-match-substring-with-braces-regexp))
5778 (org-export-with-sub-superscripts
5779 (list org-match-substring-regexp))))
5780 (re-latex
5781 (if org-export-with-LaTeX-fragments
5782 (mapcar (lambda (x) (nth 1 x)) latexs)))
5783 (re-macros
5784 (if org-export-with-TeX-macros
5785 (list (concat "\\\\"
5786 (regexp-opt
5787 (append
5789 (delq nil
5790 (mapcar 'car-safe
5791 (append org-entities-user
5792 org-entities)))
5793 (if (boundp 'org-latex-entities)
5794 (mapcar (lambda (x)
5795 (or (car-safe x) x))
5796 org-latex-entities)
5797 nil))
5798 'words))) ; FIXME
5800 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5801 (re-special (if org-export-with-special-strings
5802 (mapcar (lambda (x) (car x))
5803 org-export-html-special-string-regexps)))
5804 (re-rest
5805 (delq nil
5806 (list
5807 (if org-export-html-expand "@<[^>\n]+>")
5808 ))))
5809 (org-set-local
5810 'org-latex-and-specials-regexp
5811 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5812 re-rest) "\\|")))))
5814 (defun org-do-latex-and-special-faces (limit)
5815 "Run through the buffer and add overlays to links."
5816 (when org-latex-and-specials-regexp
5817 (let (rtn d)
5818 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5819 limit t))
5820 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5821 'face))
5822 '(org-code org-verbatim underline)))
5823 (progn
5824 (setq rtn t
5825 d (cond ((member (char-after (1+ (match-beginning 0)))
5826 '(?_ ?^)) 1)
5827 (t 0)))
5828 (font-lock-prepend-text-property
5829 (+ d (match-beginning 0)) (match-end 0)
5830 'face 'org-latex-and-export-specials)
5831 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5832 '(font-lock-multiline t)))))
5833 rtn)))
5835 (defun org-restart-font-lock ()
5836 "Restart `font-lock-mode', to force refontification."
5837 (when (and (boundp 'font-lock-mode) font-lock-mode)
5838 (font-lock-mode -1)
5839 (font-lock-mode 1)))
5841 (defun org-all-targets (&optional radio)
5842 "Return a list of all targets in this file.
5843 With optional argument RADIO, only find radio targets."
5844 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5845 rtn)
5846 (save-excursion
5847 (goto-char (point-min))
5848 (while (re-search-forward re nil t)
5849 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5850 rtn)))
5852 (defun org-make-target-link-regexp (targets)
5853 "Make regular expression matching all strings in TARGETS.
5854 The regular expression finds the targets also if there is a line break
5855 between words."
5856 (and targets
5857 (concat
5858 "\\<\\("
5859 (mapconcat
5860 (lambda (x)
5861 (setq x (regexp-quote x))
5862 (while (string-match " +" x)
5863 (setq x (replace-match "\\s-+" t t x)))
5865 targets
5866 "\\|")
5867 "\\)\\>")))
5869 (defun org-activate-tags (limit)
5870 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5871 (progn
5872 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5873 (add-text-properties (match-beginning 1) (match-end 1)
5874 (list 'mouse-face 'highlight
5875 'keymap org-mouse-map))
5876 (org-rear-nonsticky-at (match-end 1))
5877 t)))
5879 (defun org-outline-level ()
5880 "Compute the outline level of the heading at point.
5881 This function assumes that the cursor is at the beginning of a line matched
5882 by `outline-regexp'. Otherwise it returns garbage.
5883 If this is called at a normal headline, the level is the number of stars.
5884 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5885 (save-excursion
5886 (looking-at org-outline-regexp)
5887 (1- (- (match-end 0) (match-beginning 0)))))
5889 (defvar org-font-lock-keywords nil)
5891 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5892 "Regular expression matching a property line.")
5894 (defvar org-font-lock-hook nil
5895 "Functions to be called for special font lock stuff.")
5897 (defvar org-font-lock-set-keywords-hook nil
5898 "Functions that can manipulate `org-font-lock-extra-keywords'.
5899 This is called after `org-font-lock-extra-keywords' is defined, but before
5900 it is installed to be used by font lock. This can be useful if something
5901 needs to be inserted at a specific position in the font-lock sequence.")
5903 (defun org-font-lock-hook (limit)
5904 (run-hook-with-args 'org-font-lock-hook limit))
5906 (defun org-set-font-lock-defaults ()
5907 (let* ((em org-fontify-emphasized-text)
5908 (lk org-activate-links)
5909 (org-font-lock-extra-keywords
5910 (list
5911 ;; Call the hook
5912 '(org-font-lock-hook)
5913 ;; Headlines
5914 `(,(if org-fontify-whole-heading-line
5915 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5916 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5917 (1 (org-get-level-face 1))
5918 (2 (org-get-level-face 2))
5919 (3 (org-get-level-face 3)))
5920 ;; Table lines
5921 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5922 (1 'org-table t))
5923 ;; Table internals
5924 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5925 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5926 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5927 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5928 ;; Drawers
5929 (list org-drawer-regexp '(0 'org-special-keyword t))
5930 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5931 ;; Properties
5932 (list org-property-re
5933 '(1 'org-special-keyword t)
5934 '(3 'org-property-value t))
5935 ;; Links
5936 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5937 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5938 (if (memq 'plain lk) '(org-activate-plain-links))
5939 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5940 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5941 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5942 (if (memq 'footnote lk) '(org-activate-footnote-links))
5943 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5944 '(org-hide-wide-columns (0 nil append))
5945 ;; TODO keyword
5946 (list (format org-heading-keyword-regexp-format
5947 org-todo-regexp)
5948 '(2 (org-get-todo-face 2) t))
5949 ;; DONE
5950 (if org-fontify-done-headline
5951 (list (format org-heading-keyword-regexp-format
5952 (concat
5953 "\\(?:"
5954 (mapconcat 'regexp-quote org-done-keywords "\\|")
5955 "\\)"))
5956 '(2 'org-headline-done t))
5957 nil)
5958 ;; Priorities
5959 '(org-font-lock-add-priority-faces)
5960 ;; Tags
5961 '(org-font-lock-add-tag-faces)
5962 ;; Special keywords
5963 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5964 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5965 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5966 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5967 ;; Emphasis
5968 (if em
5969 (if (featurep 'xemacs)
5970 '(org-do-emphasis-faces (0 nil append))
5971 '(org-do-emphasis-faces)))
5972 ;; Checkboxes
5973 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5974 1 'org-checkbox prepend)
5975 (if (cdr (assq 'checkbox org-list-automatic-rules))
5976 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5977 (0 (org-get-checkbox-statistics-face) t)))
5978 ;; Description list items
5979 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5980 1 'org-list-dt prepend)
5981 ;; ARCHIVEd headings
5982 (list (concat
5983 org-outline-regexp-bol
5984 "\\(.*:" org-archive-tag ":.*\\)")
5985 '(1 'org-archived prepend))
5986 ;; Specials
5987 '(org-do-latex-and-special-faces)
5988 '(org-fontify-entities)
5989 '(org-raise-scripts)
5990 ;; Code
5991 '(org-activate-code (1 'org-code t))
5992 ;; COMMENT
5993 (list (format org-heading-keyword-regexp-format
5994 (concat "\\("
5995 org-comment-string "\\|" org-quote-string
5996 "\\)"))
5997 '(2 'org-special-keyword t))
5998 ;; Blocks and meta lines
5999 '(org-fontify-meta-lines-and-blocks)
6001 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6002 (run-hooks 'org-font-lock-set-keywords-hook)
6003 ;; Now set the full font-lock-keywords
6004 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6005 (org-set-local 'font-lock-defaults
6006 '(org-font-lock-keywords t nil nil backward-paragraph))
6007 (kill-local-variable 'font-lock-keywords) nil))
6009 (defun org-toggle-pretty-entities ()
6010 "Toggle the composition display of entities as UTF8 characters."
6011 (interactive)
6012 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6013 (org-restart-font-lock)
6014 (if org-pretty-entities
6015 (message "Entities are displayed as UTF8 characters")
6016 (save-restriction
6017 (widen)
6018 (org-decompose-region (point-min) (point-max))
6019 (message "Entities are displayed plain"))))
6021 (defvar org-custom-properties-overlays nil
6022 "List of overlays used for custom properties.")
6023 (make-variable-buffer-local 'org-custom-properties-overlays)
6025 (defun org-toggle-custom-properties-visibility ()
6026 "Display or hide properties in `org-custom-properties'."
6027 (interactive)
6028 (if org-custom-properties-overlays
6029 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6030 (setq org-custom-properties-overlays nil))
6031 (unless (not org-custom-properties)
6032 (save-excursion
6033 (save-restriction
6034 (widen)
6035 (goto-char (point-min))
6036 (while (re-search-forward org-property-re nil t)
6037 (mapc (lambda(p)
6038 (when (equal p (substring (match-string 1) 1 -1))
6039 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6040 (overlay-put o 'invisible t)
6041 (overlay-put o 'org-custom-property t)
6042 (push o org-custom-properties-overlays))))
6043 org-custom-properties)))))))
6045 (defun org-fontify-entities (limit)
6046 "Find an entity to fontify."
6047 (let (ee)
6048 (when org-pretty-entities
6049 (catch 'match
6050 (while (re-search-forward
6051 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6052 limit t)
6053 (if (and (not (org-in-indented-comment-line))
6054 (setq ee (org-entity-get (match-string 1)))
6055 (= (length (nth 6 ee)) 1))
6056 (let*
6057 ((end (if (equal (match-string 2) "{}")
6058 (match-end 2)
6059 (match-end 1))))
6060 (add-text-properties
6061 (match-beginning 0) end
6062 (list 'font-lock-fontified t))
6063 (compose-region (match-beginning 0) end
6064 (nth 6 ee) nil)
6065 (backward-char 1)
6066 (throw 'match t))))
6067 nil))))
6069 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6070 "Fontify string S like in Org-mode."
6071 (with-temp-buffer
6072 (insert s)
6073 (let ((org-odd-levels-only odd-levels))
6074 (org-mode)
6075 (font-lock-fontify-buffer)
6076 (buffer-string))))
6078 (defvar org-m nil)
6079 (defvar org-l nil)
6080 (defvar org-f nil)
6081 (defun org-get-level-face (n)
6082 "Get the right face for match N in font-lock matching of headlines."
6083 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6084 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6085 (if org-cycle-level-faces
6086 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6087 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6088 (cond
6089 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6090 ((eq n 2) org-f)
6091 (t (if org-level-color-stars-only nil org-f))))
6094 (defun org-get-todo-face (kwd)
6095 "Get the right face for a TODO keyword KWD.
6096 If KWD is a number, get the corresponding match group."
6097 (if (numberp kwd) (setq kwd (match-string kwd)))
6098 (or (org-face-from-face-or-color
6099 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6100 (and (member kwd org-done-keywords) 'org-done)
6101 'org-todo))
6103 (defun org-face-from-face-or-color (context inherit face-or-color)
6104 "Create a face list that inherits INHERIT, but sets the foreground color.
6105 When FACE-OR-COLOR is not a string, just return it."
6106 (if (stringp face-or-color)
6107 (list :inherit inherit
6108 (cdr (assoc context org-faces-easy-properties))
6109 face-or-color)
6110 face-or-color))
6112 (defun org-font-lock-add-tag-faces (limit)
6113 "Add the special tag faces."
6114 (when (and org-tag-faces org-tags-special-faces-re)
6115 (while (re-search-forward org-tags-special-faces-re limit t)
6116 (add-text-properties (match-beginning 1) (match-end 1)
6117 (list 'face (org-get-tag-face 1)
6118 'font-lock-fontified t))
6119 (backward-char 1))))
6121 (defun org-font-lock-add-priority-faces (limit)
6122 "Add the special priority faces."
6123 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6124 (when (save-match-data (org-at-heading-p))
6125 (add-text-properties
6126 (match-beginning 0) (match-end 0)
6127 (list 'face (or (org-face-from-face-or-color
6128 'priority 'org-special-keyword
6129 (cdr (assoc (char-after (match-beginning 1))
6130 org-priority-faces)))
6131 'org-special-keyword)
6132 'font-lock-fontified t)))))
6134 (defun org-get-tag-face (kwd)
6135 "Get the right face for a TODO keyword KWD.
6136 If KWD is a number, get the corresponding match group."
6137 (if (numberp kwd) (setq kwd (match-string kwd)))
6138 (or (org-face-from-face-or-color
6139 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6140 'org-tag))
6142 (defun org-unfontify-region (beg end &optional maybe_loudly)
6143 "Remove fontification and activation overlays from links."
6144 (font-lock-default-unfontify-region beg end)
6145 (let* ((buffer-undo-list t)
6146 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6147 (inhibit-modification-hooks t)
6148 deactivate-mark buffer-file-name buffer-file-truename)
6149 (org-decompose-region beg end)
6150 (remove-text-properties beg end
6151 '(mouse-face t keymap t org-linked-text t
6152 invisible t intangible t
6153 org-no-flyspell t org-emphasis t))
6154 (org-remove-font-lock-display-properties beg end)))
6156 (defconst org-script-display '(((raise -0.3) (height 0.7))
6157 ((raise 0.3) (height 0.7))
6158 ((raise -0.5))
6159 ((raise 0.5)))
6160 "Display properties for showing superscripts and subscripts.")
6162 (defun org-remove-font-lock-display-properties (beg end)
6163 "Remove specific display properties that have been added by font lock.
6164 The will remove the raise properties that are used to show superscripts
6165 and subscripts."
6166 (let (next prop)
6167 (while (< beg end)
6168 (setq next (next-single-property-change beg 'display nil end)
6169 prop (get-text-property beg 'display))
6170 (if (member prop org-script-display)
6171 (put-text-property beg next 'display nil))
6172 (setq beg next))))
6174 (defun org-raise-scripts (limit)
6175 "Add raise properties to sub/superscripts."
6176 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6177 (if (re-search-forward
6178 (if (eq org-use-sub-superscripts t)
6179 org-match-substring-regexp
6180 org-match-substring-with-braces-regexp)
6181 limit t)
6182 (let* ((pos (point)) table-p comment-p
6183 (mpos (match-beginning 3))
6184 (emph-p (get-text-property mpos 'org-emphasis))
6185 (link-p (get-text-property mpos 'mouse-face))
6186 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6187 (goto-char (point-at-bol))
6188 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6189 comment-p (org-looking-at-p "[ \t]*#"))
6190 (goto-char pos)
6191 ;; FIXME: Should we go back one character here, for a_b^c
6192 ;; (goto-char (1- pos)) ;????????????????????
6193 (if (or comment-p emph-p link-p keyw-p)
6195 (put-text-property (match-beginning 3) (match-end 0)
6196 'display
6197 (if (equal (char-after (match-beginning 2)) ?^)
6198 (nth (if table-p 3 1) org-script-display)
6199 (nth (if table-p 2 0) org-script-display)))
6200 (add-text-properties (match-beginning 2) (match-end 2)
6201 (list 'invisible t
6202 'org-dwidth t 'org-dwidth-n 1))
6203 (if (and (eq (char-after (match-beginning 3)) ?{)
6204 (eq (char-before (match-end 3)) ?}))
6205 (progn
6206 (add-text-properties
6207 (match-beginning 3) (1+ (match-beginning 3))
6208 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6209 (add-text-properties
6210 (1- (match-end 3)) (match-end 3)
6211 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6212 t)))))
6214 ;;;; Visibility cycling, including org-goto and indirect buffer
6216 ;;; Cycling
6218 (defvar org-cycle-global-status nil)
6219 (make-variable-buffer-local 'org-cycle-global-status)
6220 (defvar org-cycle-subtree-status nil)
6221 (make-variable-buffer-local 'org-cycle-subtree-status)
6223 ;;;###autoload
6225 (defvar org-inlinetask-min-level)
6227 (defun org-cycle (&optional arg)
6228 "TAB-action and visibility cycling for Org-mode.
6230 This is the command invoked in Org-mode by the TAB key. Its main purpose
6231 is outline visibility cycling, but it also invokes other actions
6232 in special contexts.
6234 - When this function is called with a prefix argument, rotate the entire
6235 buffer through 3 states (global cycling)
6236 1. OVERVIEW: Show only top-level headlines.
6237 2. CONTENTS: Show all headlines of all levels, but no body text.
6238 3. SHOW ALL: Show everything.
6239 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6240 determined by the variable `org-startup-folded', and by any VISIBILITY
6241 properties in the buffer.
6242 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6243 including any drawers.
6245 - When inside a table, re-align the table and move to the next field.
6247 - When point is at the beginning of a headline, rotate the subtree started
6248 by this line through 3 different states (local cycling)
6249 1. FOLDED: Only the main headline is shown.
6250 2. CHILDREN: The main headline and the direct children are shown.
6251 From this state, you can move to one of the children
6252 and zoom in further.
6253 3. SUBTREE: Show the entire subtree, including body text.
6254 If there is no subtree, switch directly from CHILDREN to FOLDED.
6256 - When point is at the beginning of an empty headline and the variable
6257 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6258 of the headline by demoting and promoting it to likely levels. This
6259 speeds up creation document structure by pressing TAB once or several
6260 times right after creating a new headline.
6262 - When there is a numeric prefix, go up to a heading with level ARG, do
6263 a `show-subtree' and return to the previous cursor position. If ARG
6264 is negative, go up that many levels.
6266 - When point is not at the beginning of a headline, execute the global
6267 binding for TAB, which is re-indenting the line. See the option
6268 `org-cycle-emulate-tab' for details.
6270 - Special case: if point is at the beginning of the buffer and there is
6271 no headline in line 1, this function will act as if called with prefix arg
6272 (C-u TAB, same as S-TAB) also when called without prefix arg.
6273 But only if also the variable `org-cycle-global-at-bob' is t."
6274 (interactive "P")
6275 (org-load-modules-maybe)
6276 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6277 (and org-cycle-level-after-item/entry-creation
6278 (or (org-cycle-level)
6279 (org-cycle-item-indentation))))
6280 (let* ((limit-level
6281 (or org-cycle-max-level
6282 (and (boundp 'org-inlinetask-min-level)
6283 org-inlinetask-min-level
6284 (1- org-inlinetask-min-level))))
6285 (nstars (and limit-level
6286 (if org-odd-levels-only
6287 (and limit-level (1- (* limit-level 2)))
6288 limit-level)))
6289 (org-outline-regexp
6290 (if (not (derived-mode-p 'org-mode))
6291 outline-regexp
6292 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6293 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6294 (not (looking-at org-outline-regexp))))
6295 (org-cycle-hook
6296 (if bob-special
6297 (delq 'org-optimize-window-after-visibility-change
6298 (copy-sequence org-cycle-hook))
6299 org-cycle-hook))
6300 (pos (point)))
6302 (if (or bob-special (equal arg '(4)))
6303 ;; special case: use global cycling
6304 (setq arg t))
6306 (cond
6308 ((equal arg '(16))
6309 (setq last-command 'dummy)
6310 (org-set-startup-visibility)
6311 (message "Startup visibility, plus VISIBILITY properties"))
6313 ((equal arg '(64))
6314 (show-all)
6315 (message "Entire buffer visible, including drawers"))
6317 ;; Table: enter it or move to the next field.
6318 ((org-at-table-p 'any)
6319 (if (org-at-table.el-p)
6320 (message "Use C-c ' to edit table.el tables")
6321 (if arg (org-table-edit-field t)
6322 (org-table-justify-field-maybe)
6323 (call-interactively 'org-table-next-field))))
6325 ((run-hook-with-args-until-success
6326 'org-tab-after-check-for-table-hook))
6328 ;; Global cycling: delegate to `org-cycle-internal-global'.
6329 ((eq arg t) (org-cycle-internal-global))
6331 ;; Drawers: delegate to `org-flag-drawer'.
6332 ((and org-drawers org-drawer-regexp
6333 (save-excursion
6334 (beginning-of-line 1)
6335 (looking-at org-drawer-regexp)))
6336 (org-flag-drawer ; toggle block visibility
6337 (not (get-char-property (match-end 0) 'invisible))))
6339 ;; Show-subtree, ARG levels up from here.
6340 ((integerp arg)
6341 (save-excursion
6342 (org-back-to-heading)
6343 (outline-up-heading (if (< arg 0) (- arg)
6344 (- (funcall outline-level) arg)))
6345 (org-show-subtree)))
6347 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6348 ((and (featurep 'org-inlinetask)
6349 (org-inlinetask-at-task-p)
6350 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6351 (org-inlinetask-toggle-visibility))
6353 ((org-try-cdlatex-tab))
6355 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6356 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6357 (save-excursion (beginning-of-line 1)
6358 (looking-at org-outline-regexp)))
6359 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6360 (org-cycle-internal-local))
6362 ;; From there: TAB emulation and template completion.
6363 (buffer-read-only (org-back-to-heading))
6365 ((run-hook-with-args-until-success
6366 'org-tab-after-check-for-cycling-hook))
6368 ((org-try-structure-completion))
6370 ((run-hook-with-args-until-success
6371 'org-tab-before-tab-emulation-hook))
6373 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6374 (or (not (bolp))
6375 (not (looking-at org-outline-regexp))))
6376 (call-interactively (global-key-binding "\t")))
6378 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6379 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6380 (or (and (eq org-cycle-emulate-tab 'white)
6381 (= (match-end 0) (point-at-eol)))
6382 (and (eq org-cycle-emulate-tab 'whitestart)
6383 (>= (match-end 0) pos))))
6385 (eq org-cycle-emulate-tab t))
6386 (call-interactively (global-key-binding "\t")))
6388 (t (save-excursion
6389 (org-back-to-heading)
6390 (org-cycle)))))))
6392 (defun org-cycle-internal-global ()
6393 "Do the global cycling action."
6394 ;; Hack to avoid display of messages for .org attachments in Gnus
6395 (let ((ga (string-match "\\*fontification" (buffer-name))))
6396 (cond
6397 ((and (eq last-command this-command)
6398 (eq org-cycle-global-status 'overview))
6399 ;; We just created the overview - now do table of contents
6400 ;; This can be slow in very large buffers, so indicate action
6401 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6402 (unless ga (message "CONTENTS..."))
6403 (org-content)
6404 (unless ga (message "CONTENTS...done"))
6405 (setq org-cycle-global-status 'contents)
6406 (run-hook-with-args 'org-cycle-hook 'contents))
6408 ((and (eq last-command this-command)
6409 (eq org-cycle-global-status 'contents))
6410 ;; We just showed the table of contents - now show everything
6411 (run-hook-with-args 'org-pre-cycle-hook 'all)
6412 (show-all)
6413 (unless ga (message "SHOW ALL"))
6414 (setq org-cycle-global-status 'all)
6415 (run-hook-with-args 'org-cycle-hook 'all))
6418 ;; Default action: go to overview
6419 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6420 (org-overview)
6421 (unless ga (message "OVERVIEW"))
6422 (setq org-cycle-global-status 'overview)
6423 (run-hook-with-args 'org-cycle-hook 'overview)))))
6425 (defun org-cycle-internal-local ()
6426 "Do the local cycling action."
6427 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6428 ;; First, determine end of headline (EOH), end of subtree or item
6429 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6430 (save-excursion
6431 (if (org-at-item-p)
6432 (progn
6433 (beginning-of-line)
6434 (setq struct (org-list-struct))
6435 (setq eoh (point-at-eol))
6436 (setq eos (org-list-get-item-end-before-blank (point) struct))
6437 (setq has-children (org-list-has-child-p (point) struct)))
6438 (org-back-to-heading)
6439 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6440 (setq eos (save-excursion
6441 (org-end-of-subtree t)
6442 (unless (eobp)
6443 (skip-chars-forward " \t\n"))
6444 (if (eobp) (point) (1- (point)))))
6445 (setq has-children
6446 (or (save-excursion
6447 (let ((level (funcall outline-level)))
6448 (outline-next-heading)
6449 (and (org-at-heading-p t)
6450 (> (funcall outline-level) level))))
6451 (save-excursion
6452 (org-list-search-forward (org-item-beginning-re) eos t)))))
6453 ;; Determine end invisible part of buffer (EOL)
6454 (beginning-of-line 2)
6455 ;; XEmacs doesn't have `next-single-char-property-change'
6456 (if (featurep 'xemacs)
6457 (while (and (not (eobp)) ;; this is like `next-line'
6458 (get-char-property (1- (point)) 'invisible))
6459 (beginning-of-line 2))
6460 (while (and (not (eobp)) ;; this is like `next-line'
6461 (get-char-property (1- (point)) 'invisible))
6462 (goto-char (next-single-char-property-change (point) 'invisible))
6463 (and (eolp) (beginning-of-line 2))))
6464 (setq eol (point)))
6465 ;; Find out what to do next and set `this-command'
6466 (cond
6467 ((= eos eoh)
6468 ;; Nothing is hidden behind this heading
6469 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6470 (message "EMPTY ENTRY")
6471 (setq org-cycle-subtree-status nil)
6472 (save-excursion
6473 (goto-char eos)
6474 (outline-next-heading)
6475 (if (outline-invisible-p) (org-flag-heading nil))))
6476 ((and (or (>= eol eos)
6477 (not (string-match "\\S-" (buffer-substring eol eos))))
6478 (or has-children
6479 (not (setq children-skipped
6480 org-cycle-skip-children-state-if-no-children))))
6481 ;; Entire subtree is hidden in one line: children view
6482 (run-hook-with-args 'org-pre-cycle-hook 'children)
6483 (if (org-at-item-p)
6484 (org-list-set-item-visibility (point-at-bol) struct 'children)
6485 (org-show-entry)
6486 (org-with-limited-levels (show-children))
6487 ;; FIXME: This slows down the func way too much.
6488 ;; How keep drawers hidden in subtree anyway?
6489 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6490 ;; (org-cycle-hide-drawers 'subtree))
6492 ;; Fold every list in subtree to top-level items.
6493 (when (eq org-cycle-include-plain-lists 'integrate)
6494 (save-excursion
6495 (org-back-to-heading)
6496 (while (org-list-search-forward (org-item-beginning-re) eos t)
6497 (beginning-of-line 1)
6498 (let* ((struct (org-list-struct))
6499 (prevs (org-list-prevs-alist struct))
6500 (end (org-list-get-bottom-point struct)))
6501 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6502 (org-list-get-all-items (point) struct prevs))
6503 (goto-char end))))))
6504 (message "CHILDREN")
6505 (save-excursion
6506 (goto-char eos)
6507 (outline-next-heading)
6508 (if (outline-invisible-p) (org-flag-heading nil)))
6509 (setq org-cycle-subtree-status 'children)
6510 (run-hook-with-args 'org-cycle-hook 'children))
6511 ((or children-skipped
6512 (and (eq last-command this-command)
6513 (eq org-cycle-subtree-status 'children)))
6514 ;; We just showed the children, or no children are there,
6515 ;; now show everything.
6516 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6517 (outline-flag-region eoh eos nil)
6518 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6519 (setq org-cycle-subtree-status 'subtree)
6520 (run-hook-with-args 'org-cycle-hook 'subtree))
6522 ;; Default action: hide the subtree.
6523 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6524 (outline-flag-region eoh eos t)
6525 (message "FOLDED")
6526 (setq org-cycle-subtree-status 'folded)
6527 (run-hook-with-args 'org-cycle-hook 'folded)))))
6529 ;;;###autoload
6530 (defun org-global-cycle (&optional arg)
6531 "Cycle the global visibility. For details see `org-cycle'.
6532 With \\[universal-argument] prefix arg, switch to startup visibility.
6533 With a numeric prefix, show all headlines up to that level."
6534 (interactive "P")
6535 (let ((org-cycle-include-plain-lists
6536 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6537 (cond
6538 ((integerp arg)
6539 (show-all)
6540 (hide-sublevels arg)
6541 (setq org-cycle-global-status 'contents))
6542 ((equal arg '(4))
6543 (org-set-startup-visibility)
6544 (message "Startup visibility, plus VISIBILITY properties."))
6546 (org-cycle '(4))))))
6548 (defun org-set-startup-visibility ()
6549 "Set the visibility required by startup options and properties."
6550 (cond
6551 ((eq org-startup-folded t)
6552 (org-cycle '(4)))
6553 ((eq org-startup-folded 'content)
6554 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6555 (org-cycle '(4)) (org-cycle '(4)))))
6556 (unless (eq org-startup-folded 'showeverything)
6557 (if org-hide-block-startup (org-hide-block-all))
6558 (org-set-visibility-according-to-property 'no-cleanup)
6559 (org-cycle-hide-archived-subtrees 'all)
6560 (org-cycle-hide-drawers 'all)
6561 (org-cycle-show-empty-lines t)))
6563 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6564 "Switch subtree visibilities according to :VISIBILITY: property."
6565 (interactive)
6566 (let (org-show-entry-below state)
6567 (save-excursion
6568 (goto-char (point-min))
6569 (while (re-search-forward
6570 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6571 nil t)
6572 (setq state (match-string 1))
6573 (save-excursion
6574 (org-back-to-heading t)
6575 (hide-subtree)
6576 (org-reveal)
6577 (cond
6578 ((equal state '("fold" "folded"))
6579 (hide-subtree))
6580 ((equal state "children")
6581 (org-show-hidden-entry)
6582 (show-children))
6583 ((equal state "content")
6584 (save-excursion
6585 (save-restriction
6586 (org-narrow-to-subtree)
6587 (org-content))))
6588 ((member state '("all" "showall"))
6589 (show-subtree)))))
6590 (unless no-cleanup
6591 (org-cycle-hide-archived-subtrees 'all)
6592 (org-cycle-hide-drawers 'all)
6593 (org-cycle-show-empty-lines 'all)))))
6595 ;; This function uses outline-regexp instead of the more fundamental
6596 ;; org-outline-regexp so that org-cycle-global works outside of Org
6597 ;; buffers, where outline-regexp is needed.
6598 (defun org-overview ()
6599 "Switch to overview mode, showing only top-level headlines.
6600 Really, this shows all headlines with level equal or greater than the level
6601 of the first headline in the buffer. This is important, because if the
6602 first headline is not level one, then (hide-sublevels 1) gives confusing
6603 results."
6604 (interactive)
6605 (let ((level (save-excursion
6606 (goto-char (point-min))
6607 (if (re-search-forward (concat "^" outline-regexp) nil t)
6608 (progn
6609 (goto-char (match-beginning 0))
6610 (funcall outline-level))))))
6611 (and level (hide-sublevels level))))
6613 (defun org-content (&optional arg)
6614 "Show all headlines in the buffer, like a table of contents.
6615 With numerical argument N, show content up to level N."
6616 (interactive "P")
6617 (save-excursion
6618 ;; Visit all headings and show their offspring
6619 (and (integerp arg) (org-overview))
6620 (goto-char (point-max))
6621 (catch 'exit
6622 (while (and (progn (condition-case nil
6623 (outline-previous-visible-heading 1)
6624 (error (goto-char (point-min))))
6626 (looking-at org-outline-regexp))
6627 (if (integerp arg)
6628 (show-children (1- arg))
6629 (show-branches))
6630 (if (bobp) (throw 'exit nil))))))
6633 (defun org-optimize-window-after-visibility-change (state)
6634 "Adjust the window after a change in outline visibility.
6635 This function is the default value of the hook `org-cycle-hook'."
6636 (when (get-buffer-window (current-buffer))
6637 (cond
6638 ((eq state 'content) nil)
6639 ((eq state 'all) nil)
6640 ((eq state 'folded) nil)
6641 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6642 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6644 (defun org-remove-empty-overlays-at (pos)
6645 "Remove outline overlays that do not contain non-white stuff."
6646 (mapc
6647 (lambda (o)
6648 (and (eq 'outline (overlay-get o 'invisible))
6649 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6650 (overlay-end o))))
6651 (delete-overlay o)))
6652 (overlays-at pos)))
6654 (defun org-clean-visibility-after-subtree-move ()
6655 "Fix visibility issues after moving a subtree."
6656 ;; First, find a reasonable region to look at:
6657 ;; Start two siblings above, end three below
6658 (let* ((beg (save-excursion
6659 (and (org-get-last-sibling)
6660 (org-get-last-sibling))
6661 (point)))
6662 (end (save-excursion
6663 (and (org-get-next-sibling)
6664 (org-get-next-sibling)
6665 (org-get-next-sibling))
6666 (if (org-at-heading-p)
6667 (point-at-eol)
6668 (point))))
6669 (level (looking-at "\\*+"))
6670 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6671 (save-excursion
6672 (save-restriction
6673 (narrow-to-region beg end)
6674 (when re
6675 ;; Properly fold already folded siblings
6676 (goto-char (point-min))
6677 (while (re-search-forward re nil t)
6678 (if (and (not (outline-invisible-p))
6679 (save-excursion
6680 (goto-char (point-at-eol)) (outline-invisible-p)))
6681 (hide-entry))))
6682 (org-cycle-show-empty-lines 'overview)
6683 (org-cycle-hide-drawers 'overview)))))
6685 (defun org-cycle-show-empty-lines (state)
6686 "Show empty lines above all visible headlines.
6687 The region to be covered depends on STATE when called through
6688 `org-cycle-hook'. Lisp program can use t for STATE to get the
6689 entire buffer covered. Note that an empty line is only shown if there
6690 are at least `org-cycle-separator-lines' empty lines before the headline."
6691 (when (not (= org-cycle-separator-lines 0))
6692 (save-excursion
6693 (let* ((n (abs org-cycle-separator-lines))
6694 (re (cond
6695 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6696 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6697 (t (let ((ns (number-to-string (- n 2))))
6698 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6699 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6700 beg end b e)
6701 (cond
6702 ((memq state '(overview contents t))
6703 (setq beg (point-min) end (point-max)))
6704 ((memq state '(children folded))
6705 (setq beg (point) end (progn (org-end-of-subtree t t)
6706 (beginning-of-line 2)
6707 (point)))))
6708 (when beg
6709 (goto-char beg)
6710 (while (re-search-forward re end t)
6711 (unless (get-char-property (match-end 1) 'invisible)
6712 (setq e (match-end 1))
6713 (if (< org-cycle-separator-lines 0)
6714 (setq b (save-excursion
6715 (goto-char (match-beginning 0))
6716 (org-back-over-empty-lines)
6717 (if (save-excursion
6718 (goto-char (max (point-min) (1- (point))))
6719 (org-at-heading-p))
6720 (1- (point))
6721 (point))))
6722 (setq b (match-beginning 1)))
6723 (outline-flag-region b e nil)))))))
6724 ;; Never hide empty lines at the end of the file.
6725 (save-excursion
6726 (goto-char (point-max))
6727 (outline-previous-heading)
6728 (outline-end-of-heading)
6729 (if (and (looking-at "[ \t\n]+")
6730 (= (match-end 0) (point-max)))
6731 (outline-flag-region (point) (match-end 0) nil))))
6733 (defun org-show-empty-lines-in-parent ()
6734 "Move to the parent and re-show empty lines before visible headlines."
6735 (save-excursion
6736 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6737 (org-cycle-show-empty-lines context))))
6739 (defun org-files-list ()
6740 "Return `org-agenda-files' list, plus all open org-mode files.
6741 This is useful for operations that need to scan all of a user's
6742 open and agenda-wise Org files."
6743 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6744 (dolist (buf (buffer-list))
6745 (with-current-buffer buf
6746 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6747 (let ((file (expand-file-name (buffer-file-name))))
6748 (unless (member file files)
6749 (push file files))))))
6750 files))
6752 (defsubst org-entry-beginning-position ()
6753 "Return the beginning position of the current entry."
6754 (save-excursion (outline-back-to-heading t) (point)))
6756 (defsubst org-entry-end-position ()
6757 "Return the end position of the current entry."
6758 (save-excursion (outline-next-heading) (point)))
6760 (defun org-cycle-hide-drawers (state)
6761 "Re-hide all drawers after a visibility state change."
6762 (when (and (derived-mode-p 'org-mode)
6763 (not (memq state '(overview folded contents))))
6764 (save-excursion
6765 (let* ((globalp (memq state '(contents all)))
6766 (beg (if globalp (point-min) (point)))
6767 (end (if globalp (point-max)
6768 (if (eq state 'children)
6769 (save-excursion (outline-next-heading) (point))
6770 (org-end-of-subtree t)))))
6771 (goto-char beg)
6772 (while (re-search-forward org-drawer-regexp end t)
6773 (org-flag-drawer t))))))
6775 (defun org-flag-drawer (flag)
6776 "When FLAG is non-nil, hide the drawer we are within.
6777 Otherwise make it visible."
6778 (save-excursion
6779 (beginning-of-line 1)
6780 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6781 (let ((b (match-end 0)))
6782 (if (re-search-forward
6783 "^[ \t]*:END:"
6784 (save-excursion (outline-next-heading) (point)) t)
6785 (outline-flag-region b (point-at-eol) flag)
6786 (error ":END: line missing at position %s" b))))))
6788 (defun org-subtree-end-visible-p ()
6789 "Is the end of the current subtree visible?"
6790 (pos-visible-in-window-p
6791 (save-excursion (org-end-of-subtree t) (point))))
6793 (defun org-first-headline-recenter (&optional N)
6794 "Move cursor to the first headline and recenter the headline.
6795 Optional argument N means put the headline into the Nth line of the window."
6796 (goto-char (point-min))
6797 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6798 (beginning-of-line)
6799 (recenter (prefix-numeric-value N))))
6801 ;;; Saving and restoring visibility
6803 (defun org-outline-overlay-data (&optional use-markers)
6804 "Return a list of the locations of all outline overlays.
6805 These are overlays with the `invisible' property value `outline'.
6806 The return value is a list of cons cells, with start and stop
6807 positions for each overlay.
6808 If USE-MARKERS is set, return the positions as markers."
6809 (let (beg end)
6810 (save-excursion
6811 (save-restriction
6812 (widen)
6813 (delq nil
6814 (mapcar (lambda (o)
6815 (when (eq (overlay-get o 'invisible) 'outline)
6816 (setq beg (overlay-start o)
6817 end (overlay-end o))
6818 (and beg end (> end beg)
6819 (if use-markers
6820 (cons (move-marker (make-marker) beg)
6821 (move-marker (make-marker) end))
6822 (cons beg end)))))
6823 (overlays-in (point-min) (point-max))))))))
6825 (defun org-set-outline-overlay-data (data)
6826 "Create visibility overlays for all positions in DATA.
6827 DATA should have been made by `org-outline-overlay-data'."
6828 (let (o)
6829 (save-excursion
6830 (save-restriction
6831 (widen)
6832 (show-all)
6833 (mapc (lambda (c)
6834 (outline-flag-region (car c) (cdr c) t))
6835 data)))))
6837 ;;; Folding of blocks
6839 (defvar org-hide-block-overlays nil
6840 "Overlays hiding blocks.")
6841 (make-variable-buffer-local 'org-hide-block-overlays)
6843 (defun org-block-map (function &optional start end)
6844 "Call FUNCTION at the head of all source blocks in the current buffer.
6845 Optional arguments START and END can be used to limit the range."
6846 (let ((start (or start (point-min)))
6847 (end (or end (point-max))))
6848 (save-excursion
6849 (goto-char start)
6850 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6851 (save-excursion
6852 (save-match-data
6853 (goto-char (match-beginning 0))
6854 (funcall function)))))))
6856 (defun org-hide-block-toggle-all ()
6857 "Toggle the visibility of all blocks in the current buffer."
6858 (org-block-map #'org-hide-block-toggle))
6860 (defun org-hide-block-all ()
6861 "Fold all blocks in the current buffer."
6862 (interactive)
6863 (org-show-block-all)
6864 (org-block-map #'org-hide-block-toggle-maybe))
6866 (defun org-show-block-all ()
6867 "Unfold all blocks in the current buffer."
6868 (interactive)
6869 (mapc 'delete-overlay org-hide-block-overlays)
6870 (setq org-hide-block-overlays nil))
6872 (defun org-hide-block-toggle-maybe ()
6873 "Toggle visibility of block at point."
6874 (interactive)
6875 (let ((case-fold-search t))
6876 (if (save-excursion
6877 (beginning-of-line 1)
6878 (looking-at org-block-regexp))
6879 (progn (org-hide-block-toggle)
6880 t) ;; to signal that we took action
6881 nil))) ;; to signal that we did not
6883 (defun org-hide-block-toggle (&optional force)
6884 "Toggle the visibility of the current block."
6885 (interactive)
6886 (save-excursion
6887 (beginning-of-line)
6888 (if (re-search-forward org-block-regexp nil t)
6889 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6890 (end (match-end 0)) ;; end of entire body
6892 (if (memq t (mapcar (lambda (overlay)
6893 (eq (overlay-get overlay 'invisible)
6894 'org-hide-block))
6895 (overlays-at start)))
6896 (if (or (not force) (eq force 'off))
6897 (mapc (lambda (ov)
6898 (when (member ov org-hide-block-overlays)
6899 (setq org-hide-block-overlays
6900 (delq ov org-hide-block-overlays)))
6901 (when (eq (overlay-get ov 'invisible)
6902 'org-hide-block)
6903 (delete-overlay ov)))
6904 (overlays-at start)))
6905 (setq ov (make-overlay start end))
6906 (overlay-put ov 'invisible 'org-hide-block)
6907 ;; make the block accessible to isearch
6908 (overlay-put
6909 ov 'isearch-open-invisible
6910 (lambda (ov)
6911 (when (member ov org-hide-block-overlays)
6912 (setq org-hide-block-overlays
6913 (delq ov org-hide-block-overlays)))
6914 (when (eq (overlay-get ov 'invisible)
6915 'org-hide-block)
6916 (delete-overlay ov))))
6917 (push ov org-hide-block-overlays)))
6918 (error "Not looking at a source block"))))
6920 ;; org-tab-after-check-for-cycling-hook
6921 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6922 ;; Remove overlays when changing major mode
6923 (add-hook 'org-mode-hook
6924 (lambda () (org-add-hook 'change-major-mode-hook
6925 'org-show-block-all 'append 'local)))
6927 ;;; Org-goto
6929 (defvar org-goto-window-configuration nil)
6930 (defvar org-goto-marker nil)
6931 (defvar org-goto-map
6932 (let ((map (make-sparse-keymap)))
6933 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6934 (while (setq cmd (pop cmds))
6935 (substitute-key-definition cmd cmd map global-map)))
6936 (suppress-keymap map)
6937 (org-defkey map "\C-m" 'org-goto-ret)
6938 (org-defkey map [(return)] 'org-goto-ret)
6939 (org-defkey map [(left)] 'org-goto-left)
6940 (org-defkey map [(right)] 'org-goto-right)
6941 (org-defkey map [(control ?g)] 'org-goto-quit)
6942 (org-defkey map "\C-i" 'org-cycle)
6943 (org-defkey map [(tab)] 'org-cycle)
6944 (org-defkey map [(down)] 'outline-next-visible-heading)
6945 (org-defkey map [(up)] 'outline-previous-visible-heading)
6946 (if org-goto-auto-isearch
6947 (if (fboundp 'define-key-after)
6948 (define-key-after map [t] 'org-goto-local-auto-isearch)
6949 nil)
6950 (org-defkey map "q" 'org-goto-quit)
6951 (org-defkey map "n" 'outline-next-visible-heading)
6952 (org-defkey map "p" 'outline-previous-visible-heading)
6953 (org-defkey map "f" 'outline-forward-same-level)
6954 (org-defkey map "b" 'outline-backward-same-level)
6955 (org-defkey map "u" 'outline-up-heading))
6956 (org-defkey map "/" 'org-occur)
6957 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6958 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6959 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6960 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6961 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6962 map))
6964 (defconst org-goto-help
6965 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6966 RET=jump to location [Q]uit and return to previous location
6967 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6969 (defvar org-goto-start-pos) ; dynamically scoped parameter
6971 ;; FIXME: Docstring does not mention both interfaces
6972 (defun org-goto (&optional alternative-interface)
6973 "Look up a different location in the current file, keeping current visibility.
6975 When you want look-up or go to a different location in a
6976 document, the fastest way is often to fold the entire buffer and
6977 then dive into the tree. This method has the disadvantage, that
6978 the previous location will be folded, which may not be what you
6979 want.
6981 This command works around this by showing a copy of the current
6982 buffer in an indirect buffer, in overview mode. You can dive
6983 into the tree in that copy, use org-occur and incremental search
6984 to find a location. When pressing RET or `Q', the command
6985 returns to the original buffer in which the visibility is still
6986 unchanged. After RET it will also jump to the location selected
6987 in the indirect buffer and expose the headline hierarchy above.
6989 With a prefix argument, use the alternative interface: e.g. if
6990 `org-goto-interface' is 'outline use 'outline-path-completion."
6991 (interactive "P")
6992 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6993 (org-refile-use-outline-path t)
6994 (org-refile-target-verify-function nil)
6995 (interface
6996 (if (not alternative-interface)
6997 org-goto-interface
6998 (if (eq org-goto-interface 'outline)
6999 'outline-path-completion
7000 'outline)))
7001 (org-goto-start-pos (point))
7002 (selected-point
7003 (if (eq interface 'outline)
7004 (car (org-get-location (current-buffer) org-goto-help))
7005 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7006 (org-refile-check-position pa)
7007 (nth 3 pa)))))
7008 (if selected-point
7009 (progn
7010 (org-mark-ring-push org-goto-start-pos)
7011 (goto-char selected-point)
7012 (if (or (outline-invisible-p) (org-invisible-p2))
7013 (org-show-context 'org-goto)))
7014 (message "Quit"))))
7016 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7017 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7018 (defvar org-goto-local-auto-isearch-map) ; defined below
7020 (defun org-get-location (buf help)
7021 "Let the user select a location in the Org-mode buffer BUF.
7022 This function uses a recursive edit. It returns the selected position
7023 or nil."
7024 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7025 (isearch-hide-immediately nil)
7026 (isearch-search-fun-function
7027 (lambda () 'org-goto-local-search-headings))
7028 (org-goto-selected-point org-goto-exit-command)
7029 (pop-up-frames nil)
7030 (special-display-buffer-names nil)
7031 (special-display-regexps nil)
7032 (special-display-function nil))
7033 (save-excursion
7034 (save-window-excursion
7035 (delete-other-windows)
7036 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7037 (org-pop-to-buffer-same-window
7038 (condition-case nil
7039 (make-indirect-buffer (current-buffer) "*org-goto*")
7040 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7041 (with-output-to-temp-buffer "*Help*"
7042 (princ help))
7043 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7044 (setq buffer-read-only nil)
7045 (let ((org-startup-truncated t)
7046 (org-startup-folded nil)
7047 (org-startup-align-all-tables nil))
7048 (org-mode)
7049 (org-overview))
7050 (setq buffer-read-only t)
7051 (if (and (boundp 'org-goto-start-pos)
7052 (integer-or-marker-p org-goto-start-pos))
7053 (let ((org-show-hierarchy-above t)
7054 (org-show-siblings t)
7055 (org-show-following-heading t))
7056 (goto-char org-goto-start-pos)
7057 (and (outline-invisible-p) (org-show-context)))
7058 (goto-char (point-min)))
7059 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7060 (message "Select location and press RET")
7061 (use-local-map org-goto-map)
7062 (recursive-edit)
7064 (kill-buffer "*org-goto*")
7065 (cons org-goto-selected-point org-goto-exit-command)))
7067 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7068 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7069 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7070 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7072 (defun org-goto-local-search-headings (string bound noerror)
7073 "Search and make sure that any matches are in headlines."
7074 (catch 'return
7075 (while (if isearch-forward
7076 (search-forward string bound noerror)
7077 (search-backward string bound noerror))
7078 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7079 (and (member :headline context)
7080 (not (member :tags context))))
7081 (throw 'return (point))))))
7083 (defun org-goto-local-auto-isearch ()
7084 "Start isearch."
7085 (interactive)
7086 (goto-char (point-min))
7087 (let ((keys (this-command-keys)))
7088 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7089 (isearch-mode t)
7090 (isearch-process-search-char (string-to-char keys)))))
7092 (defun org-goto-ret (&optional arg)
7093 "Finish `org-goto' by going to the new location."
7094 (interactive "P")
7095 (setq org-goto-selected-point (point)
7096 org-goto-exit-command 'return)
7097 (throw 'exit nil))
7099 (defun org-goto-left ()
7100 "Finish `org-goto' by going to the new location."
7101 (interactive)
7102 (if (org-at-heading-p)
7103 (progn
7104 (beginning-of-line 1)
7105 (setq org-goto-selected-point (point)
7106 org-goto-exit-command 'left)
7107 (throw 'exit nil))
7108 (error "Not on a heading")))
7110 (defun org-goto-right ()
7111 "Finish `org-goto' by going to the new location."
7112 (interactive)
7113 (if (org-at-heading-p)
7114 (progn
7115 (setq org-goto-selected-point (point)
7116 org-goto-exit-command 'right)
7117 (throw 'exit nil))
7118 (error "Not on a heading")))
7120 (defun org-goto-quit ()
7121 "Finish `org-goto' without cursor motion."
7122 (interactive)
7123 (setq org-goto-selected-point nil)
7124 (setq org-goto-exit-command 'quit)
7125 (throw 'exit nil))
7127 ;;; Indirect buffer display of subtrees
7129 (defvar org-indirect-dedicated-frame nil
7130 "This is the frame being used for indirect tree display.")
7131 (defvar org-last-indirect-buffer nil)
7133 (defun org-tree-to-indirect-buffer (&optional arg)
7134 "Create indirect buffer and narrow it to current subtree.
7135 With numerical prefix ARG, go up to this level and then take that tree.
7136 If ARG is negative, go up that many levels.
7137 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7138 indirect buffer previously made with this command, to avoid proliferation of
7139 indirect buffers. However, when you call the command with a \
7140 \\[universal-argument] prefix, or
7141 when `org-indirect-buffer-display' is `new-frame', the last buffer
7142 is kept so that you can work with several indirect buffers at the same time.
7143 If `org-indirect-buffer-display' is `dedicated-frame', the \
7144 \\[universal-argument] prefix also
7145 requests that a new frame be made for the new buffer, so that the dedicated
7146 frame is not changed."
7147 (interactive "P")
7148 (let ((cbuf (current-buffer))
7149 (cwin (selected-window))
7150 (pos (point))
7151 beg end level heading ibuf)
7152 (save-excursion
7153 (org-back-to-heading t)
7154 (when (numberp arg)
7155 (setq level (org-outline-level))
7156 (if (< arg 0) (setq arg (+ level arg)))
7157 (while (> (setq level (org-outline-level)) arg)
7158 (outline-up-heading 1 t)))
7159 (setq beg (point)
7160 heading (org-get-heading))
7161 (org-end-of-subtree t t)
7162 (if (org-at-heading-p) (backward-char 1))
7163 (setq end (point)))
7164 (if (and (buffer-live-p org-last-indirect-buffer)
7165 (not (eq org-indirect-buffer-display 'new-frame))
7166 (not arg))
7167 (kill-buffer org-last-indirect-buffer))
7168 (setq ibuf (org-get-indirect-buffer cbuf)
7169 org-last-indirect-buffer ibuf)
7170 (cond
7171 ((or (eq org-indirect-buffer-display 'new-frame)
7172 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7173 (select-frame (make-frame))
7174 (delete-other-windows)
7175 (org-pop-to-buffer-same-window ibuf)
7176 (org-set-frame-title heading))
7177 ((eq org-indirect-buffer-display 'dedicated-frame)
7178 (raise-frame
7179 (select-frame (or (and org-indirect-dedicated-frame
7180 (frame-live-p org-indirect-dedicated-frame)
7181 org-indirect-dedicated-frame)
7182 (setq org-indirect-dedicated-frame (make-frame)))))
7183 (delete-other-windows)
7184 (org-pop-to-buffer-same-window ibuf)
7185 (org-set-frame-title (concat "Indirect: " heading)))
7186 ((eq org-indirect-buffer-display 'current-window)
7187 (org-pop-to-buffer-same-window ibuf))
7188 ((eq org-indirect-buffer-display 'other-window)
7189 (pop-to-buffer ibuf))
7190 (t (error "Invalid value")))
7191 (if (featurep 'xemacs)
7192 (save-excursion (org-mode) (turn-on-font-lock)))
7193 (narrow-to-region beg end)
7194 (show-all)
7195 (goto-char pos)
7196 (run-hook-with-args 'org-cycle-hook 'all)
7197 (and (window-live-p cwin) (select-window cwin))))
7199 (defun org-get-indirect-buffer (&optional buffer)
7200 (setq buffer (or buffer (current-buffer)))
7201 (let ((n 1) (base (buffer-name buffer)) bname)
7202 (while (buffer-live-p
7203 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7204 (setq n (1+ n)))
7205 (condition-case nil
7206 (make-indirect-buffer buffer bname 'clone)
7207 (error (make-indirect-buffer buffer bname)))))
7209 (defun org-set-frame-title (title)
7210 "Set the title of the current frame to the string TITLE."
7211 ;; FIXME: how to name a single frame in XEmacs???
7212 (unless (featurep 'xemacs)
7213 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7215 ;;;; Structure editing
7217 ;;; Inserting headlines
7219 (defun org-previous-line-empty-p ()
7220 (save-excursion
7221 (and (not (bobp))
7222 (or (beginning-of-line 0) t)
7223 (save-match-data
7224 (looking-at "[ \t]*$")))))
7226 (defun org-insert-heading (&optional force-heading invisible-ok)
7227 "Insert a new heading or item with same depth at point.
7228 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7229 If point is at the beginning of a headline, insert a sibling before the
7230 current headline. If point is not at the beginning, split the line,
7231 create the new headline with the text in the current line after point
7232 \(but see also the variable `org-M-RET-may-split-line').
7234 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7235 This is important for non-interactive uses of the command."
7236 (interactive "P")
7237 (if (or (= (buffer-size) 0)
7238 (and (not (save-excursion
7239 (and (ignore-errors (org-back-to-heading invisible-ok))
7240 (org-at-heading-p))))
7241 (or force-heading (not (org-in-item-p)))))
7242 (progn
7243 (insert "\n* ")
7244 (run-hooks 'org-insert-heading-hook))
7245 (when (or force-heading (not (org-insert-item)))
7246 (let* ((empty-line-p nil)
7247 (level nil)
7248 (on-heading (org-at-heading-p))
7249 (head (save-excursion
7250 (condition-case nil
7251 (progn
7252 (org-back-to-heading invisible-ok)
7253 (when (and (not on-heading)
7254 (featurep 'org-inlinetask)
7255 (integerp org-inlinetask-min-level)
7256 (>= (length (match-string 0))
7257 org-inlinetask-min-level))
7258 ;; Find a heading level before the inline task
7259 (while (and (setq level (org-up-heading-safe))
7260 (>= level org-inlinetask-min-level)))
7261 (if (org-at-heading-p)
7262 (org-back-to-heading invisible-ok)
7263 (error "This should not happen")))
7264 (setq empty-line-p (org-previous-line-empty-p))
7265 (match-string 0))
7266 (error "*"))))
7267 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7268 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7269 pos hide-previous previous-pos)
7270 (cond
7271 ((and (org-at-heading-p) (bolp)
7272 (or (bobp)
7273 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7274 ;; insert before the current line
7275 (open-line (if blank 2 1)))
7276 ((and (bolp)
7277 (not org-insert-heading-respect-content)
7278 (or (bobp)
7279 (save-excursion
7280 (backward-char 1) (not (outline-invisible-p)))))
7281 ;; insert right here
7282 nil)
7284 ;; somewhere in the line
7285 (save-excursion
7286 (setq previous-pos (point-at-bol))
7287 (end-of-line)
7288 (setq hide-previous (outline-invisible-p)))
7289 (and org-insert-heading-respect-content (org-show-subtree))
7290 (let ((split
7291 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7292 (save-excursion
7293 (let ((p (point)))
7294 (goto-char (point-at-bol))
7295 (and (looking-at org-complex-heading-regexp)
7296 (match-beginning 4)
7297 (> p (match-beginning 4)))))))
7298 tags pos)
7299 (cond
7300 (org-insert-heading-respect-content
7301 (org-end-of-subtree nil t)
7302 (when (featurep 'org-inlinetask)
7303 (while (and (not (eobp))
7304 (looking-at "\\(\\*+\\)[ \t]+")
7305 (>= (length (match-string 1))
7306 org-inlinetask-min-level))
7307 (org-end-of-subtree nil t)))
7308 (or (bolp) (newline))
7309 (or (org-previous-line-empty-p)
7310 (and blank (newline)))
7311 (open-line 1))
7312 ((org-at-heading-p)
7313 (when hide-previous
7314 (show-children)
7315 (org-show-entry))
7316 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7317 (setq tags (and (match-end 2) (match-string 2)))
7318 (and (match-end 1)
7319 (delete-region (match-beginning 1) (match-end 1)))
7320 (setq pos (point-at-bol))
7321 (or split (end-of-line 1))
7322 (delete-horizontal-space)
7323 (if (string-match "\\`\\*+\\'"
7324 (buffer-substring (point-at-bol) (point)))
7325 (insert " "))
7326 (newline (if blank 2 1))
7327 (when tags
7328 (save-excursion
7329 (goto-char pos)
7330 (end-of-line 1)
7331 (insert " " tags)
7332 (org-set-tags nil 'align))))
7334 (or split (end-of-line 1))
7335 (newline (if blank 2 1)))))))
7336 (insert head) (just-one-space)
7337 (setq pos (point))
7338 (end-of-line 1)
7339 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7340 (when (and org-insert-heading-respect-content hide-previous)
7341 (save-excursion
7342 (goto-char previous-pos)
7343 (hide-subtree)))
7344 (run-hooks 'org-insert-heading-hook)))))
7346 (defun org-get-heading (&optional no-tags no-todo)
7347 "Return the heading of the current entry, without the stars.
7348 When NO-TAGS is non-nil, don't include tags.
7349 When NO-TODO is non-nil, don't include TODO keywords."
7350 (save-excursion
7351 (org-back-to-heading t)
7352 (cond
7353 ((and no-tags no-todo)
7354 (looking-at org-complex-heading-regexp)
7355 (match-string 4))
7356 (no-tags
7357 (looking-at (concat org-outline-regexp
7358 "\\(.*?\\)"
7359 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7360 (match-string 1))
7361 (no-todo
7362 (looking-at org-todo-line-regexp)
7363 (match-string 3))
7364 (t (looking-at org-heading-regexp)
7365 (match-string 2)))))
7367 (defun org-heading-components ()
7368 "Return the components of the current heading.
7369 This is a list with the following elements:
7370 - the level as an integer
7371 - the reduced level, different if `org-odd-levels-only' is set.
7372 - the TODO keyword, or nil
7373 - the priority character, like ?A, or nil if no priority is given
7374 - the headline text itself, or the tags string if no headline text
7375 - the tags string, or nil."
7376 (save-excursion
7377 (org-back-to-heading t)
7378 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7379 (list (length (match-string 1))
7380 (org-reduced-level (length (match-string 1)))
7381 (org-match-string-no-properties 2)
7382 (and (match-end 3) (aref (match-string 3) 2))
7383 (org-match-string-no-properties 4)
7384 (org-match-string-no-properties 5)))))
7386 (defun org-get-entry ()
7387 "Get the entry text, after heading, entire subtree."
7388 (save-excursion
7389 (org-back-to-heading t)
7390 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7392 (defun org-insert-heading-after-current ()
7393 "Insert a new heading with same level as current, after current subtree."
7394 (interactive)
7395 (org-back-to-heading)
7396 (org-insert-heading)
7397 (org-move-subtree-down)
7398 (end-of-line 1))
7400 (defun org-insert-heading-respect-content ()
7401 (interactive)
7402 (let ((org-insert-heading-respect-content t))
7403 (org-insert-heading t)))
7405 (defun org-insert-todo-heading-respect-content (&optional force-state)
7406 (interactive "P")
7407 (let ((org-insert-heading-respect-content t))
7408 (org-insert-todo-heading force-state t)))
7410 (defun org-insert-todo-heading (arg &optional force-heading)
7411 "Insert a new heading with the same level and TODO state as current heading.
7412 If the heading has no TODO state, or if the state is DONE, use the first
7413 state (TODO by default). Also with prefix arg, force first state."
7414 (interactive "P")
7415 (when (or force-heading (not (org-insert-item 'checkbox)))
7416 (org-insert-heading force-heading)
7417 (save-excursion
7418 (org-back-to-heading)
7419 (outline-previous-heading)
7420 (looking-at org-todo-line-regexp))
7421 (let*
7422 ((new-mark-x
7423 (if (or arg
7424 (not (match-beginning 2))
7425 (member (match-string 2) org-done-keywords))
7426 (car org-todo-keywords-1)
7427 (match-string 2)))
7428 (new-mark
7430 (run-hook-with-args-until-success
7431 'org-todo-get-default-hook new-mark-x nil)
7432 new-mark-x)))
7433 (beginning-of-line 1)
7434 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7435 (if org-treat-insert-todo-heading-as-state-change
7436 (org-todo new-mark)
7437 (insert new-mark " "))))
7438 (when org-provide-todo-statistics
7439 (org-update-parent-todo-statistics))))
7441 (defun org-insert-subheading (arg)
7442 "Insert a new subheading and demote it.
7443 Works for outline headings and for plain lists alike."
7444 (interactive "P")
7445 (org-insert-heading arg)
7446 (cond
7447 ((org-at-heading-p) (org-do-demote))
7448 ((org-at-item-p) (org-indent-item))))
7450 (defun org-insert-todo-subheading (arg)
7451 "Insert a new subheading with TODO keyword or checkbox and demote it.
7452 Works for outline headings and for plain lists alike."
7453 (interactive "P")
7454 (org-insert-todo-heading arg)
7455 (cond
7456 ((org-at-heading-p) (org-do-demote))
7457 ((org-at-item-p) (org-indent-item))))
7459 ;;; Promotion and Demotion
7461 (defvar org-after-demote-entry-hook nil
7462 "Hook run after an entry has been demoted.
7463 The cursor will be at the beginning of the entry.
7464 When a subtree is being demoted, the hook will be called for each node.")
7466 (defvar org-after-promote-entry-hook nil
7467 "Hook run after an entry has been promoted.
7468 The cursor will be at the beginning of the entry.
7469 When a subtree is being promoted, the hook will be called for each node.")
7471 (defun org-promote-subtree ()
7472 "Promote the entire subtree.
7473 See also `org-promote'."
7474 (interactive)
7475 (save-excursion
7476 (org-with-limited-levels (org-map-tree 'org-promote)))
7477 (org-fix-position-after-promote))
7479 (defun org-demote-subtree ()
7480 "Demote the entire subtree. See `org-demote'.
7481 See also `org-promote'."
7482 (interactive)
7483 (save-excursion
7484 (org-with-limited-levels (org-map-tree 'org-demote)))
7485 (org-fix-position-after-promote))
7488 (defun org-do-promote ()
7489 "Promote the current heading higher up the tree.
7490 If the region is active in `transient-mark-mode', promote all headings
7491 in the region."
7492 (interactive)
7493 (save-excursion
7494 (if (org-region-active-p)
7495 (org-map-region 'org-promote (region-beginning) (region-end))
7496 (org-promote)))
7497 (org-fix-position-after-promote))
7499 (defun org-do-demote ()
7500 "Demote the current heading lower down the tree.
7501 If the region is active in `transient-mark-mode', demote all headings
7502 in the region."
7503 (interactive)
7504 (save-excursion
7505 (if (org-region-active-p)
7506 (org-map-region 'org-demote (region-beginning) (region-end))
7507 (org-demote)))
7508 (org-fix-position-after-promote))
7510 (defun org-fix-position-after-promote ()
7511 "Make sure that after pro/demotion cursor position is right."
7512 (let ((pos (point)))
7513 (when (save-excursion
7514 (beginning-of-line 1)
7515 (looking-at org-todo-line-regexp)
7516 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7517 (cond ((eobp) (insert " "))
7518 ((eolp) (insert " "))
7519 ((equal (char-after) ?\ ) (forward-char 1))))))
7521 (defun org-current-level ()
7522 "Return the level of the current entry, or nil if before the first headline.
7523 The level is the number of stars at the beginning of the headline."
7524 (save-excursion
7525 (org-with-limited-levels
7526 (if (ignore-errors (org-back-to-heading t))
7527 (funcall outline-level)))))
7529 (defun org-get-previous-line-level ()
7530 "Return the outline depth of the last headline before the current line.
7531 Returns 0 for the first headline in the buffer, and nil if before the
7532 first headline."
7533 (let ((current-level (org-current-level))
7534 (prev-level (when (> (line-number-at-pos) 1)
7535 (save-excursion
7536 (beginning-of-line 0)
7537 (org-current-level)))))
7538 (cond ((null current-level) nil) ; Before first headline
7539 ((null prev-level) 0) ; At first headline
7540 (prev-level))))
7542 (defun org-reduced-level (l)
7543 "Compute the effective level of a heading.
7544 This takes into account the setting of `org-odd-levels-only'."
7545 (cond
7546 ((zerop l) 0)
7547 (org-odd-levels-only (1+ (floor (/ l 2))))
7548 (t l)))
7550 (defun org-level-increment ()
7551 "Return the number of stars that will be added or removed at a
7552 time to headlines when structure editing, based on the value of
7553 `org-odd-levels-only'."
7554 (if org-odd-levels-only 2 1))
7556 (defun org-get-valid-level (level &optional change)
7557 "Rectify a level change under the influence of `org-odd-levels-only'
7558 LEVEL is a current level, CHANGE is by how much the level should be
7559 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7560 even level numbers will become the next higher odd number."
7561 (if org-odd-levels-only
7562 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7563 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7564 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7565 (max 1 (+ level (or change 0)))))
7567 (if (boundp 'define-obsolete-function-alias)
7568 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7569 (define-obsolete-function-alias 'org-get-legal-level
7570 'org-get-valid-level)
7571 (define-obsolete-function-alias 'org-get-legal-level
7572 'org-get-valid-level "23.1")))
7574 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7575 ;; ̀org-with-limited-levels'
7576 (defun org-promote ()
7577 "Promote the current heading higher up the tree.
7578 If the region is active in `transient-mark-mode', promote all headings
7579 in the region."
7580 (org-back-to-heading t)
7581 (let* ((level (save-match-data (funcall outline-level)))
7582 (after-change-functions (remove 'flyspell-after-change-function
7583 after-change-functions))
7584 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7585 (diff (abs (- level (length up-head) -1))))
7586 (cond ((and (= level 1) org-called-with-limited-levels
7587 org-allow-promoting-top-level-subtree)
7588 (replace-match "# " nil t))
7589 ((= level 1)
7590 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7591 (t (replace-match up-head nil t)))
7592 ;; Fixup tag positioning
7593 (unless (= level 1)
7594 (and org-auto-align-tags (org-set-tags nil t))
7595 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7596 (run-hooks 'org-after-promote-entry-hook)))
7598 (defun org-demote ()
7599 "Demote the current heading lower down the tree.
7600 If the region is active in `transient-mark-mode', demote all headings
7601 in the region."
7602 (org-back-to-heading t)
7603 (let* ((level (save-match-data (funcall outline-level)))
7604 (after-change-functions (remove 'flyspell-after-change-function
7605 after-change-functions))
7606 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7607 (diff (abs (- level (length down-head) -1))))
7608 (replace-match down-head nil t)
7609 ;; Fixup tag positioning
7610 (and org-auto-align-tags (org-set-tags nil t))
7611 (if org-adapt-indentation (org-fixup-indentation diff))
7612 (run-hooks 'org-after-demote-entry-hook)))
7614 (defun org-cycle-level ()
7615 "Cycle the level of an empty headline through possible states.
7616 This goes first to child, then to parent, level, then up the hierarchy.
7617 After top level, it switches back to sibling level."
7618 (interactive)
7619 (let ((org-adapt-indentation nil))
7620 (when (org-point-at-end-of-empty-headline)
7621 (setq this-command 'org-cycle-level) ; Only needed for caching
7622 (let ((cur-level (org-current-level))
7623 (prev-level (org-get-previous-line-level)))
7624 (cond
7625 ;; If first headline in file, promote to top-level.
7626 ((= prev-level 0)
7627 (loop repeat (/ (- cur-level 1) (org-level-increment))
7628 do (org-do-promote)))
7629 ;; If same level as prev, demote one.
7630 ((= prev-level cur-level)
7631 (org-do-demote))
7632 ;; If parent is top-level, promote to top level if not already.
7633 ((= prev-level 1)
7634 (loop repeat (/ (- cur-level 1) (org-level-increment))
7635 do (org-do-promote)))
7636 ;; If top-level, return to prev-level.
7637 ((= cur-level 1)
7638 (loop repeat (/ (- prev-level 1) (org-level-increment))
7639 do (org-do-demote)))
7640 ;; If less than prev-level, promote one.
7641 ((< cur-level prev-level)
7642 (org-do-promote))
7643 ;; If deeper than prev-level, promote until higher than
7644 ;; prev-level.
7645 ((> cur-level prev-level)
7646 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7647 do (org-do-promote))))
7648 t))))
7650 (defun org-map-tree (fun)
7651 "Call FUN for every heading underneath the current one."
7652 (org-back-to-heading)
7653 (let ((level (funcall outline-level)))
7654 (save-excursion
7655 (funcall fun)
7656 (while (and (progn
7657 (outline-next-heading)
7658 (> (funcall outline-level) level))
7659 (not (eobp)))
7660 (funcall fun)))))
7662 (defun org-map-region (fun beg end)
7663 "Call FUN for every heading between BEG and END."
7664 (let ((org-ignore-region t))
7665 (save-excursion
7666 (setq end (copy-marker end))
7667 (goto-char beg)
7668 (if (and (re-search-forward org-outline-regexp-bol nil t)
7669 (< (point) end))
7670 (funcall fun))
7671 (while (and (progn
7672 (outline-next-heading)
7673 (< (point) end))
7674 (not (eobp)))
7675 (funcall fun)))))
7677 (defvar org-property-end-re) ; silence byte-compiler
7678 (defun org-fixup-indentation (diff)
7679 "Change the indentation in the current entry by DIFF.
7680 However, if any line in the current entry has no indentation, or if it
7681 would end up with no indentation after the change, nothing at all is done."
7682 (save-excursion
7683 (let ((end (save-excursion (outline-next-heading)
7684 (point-marker)))
7685 (prohibit (if (> diff 0)
7686 "^\\S-"
7687 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7688 col)
7689 (unless (save-excursion (end-of-line 1)
7690 (re-search-forward prohibit end t))
7691 (while (and (< (point) end)
7692 (re-search-forward "^[ \t]+" end t))
7693 (goto-char (match-end 0))
7694 (setq col (current-column))
7695 (if (< diff 0) (replace-match ""))
7696 (org-indent-to-column (+ diff col))))
7697 (move-marker end nil))))
7699 (defun org-convert-to-odd-levels ()
7700 "Convert an org-mode file with all levels allowed to one with odd levels.
7701 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7702 level 5 etc."
7703 (interactive)
7704 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7705 (let ((outline-level 'org-outline-level)
7706 (org-odd-levels-only nil) n)
7707 (save-excursion
7708 (goto-char (point-min))
7709 (while (re-search-forward "^\\*\\*+ " nil t)
7710 (setq n (- (length (match-string 0)) 2))
7711 (while (>= (setq n (1- n)) 0)
7712 (org-demote))
7713 (end-of-line 1))))))
7715 (defun org-convert-to-oddeven-levels ()
7716 "Convert an org-mode file with only odd levels to one with odd/even levels.
7717 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7718 file contains a section with an even level, conversion would
7719 destroy the structure of the file. An error is signaled in this
7720 case."
7721 (interactive)
7722 (goto-char (point-min))
7723 ;; First check if there are no even levels
7724 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7725 (org-show-context t)
7726 (error "Not all levels are odd in this file. Conversion not possible"))
7727 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7728 (let ((outline-regexp org-outline-regexp)
7729 (outline-level 'org-outline-level)
7730 (org-odd-levels-only nil) n)
7731 (save-excursion
7732 (goto-char (point-min))
7733 (while (re-search-forward "^\\*\\*+ " nil t)
7734 (setq n (/ (1- (length (match-string 0))) 2))
7735 (while (>= (setq n (1- n)) 0)
7736 (org-promote))
7737 (end-of-line 1))))))
7739 (defun org-tr-level (n)
7740 "Make N odd if required."
7741 (if org-odd-levels-only (1+ (/ n 2)) n))
7743 ;;; Vertical tree motion, cutting and pasting of subtrees
7745 (defun org-move-subtree-up (&optional arg)
7746 "Move the current subtree up past ARG headlines of the same level."
7747 (interactive "p")
7748 (org-move-subtree-down (- (prefix-numeric-value arg))))
7750 (defun org-move-subtree-down (&optional arg)
7751 "Move the current subtree down past ARG headlines of the same level."
7752 (interactive "p")
7753 (setq arg (prefix-numeric-value arg))
7754 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7755 'org-get-last-sibling))
7756 (ins-point (make-marker))
7757 (cnt (abs arg))
7758 (col (current-column))
7759 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7760 ;; Select the tree
7761 (org-back-to-heading)
7762 (setq beg0 (point))
7763 (save-excursion
7764 (setq ne-beg (org-back-over-empty-lines))
7765 (setq beg (point)))
7766 (save-match-data
7767 (save-excursion (outline-end-of-heading)
7768 (setq folded (outline-invisible-p)))
7769 (outline-end-of-subtree))
7770 (outline-next-heading)
7771 (setq ne-end (org-back-over-empty-lines))
7772 (setq end (point))
7773 (goto-char beg0)
7774 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7775 ;; include less whitespace
7776 (save-excursion
7777 (goto-char beg)
7778 (forward-line (- ne-beg ne-end))
7779 (setq beg (point))))
7780 ;; Find insertion point, with error handling
7781 (while (> cnt 0)
7782 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7783 (progn (goto-char beg0)
7784 (error "Cannot move past superior level or buffer limit")))
7785 (setq cnt (1- cnt)))
7786 (if (> arg 0)
7787 ;; Moving forward - still need to move over subtree
7788 (progn (org-end-of-subtree t t)
7789 (save-excursion
7790 (org-back-over-empty-lines)
7791 (or (bolp) (newline)))))
7792 (setq ne-ins (org-back-over-empty-lines))
7793 (move-marker ins-point (point))
7794 (setq txt (buffer-substring beg end))
7795 (org-save-markers-in-region beg end)
7796 (delete-region beg end)
7797 (org-remove-empty-overlays-at beg)
7798 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7799 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7800 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7801 (let ((bbb (point)))
7802 (insert-before-markers txt)
7803 (org-reinstall-markers-in-region bbb)
7804 (move-marker ins-point bbb))
7805 (or (bolp) (insert "\n"))
7806 (setq ins-end (point))
7807 (goto-char ins-point)
7808 (org-skip-whitespace)
7809 (when (and (< arg 0)
7810 (org-first-sibling-p)
7811 (> ne-ins ne-beg))
7812 ;; Move whitespace back to beginning
7813 (save-excursion
7814 (goto-char ins-end)
7815 (let ((kill-whole-line t))
7816 (kill-line (- ne-ins ne-beg)) (point)))
7817 (insert (make-string (- ne-ins ne-beg) ?\n)))
7818 (move-marker ins-point nil)
7819 (if folded
7820 (hide-subtree)
7821 (org-show-entry)
7822 (show-children)
7823 (org-cycle-hide-drawers 'children))
7824 (org-clean-visibility-after-subtree-move)
7825 ;; move back to the initial column we were at
7826 (move-to-column col)))
7828 (defvar org-subtree-clip ""
7829 "Clipboard for cut and paste of subtrees.
7830 This is actually only a copy of the kill, because we use the normal kill
7831 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7833 (defvar org-subtree-clip-folded nil
7834 "Was the last copied subtree folded?
7835 This is used to fold the tree back after pasting.")
7837 (defun org-cut-subtree (&optional n)
7838 "Cut the current subtree into the clipboard.
7839 With prefix arg N, cut this many sequential subtrees.
7840 This is a short-hand for marking the subtree and then cutting it."
7841 (interactive "p")
7842 (org-copy-subtree n 'cut))
7844 (defun org-copy-subtree (&optional n cut force-store-markers)
7845 "Cut the current subtree into the clipboard.
7846 With prefix arg N, cut this many sequential subtrees.
7847 This is a short-hand for marking the subtree and then copying it.
7848 If CUT is non-nil, actually cut the subtree.
7849 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7850 of some markers in the region, even if CUT is non-nil. This is
7851 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7852 (interactive "p")
7853 (let (beg end folded (beg0 (point)))
7854 (if (org-called-interactively-p 'any)
7855 (org-back-to-heading nil) ; take what looks like a subtree
7856 (org-back-to-heading t)) ; take what is really there
7857 (org-back-over-empty-lines)
7858 (setq beg (point))
7859 (skip-chars-forward " \t\r\n")
7860 (save-match-data
7861 (save-excursion (outline-end-of-heading)
7862 (setq folded (outline-invisible-p)))
7863 (condition-case nil
7864 (org-forward-heading-same-level (1- n) t)
7865 (error nil))
7866 (org-end-of-subtree t t))
7867 (org-back-over-empty-lines)
7868 (setq end (point))
7869 (goto-char beg0)
7870 (when (> end beg)
7871 (setq org-subtree-clip-folded folded)
7872 (when (or cut force-store-markers)
7873 (org-save-markers-in-region beg end))
7874 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7875 (setq org-subtree-clip (current-kill 0))
7876 (message "%s: Subtree(s) with %d characters"
7877 (if cut "Cut" "Copied")
7878 (length org-subtree-clip)))))
7880 (defun org-paste-subtree (&optional level tree for-yank)
7881 "Paste the clipboard as a subtree, with modification of headline level.
7882 The entire subtree is promoted or demoted in order to match a new headline
7883 level.
7885 If the cursor is at the beginning of a headline, the same level as
7886 that headline is used to paste the tree
7888 If not, the new level is derived from the *visible* headings
7889 before and after the insertion point, and taken to be the inferior headline
7890 level of the two. So if the previous visible heading is level 3 and the
7891 next is level 4 (or vice versa), level 4 will be used for insertion.
7892 This makes sure that the subtree remains an independent subtree and does
7893 not swallow low level entries.
7895 You can also force a different level, either by using a numeric prefix
7896 argument, or by inserting the heading marker by hand. For example, if the
7897 cursor is after \"*****\", then the tree will be shifted to level 5.
7899 If optional TREE is given, use this text instead of the kill ring.
7901 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7902 move back over whitespace before inserting, and move point to the end of
7903 the inserted text when done."
7904 (interactive "P")
7905 (setq tree (or tree (and kill-ring (current-kill 0))))
7906 (unless (org-kill-is-subtree-p tree)
7907 (error "%s"
7908 (substitute-command-keys
7909 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7910 (org-with-limited-levels
7911 (let* ((visp (not (outline-invisible-p)))
7912 (txt tree)
7913 (^re_ "\\(\\*+\\)[ \t]*")
7914 (old-level (if (string-match org-outline-regexp-bol txt)
7915 (- (match-end 0) (match-beginning 0) 1)
7916 -1))
7917 (force-level (cond (level (prefix-numeric-value level))
7918 ((and (looking-at "[ \t]*$")
7919 (string-match
7920 "^\\*+$" (buffer-substring
7921 (point-at-bol) (point))))
7922 (- (match-end 1) (match-beginning 1)))
7923 ((and (bolp)
7924 (looking-at org-outline-regexp))
7925 (- (match-end 0) (point) 1))))
7926 (previous-level (save-excursion
7927 (condition-case nil
7928 (progn
7929 (outline-previous-visible-heading 1)
7930 (if (looking-at ^re_)
7931 (- (match-end 0) (match-beginning 0) 1)
7933 (error 1))))
7934 (next-level (save-excursion
7935 (condition-case nil
7936 (progn
7937 (or (looking-at org-outline-regexp)
7938 (outline-next-visible-heading 1))
7939 (if (looking-at ^re_)
7940 (- (match-end 0) (match-beginning 0) 1)
7942 (error 1))))
7943 (new-level (or force-level (max previous-level next-level)))
7944 (shift (if (or (= old-level -1)
7945 (= new-level -1)
7946 (= old-level new-level))
7948 (- new-level old-level)))
7949 (delta (if (> shift 0) -1 1))
7950 (func (if (> shift 0) 'org-demote 'org-promote))
7951 (org-odd-levels-only nil)
7952 beg end newend)
7953 ;; Remove the forced level indicator
7954 (if force-level
7955 (delete-region (point-at-bol) (point)))
7956 ;; Paste
7957 (beginning-of-line (if (bolp) 1 2))
7958 (unless for-yank (org-back-over-empty-lines))
7959 (setq beg (point))
7960 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7961 (insert-before-markers txt)
7962 (unless (string-match "\n\\'" txt) (insert "\n"))
7963 (setq newend (point))
7964 (org-reinstall-markers-in-region beg)
7965 (setq end (point))
7966 (goto-char beg)
7967 (skip-chars-forward " \t\n\r")
7968 (setq beg (point))
7969 (if (and (outline-invisible-p) visp)
7970 (save-excursion (outline-show-heading)))
7971 ;; Shift if necessary
7972 (unless (= shift 0)
7973 (save-restriction
7974 (narrow-to-region beg end)
7975 (while (not (= shift 0))
7976 (org-map-region func (point-min) (point-max))
7977 (setq shift (+ delta shift)))
7978 (goto-char (point-min))
7979 (setq newend (point-max))))
7980 (when (or (org-called-interactively-p 'interactive) for-yank)
7981 (message "Clipboard pasted as level %d subtree" new-level))
7982 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7983 kill-ring
7984 (eq org-subtree-clip (current-kill 0))
7985 org-subtree-clip-folded)
7986 ;; The tree was folded before it was killed/copied
7987 (hide-subtree))
7988 (and for-yank (goto-char newend)))))
7990 (defun org-kill-is-subtree-p (&optional txt)
7991 "Check if the current kill is an outline subtree, or a set of trees.
7992 Returns nil if kill does not start with a headline, or if the first
7993 headline level is not the largest headline level in the tree.
7994 So this will actually accept several entries of equal levels as well,
7995 which is OK for `org-paste-subtree'.
7996 If optional TXT is given, check this string instead of the current kill."
7997 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7998 (re (org-get-limited-outline-regexp))
7999 (^re (concat "^" re))
8000 (start-level (and kill
8001 (string-match
8002 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8003 kill)
8004 (- (match-end 2) (match-beginning 2) 1)))
8005 (start (1+ (or (match-beginning 2) -1))))
8006 (if (not start-level)
8007 (progn
8008 nil) ;; does not even start with a heading
8009 (catch 'exit
8010 (while (setq start (string-match ^re kill (1+ start)))
8011 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8012 (throw 'exit nil)))
8013 t))))
8015 (defvar org-markers-to-move nil
8016 "Markers that should be moved with a cut-and-paste operation.
8017 Those markers are stored together with their positions relative to
8018 the start of the region.")
8020 (defun org-save-markers-in-region (beg end)
8021 "Check markers in region.
8022 If these markers are between BEG and END, record their position relative
8023 to BEG, so that after moving the block of text, we can put the markers back
8024 into place.
8025 This function gets called just before an entry or tree gets cut from the
8026 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8027 called immediately, to move the markers with the entries."
8028 (setq org-markers-to-move nil)
8029 (when (featurep 'org-clock)
8030 (org-clock-save-markers-for-cut-and-paste beg end))
8031 (when (featurep 'org-agenda)
8032 (org-agenda-save-markers-for-cut-and-paste beg end)))
8034 (defun org-check-and-save-marker (marker beg end)
8035 "Check if MARKER is between BEG and END.
8036 If yes, remember the marker and the distance to BEG."
8037 (when (and (marker-buffer marker)
8038 (equal (marker-buffer marker) (current-buffer)))
8039 (if (and (>= marker beg) (< marker end))
8040 (push (cons marker (- marker beg)) org-markers-to-move))))
8042 (defun org-reinstall-markers-in-region (beg)
8043 "Move all remembered markers to their position relative to BEG."
8044 (mapc (lambda (x)
8045 (move-marker (car x) (+ beg (cdr x))))
8046 org-markers-to-move)
8047 (setq org-markers-to-move nil))
8049 (defun org-narrow-to-subtree ()
8050 "Narrow buffer to the current subtree."
8051 (interactive)
8052 (save-excursion
8053 (save-match-data
8054 (org-with-limited-levels
8055 (narrow-to-region
8056 (progn (org-back-to-heading t) (point))
8057 (progn (org-end-of-subtree t t)
8058 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8059 (point)))))))
8061 (defun org-narrow-to-block ()
8062 "Narrow buffer to the current block."
8063 (interactive)
8064 (let* ((case-fold-search t)
8065 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8066 "^[ \t]*#\\+end_.*")))
8067 (if blockp
8068 (narrow-to-region (car blockp) (cdr blockp))
8069 (error "Not in a block"))))
8071 (eval-when-compile
8072 (defvar org-property-drawer-re))
8074 (defvar org-property-start-re) ;; defined below
8075 (defun org-clone-subtree-with-time-shift (n &optional shift)
8076 "Clone the task (subtree) at point N times.
8077 The clones will be inserted as siblings.
8079 In interactive use, the user will be prompted for the number of
8080 clones to be produced, and for a time SHIFT, which may be a
8081 repeater as used in time stamps, for example `+3d'.
8083 When a valid repeater is given and the entry contains any time
8084 stamps, the clones will become a sequence in time, with time
8085 stamps in the subtree shifted for each clone produced. If SHIFT
8086 is nil or the empty string, time stamps will be left alone. The
8087 ID property of the original subtree is removed.
8089 If the original subtree did contain time stamps with a repeater,
8090 the following will happen:
8091 - the repeater will be removed in each clone
8092 - an additional clone will be produced, with the current, unshifted
8093 date(s) in the entry.
8094 - the original entry will be placed *after* all the clones, with
8095 repeater intact.
8096 - the start days in the repeater in the original entry will be shifted
8097 to past the last clone.
8098 In this way you can spell out a number of instances of a repeating task,
8099 and still retain the repeater to cover future instances of the task."
8100 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8101 (let (beg end template task idprop
8102 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8103 (drawer-re org-drawer-regexp))
8104 (if (not (and (integerp n) (> n 0)))
8105 (error "Invalid number of replications %s" n))
8106 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8107 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8108 shift)))
8109 (error "Invalid shift specification %s" shift))
8110 (when doshift
8111 (setq shift-n (string-to-number (match-string 1 shift))
8112 shift-what (cdr (assoc (match-string 2 shift)
8113 '(("d" . day) ("w" . week)
8114 ("m" . month) ("y" . year))))))
8115 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8116 (setq nmin 1 nmax n)
8117 (org-back-to-heading t)
8118 (setq beg (point))
8119 (setq idprop (org-entry-get nil "ID"))
8120 (org-end-of-subtree t t)
8121 (or (bolp) (insert "\n"))
8122 (setq end (point))
8123 (setq template (buffer-substring beg end))
8124 (when (and doshift
8125 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8126 (delete-region beg end)
8127 (setq end beg)
8128 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8129 (goto-char end)
8130 (loop for n from nmin to nmax do
8131 ;; prepare clone
8132 (with-temp-buffer
8133 (insert template)
8134 (org-mode)
8135 (goto-char (point-min))
8136 (org-show-subtree)
8137 (and idprop (if org-clone-delete-id
8138 (org-entry-delete nil "ID")
8139 (org-id-get-create t)))
8140 (unless (= n 0)
8141 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8142 (kill-whole-line))
8143 (goto-char (point-min))
8144 (while (re-search-forward drawer-re nil t)
8145 (mapc (lambda (d)
8146 (org-remove-empty-drawer-at d (point))) org-drawers)))
8147 (goto-char (point-min))
8148 (when doshift
8149 (while (re-search-forward org-ts-regexp-both nil t)
8150 (org-timestamp-change (* n shift-n) shift-what))
8151 (unless (= n n-no-remove)
8152 (goto-char (point-min))
8153 (while (re-search-forward org-ts-regexp nil t)
8154 (save-excursion
8155 (goto-char (match-beginning 0))
8156 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8157 (delete-region (match-beginning 1) (match-end 1)))))))
8158 (setq task (buffer-string)))
8159 (insert task))
8160 (goto-char beg)))
8162 ;;; Outline Sorting
8164 (defun org-sort (with-case)
8165 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8166 Optional argument WITH-CASE means sort case-sensitively."
8167 (interactive "P")
8168 (cond
8169 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8170 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8172 (org-call-with-arg 'org-sort-entries with-case))))
8174 (defun org-sort-remove-invisible (s)
8175 (remove-text-properties 0 (length s) org-rm-props s)
8176 (while (string-match org-bracket-link-regexp s)
8177 (setq s (replace-match (if (match-end 2)
8178 (match-string 3 s)
8179 (match-string 1 s)) t t s)))
8182 (defvar org-priority-regexp) ; defined later in the file
8184 (defvar org-after-sorting-entries-or-items-hook nil
8185 "Hook that is run after a bunch of entries or items have been sorted.
8186 When children are sorted, the cursor is in the parent line when this
8187 hook gets called. When a region or a plain list is sorted, the cursor
8188 will be in the first entry of the sorted region/list.")
8190 (defun org-sort-entries
8191 (&optional with-case sorting-type getkey-func compare-func property)
8192 "Sort entries on a certain level of an outline tree.
8193 If there is an active region, the entries in the region are sorted.
8194 Else, if the cursor is before the first entry, sort the top-level items.
8195 Else, the children of the entry at point are sorted.
8197 Sorting can be alphabetically, numerically, by date/time as given by
8198 a time stamp, by a property or by priority.
8200 The command prompts for the sorting type unless it has been given to the
8201 function through the SORTING-TYPE argument, which needs to be a character,
8202 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8203 precise meaning of each character:
8205 n Numerically, by converting the beginning of the entry/item to a number.
8206 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8207 t By date/time, either the first active time stamp in the entry, or, if
8208 none exist, by the first inactive one.
8209 s By the scheduled date/time.
8210 d By deadline date/time.
8211 c By creation time, which is assumed to be the first inactive time stamp
8212 at the beginning of a line.
8213 p By priority according to the cookie.
8214 r By the value of a property.
8216 Capital letters will reverse the sort order.
8218 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8219 called with point at the beginning of the record. It must return either
8220 a string or a number that should serve as the sorting key for that record.
8222 Comparing entries ignores case by default. However, with an optional argument
8223 WITH-CASE, the sorting considers case as well."
8224 (interactive "P")
8225 (let ((case-func (if with-case 'identity 'downcase))
8226 start beg end stars re re2
8227 txt what tmp)
8228 ;; Find beginning and end of region to sort
8229 (cond
8230 ((org-region-active-p)
8231 ;; we will sort the region
8232 (setq end (region-end)
8233 what "region")
8234 (goto-char (region-beginning))
8235 (if (not (org-at-heading-p)) (outline-next-heading))
8236 (setq start (point)))
8237 ((or (org-at-heading-p)
8238 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8239 ;; we will sort the children of the current headline
8240 (org-back-to-heading)
8241 (setq start (point)
8242 end (progn (org-end-of-subtree t t)
8243 (or (bolp) (insert "\n"))
8244 (org-back-over-empty-lines)
8245 (point))
8246 what "children")
8247 (goto-char start)
8248 (show-subtree)
8249 (outline-next-heading))
8251 ;; we will sort the top-level entries in this file
8252 (goto-char (point-min))
8253 (or (org-at-heading-p) (outline-next-heading))
8254 (setq start (point))
8255 (goto-char (point-max))
8256 (beginning-of-line 1)
8257 (when (looking-at ".*?\\S-")
8258 ;; File ends in a non-white line
8259 (end-of-line 1)
8260 (insert "\n"))
8261 (setq end (point-max))
8262 (setq what "top-level")
8263 (goto-char start)
8264 (show-all)))
8266 (setq beg (point))
8267 (if (>= beg end) (error "Nothing to sort"))
8269 (looking-at "\\(\\*+\\)")
8270 (setq stars (match-string 1)
8271 re (concat "^" (regexp-quote stars) " +")
8272 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8273 txt (buffer-substring beg end))
8274 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8275 (if (and (not (equal stars "*")) (string-match re2 txt))
8276 (error "Region to sort contains a level above the first entry"))
8278 (unless sorting-type
8279 (message
8280 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8281 [t]ime [s]cheduled [d]eadline [c]reated
8282 A/N/T/S/D/C/P/O/F means reversed:"
8283 what)
8284 (setq sorting-type (read-char-exclusive))
8286 (and (= (downcase sorting-type) ?f)
8287 (setq getkey-func
8288 (org-icompleting-read "Sort using function: "
8289 obarray 'fboundp t nil nil))
8290 (setq getkey-func (intern getkey-func)))
8292 (and (= (downcase sorting-type) ?r)
8293 (setq property
8294 (org-icompleting-read "Property: "
8295 (mapcar 'list (org-buffer-property-keys t))
8296 nil t))))
8298 (message "Sorting entries...")
8300 (save-restriction
8301 (narrow-to-region start end)
8302 (let ((dcst (downcase sorting-type))
8303 (case-fold-search nil)
8304 (now (current-time)))
8305 (sort-subr
8306 (/= dcst sorting-type)
8307 ;; This function moves to the beginning character of the "record" to
8308 ;; be sorted.
8309 (lambda nil
8310 (if (re-search-forward re nil t)
8311 (goto-char (match-beginning 0))
8312 (goto-char (point-max))))
8313 ;; This function moves to the last character of the "record" being
8314 ;; sorted.
8315 (lambda nil
8316 (save-match-data
8317 (condition-case nil
8318 (outline-forward-same-level 1)
8319 (error
8320 (goto-char (point-max))))))
8321 ;; This function returns the value that gets sorted against.
8322 (lambda nil
8323 (cond
8324 ((= dcst ?n)
8325 (if (looking-at org-complex-heading-regexp)
8326 (string-to-number (match-string 4))
8327 nil))
8328 ((= dcst ?a)
8329 (if (looking-at org-complex-heading-regexp)
8330 (funcall case-func (match-string 4))
8331 nil))
8332 ((= dcst ?t)
8333 (let ((end (save-excursion (outline-next-heading) (point))))
8334 (if (or (re-search-forward org-ts-regexp end t)
8335 (re-search-forward org-ts-regexp-both end t))
8336 (org-time-string-to-seconds (match-string 0))
8337 (org-float-time now))))
8338 ((= dcst ?c)
8339 (let ((end (save-excursion (outline-next-heading) (point))))
8340 (if (re-search-forward
8341 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8342 end t)
8343 (org-time-string-to-seconds (match-string 0))
8344 (org-float-time now))))
8345 ((= dcst ?s)
8346 (let ((end (save-excursion (outline-next-heading) (point))))
8347 (if (re-search-forward org-scheduled-time-regexp end t)
8348 (org-time-string-to-seconds (match-string 1))
8349 (org-float-time now))))
8350 ((= dcst ?d)
8351 (let ((end (save-excursion (outline-next-heading) (point))))
8352 (if (re-search-forward org-deadline-time-regexp end t)
8353 (org-time-string-to-seconds (match-string 1))
8354 (org-float-time now))))
8355 ((= dcst ?p)
8356 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8357 (string-to-char (match-string 2))
8358 org-default-priority))
8359 ((= dcst ?r)
8360 (or (org-entry-get nil property) ""))
8361 ((= dcst ?o)
8362 (if (looking-at org-complex-heading-regexp)
8363 (- 9999 (length (member (match-string 2)
8364 org-todo-keywords-1)))))
8365 ((= dcst ?f)
8366 (if getkey-func
8367 (progn
8368 (setq tmp (funcall getkey-func))
8369 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8370 tmp)
8371 (error "Invalid key function `%s'" getkey-func)))
8372 (t (error "Invalid sorting type `%c'" sorting-type))))
8374 (cond
8375 ((= dcst ?a) 'string<)
8376 ((= dcst ?f) compare-func)
8377 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8378 (run-hooks 'org-after-sorting-entries-or-items-hook)
8379 (message "Sorting entries...done")))
8381 (defun org-do-sort (table what &optional with-case sorting-type)
8382 "Sort TABLE of WHAT according to SORTING-TYPE.
8383 The user will be prompted for the SORTING-TYPE if the call to this
8384 function does not specify it. WHAT is only for the prompt, to indicate
8385 what is being sorted. The sorting key will be extracted from
8386 the car of the elements of the table.
8387 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8388 (unless sorting-type
8389 (message
8390 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8391 what)
8392 (setq sorting-type (read-char-exclusive)))
8393 (let ((dcst (downcase sorting-type))
8394 extractfun comparefun)
8395 ;; Define the appropriate functions
8396 (cond
8397 ((= dcst ?n)
8398 (setq extractfun 'string-to-number
8399 comparefun (if (= dcst sorting-type) '< '>)))
8400 ((= dcst ?a)
8401 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8402 (lambda(x) (downcase (org-sort-remove-invisible x))))
8403 comparefun (if (= dcst sorting-type)
8404 'string<
8405 (lambda (a b) (and (not (string< a b))
8406 (not (string= a b)))))))
8407 ((= dcst ?t)
8408 (setq extractfun
8409 (lambda (x)
8410 (if (or (string-match org-ts-regexp x)
8411 (string-match org-ts-regexp-both x))
8412 (org-float-time
8413 (org-time-string-to-time (match-string 0 x)))
8415 comparefun (if (= dcst sorting-type) '< '>)))
8416 (t (error "Invalid sorting type `%c'" sorting-type)))
8418 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8419 table)
8420 (lambda (a b) (funcall comparefun (car a) (car b))))))
8423 ;;; The orgstruct minor mode
8425 ;; Define a minor mode which can be used in other modes in order to
8426 ;; integrate the org-mode structure editing commands.
8428 ;; This is really a hack, because the org-mode structure commands use
8429 ;; keys which normally belong to the major mode. Here is how it
8430 ;; works: The minor mode defines all the keys necessary to operate the
8431 ;; structure commands, but wraps the commands into a function which
8432 ;; tests if the cursor is currently at a headline or a plain list
8433 ;; item. If that is the case, the structure command is used,
8434 ;; temporarily setting many Org-mode variables like regular
8435 ;; expressions for filling etc. However, when any of those keys is
8436 ;; used at a different location, function uses `key-binding' to look
8437 ;; up if the key has an associated command in another currently active
8438 ;; keymap (minor modes, major mode, global), and executes that
8439 ;; command. There might be problems if any of the keys is otherwise
8440 ;; used as a prefix key.
8442 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8443 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8444 ;; addresses this by checking explicitly for both bindings.
8446 (defvar orgstruct-mode-map (make-sparse-keymap)
8447 "Keymap for the minor `orgstruct-mode'.")
8449 (defvar org-local-vars nil
8450 "List of local variables, for use by `orgstruct-mode'.")
8452 ;;;###autoload
8453 (define-minor-mode orgstruct-mode
8454 "Toggle the minor mode `orgstruct-mode'.
8455 This mode is for using Org-mode structure commands in other
8456 modes. The following keys behave as if Org-mode were active, if
8457 the cursor is on a headline, or on a plain list item (both as
8458 defined by Org-mode).
8460 M-up Move entry/item up
8461 M-down Move entry/item down
8462 M-left Promote
8463 M-right Demote
8464 M-S-up Move entry/item up
8465 M-S-down Move entry/item down
8466 M-S-left Promote subtree
8467 M-S-right Demote subtree
8468 M-q Fill paragraph and items like in Org-mode
8469 C-c ^ Sort entries
8470 C-c - Cycle list bullet
8471 TAB Cycle item visibility
8472 M-RET Insert new heading/item
8473 S-M-RET Insert new TODO heading / Checkbox item
8474 C-c C-c Set tags / toggle checkbox"
8475 nil " OrgStruct" nil
8476 (org-load-modules-maybe)
8477 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8479 ;;;###autoload
8480 (defun turn-on-orgstruct ()
8481 "Unconditionally turn on `orgstruct-mode'."
8482 (orgstruct-mode 1))
8484 (defvar org-fb-vars nil)
8485 (make-variable-buffer-local 'org-fb-vars)
8486 (defun orgstruct++-mode (&optional arg)
8487 "Toggle `orgstruct-mode', the enhanced version of it.
8488 In addition to setting orgstruct-mode, this also exports all
8489 indentation and autofilling variables from org-mode into the
8490 buffer. It will also recognize item context in multiline items."
8491 (interactive "P")
8492 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8493 (if (< arg 1)
8494 (progn (orgstruct-mode -1)
8495 (mapc (lambda(v)
8496 (org-set-local (car v)
8497 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8498 org-fb-vars))
8499 (orgstruct-mode 1)
8500 (setq org-fb-vars nil)
8501 (let (var val)
8502 (mapc
8503 (lambda (x)
8504 (when (string-match
8505 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8506 (symbol-name (car x)))
8507 (setq var (car x) val (nth 1 x))
8508 (push (list var `(quote ,(eval var))) org-fb-vars)
8509 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8510 org-local-vars)
8511 (org-set-local 'orgstruct-is-++ t))))
8513 (defvar orgstruct-is-++ nil
8514 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8515 (make-variable-buffer-local 'orgstruct-is-++)
8517 ;;;###autoload
8518 (defun turn-on-orgstruct++ ()
8519 "Unconditionally turn on `orgstruct++-mode'."
8520 (orgstruct++-mode 1))
8522 (defun orgstruct-error ()
8523 "Error when there is no default binding for a structure key."
8524 (interactive)
8525 (error "This key has no function outside structure elements"))
8527 (defun orgstruct-setup ()
8528 "Setup orgstruct keymaps."
8529 (let ((nfunc 0)
8530 (bindings
8531 (list
8532 '([(meta up)] org-metaup)
8533 '([(meta down)] org-metadown)
8534 '([(meta left)] org-metaleft)
8535 '([(meta right)] org-metaright)
8536 '([(meta shift up)] org-shiftmetaup)
8537 '([(meta shift down)] org-shiftmetadown)
8538 '([(meta shift left)] org-shiftmetaleft)
8539 '([(meta shift right)] org-shiftmetaright)
8540 '([?\e (up)] org-metaup)
8541 '([?\e (down)] org-metadown)
8542 '([?\e (left)] org-metaleft)
8543 '([?\e (right)] org-metaright)
8544 '([?\e (shift up)] org-shiftmetaup)
8545 '([?\e (shift down)] org-shiftmetadown)
8546 '([?\e (shift left)] org-shiftmetaleft)
8547 '([?\e (shift right)] org-shiftmetaright)
8548 '([(shift up)] org-shiftup)
8549 '([(shift down)] org-shiftdown)
8550 '([(shift left)] org-shiftleft)
8551 '([(shift right)] org-shiftright)
8552 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8553 '("\M-q" fill-paragraph)
8554 '("\C-c^" org-sort)
8555 '("\C-c-" org-cycle-list-bullet)))
8556 elt key fun cmd)
8557 (while (setq elt (pop bindings))
8558 (setq nfunc (1+ nfunc))
8559 (setq key (org-key (car elt))
8560 fun (nth 1 elt)
8561 cmd (orgstruct-make-binding fun nfunc key))
8562 (org-defkey orgstruct-mode-map key cmd))
8564 ;; Prevent an error for users who forgot to make autoloads
8565 (require 'org-element)
8567 ;; Special treatment needed for TAB and RET
8568 (org-defkey orgstruct-mode-map [(tab)]
8569 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8570 (org-defkey orgstruct-mode-map "\C-i"
8571 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8573 (org-defkey orgstruct-mode-map "\M-\C-m"
8574 (orgstruct-make-binding 'org-insert-heading 105
8575 "\M-\C-m" [(meta return)]))
8576 (org-defkey orgstruct-mode-map [(meta return)]
8577 (orgstruct-make-binding 'org-insert-heading 106
8578 [(meta return)] "\M-\C-m"))
8580 (org-defkey orgstruct-mode-map [(shift meta return)]
8581 (orgstruct-make-binding 'org-insert-todo-heading 107
8582 [(meta return)] "\M-\C-m"))
8584 (org-defkey orgstruct-mode-map "\e\C-m"
8585 (orgstruct-make-binding 'org-insert-heading 108
8586 "\e\C-m" [?\e (return)]))
8587 (org-defkey orgstruct-mode-map [?\e (return)]
8588 (orgstruct-make-binding 'org-insert-heading 109
8589 [?\e (return)] "\e\C-m"))
8590 (org-defkey orgstruct-mode-map [?\e (shift return)]
8591 (orgstruct-make-binding 'org-insert-todo-heading 110
8592 [?\e (return)] "\e\C-m"))
8594 (unless org-local-vars
8595 (setq org-local-vars (org-get-local-variables)))
8599 (defun orgstruct-make-binding (fun n &rest keys)
8600 "Create a function for binding in the structure minor mode.
8601 FUN is the command to call inside a table. N is used to create a unique
8602 command name. KEYS are keys that should be checked in for a command
8603 to execute outside of tables."
8604 (eval
8605 (list 'defun
8606 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8607 '(arg)
8608 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8609 "Outside of structure, run the binding of `"
8610 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8611 "'.")
8612 '(interactive "p")
8613 (list 'if
8614 `(org-context-p 'headline 'item
8615 (and orgstruct-is-++
8616 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8617 'item-body))
8618 (list 'org-run-like-in-org-mode (list 'quote fun))
8619 (list 'let '(orgstruct-mode)
8620 (list 'call-interactively
8621 (append '(or)
8622 (mapcar (lambda (k)
8623 (list 'key-binding k))
8624 keys)
8625 '('orgstruct-error))))))))
8627 (defun org-contextualize-keys (alist contexts)
8628 "Return valid elements in ALIST depending on CONTEXTS.
8630 `org-agenda-custom-commands' or `org-capture-templates' are the
8631 values used for ALIST, and `org-agenda-custom-commands-contexts'
8632 or `org-capture-templates-contexts' are the associated contexts
8633 definitions."
8634 (let ((contexts
8635 ;; normalize contexts
8636 (mapcar
8637 (lambda(c) (cond ((listp (cadr c))
8638 (list (car c) (car c) (cadr c)))
8639 ((string= "" (cadr c))
8640 (list (car c) (car c) (caddr c)))
8641 (t c))) contexts))
8642 (a alist) c r s)
8643 ;; loop over all commands or templates
8644 (while (setq c (pop a))
8645 (let (vrules repl)
8646 (cond
8647 ((not (assoc (car c) contexts))
8648 (push c r))
8649 ((and (assoc (car c) contexts)
8650 (setq vrules (org-contextualize-validate-key
8651 (car c) contexts)))
8652 (mapc (lambda (vr)
8653 (when (not (equal (car vr) (cadr vr)))
8654 (setq repl vr))) vrules)
8655 (if (not repl) (push c r)
8656 (push (cadr repl) s)
8657 (push
8658 (cons (car c)
8659 (cdr (or (assoc (cadr repl) alist)
8660 (error "Undefined key `%s' as contextual replacement for `%s'"
8661 (cadr repl) (car c)))))
8662 r))))))
8663 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8664 (delq
8666 (delete-dups
8667 (mapcar (lambda (x)
8668 (let ((tpl (car x)))
8669 (when (not (delq
8671 (mapcar (lambda(y)
8672 (equal y tpl)) s))) x)))
8673 (reverse r))))))
8675 (defun org-contextualize-validate-key (key contexts)
8676 "Check CONTEXTS for agenda or capture KEY."
8677 (let (r rr res)
8678 (while (setq r (pop contexts))
8679 (mapc
8680 (lambda (rr)
8681 (when
8682 (and (equal key (car r))
8683 (if (functionp rr) (funcall rr)
8684 (or (and (eq (car rr) 'in-file)
8685 (buffer-file-name)
8686 (string-match (cdr rr) (buffer-file-name)))
8687 (and (eq (car rr) 'in-mode)
8688 (string-match (cdr rr) (symbol-name major-mode)))
8689 (when (and (eq (car rr) 'not-in-file)
8690 (buffer-file-name))
8691 (not (string-match (cdr rr) (buffer-file-name))))
8692 (when (eq (car rr) 'not-in-mode)
8693 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8694 (push r res)))
8695 (car (last r))))
8696 (delete-dups (delq nil res))))
8698 (defun org-context-p (&rest contexts)
8699 "Check if local context is any of CONTEXTS.
8700 Possible values in the list of contexts are `table', `headline', and `item'."
8701 (let ((pos (point)))
8702 (goto-char (point-at-bol))
8703 (prog1 (or (and (memq 'table contexts)
8704 (looking-at "[ \t]*|"))
8705 (and (memq 'headline contexts)
8706 (looking-at org-outline-regexp))
8707 (and (memq 'item contexts)
8708 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8709 (and (memq 'item-body contexts)
8710 (org-in-item-p)))
8711 (goto-char pos))))
8713 (defun org-get-local-variables ()
8714 "Return a list of all local variables in an Org mode buffer."
8715 (let (varlist)
8716 (with-current-buffer (get-buffer-create "*Org tmp*")
8717 (erase-buffer)
8718 (org-mode)
8719 (setq varlist (buffer-local-variables)))
8720 (kill-buffer "*Org tmp*")
8721 (delq nil
8722 (mapcar
8723 (lambda (x)
8724 (setq x
8725 (if (symbolp x)
8726 (list x)
8727 (list (car x) (list 'quote (cdr x)))))
8728 (if (string-match
8729 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8730 (symbol-name (car x)))
8731 x nil))
8732 varlist))))
8734 (defun org-clone-local-variables (from-buffer &optional regexp)
8735 "Clone local variables from FROM-BUFFER.
8736 Optional argument REGEXP selects variables to clone."
8737 (mapc
8738 (lambda (pair)
8739 (and (symbolp (car pair))
8740 (or (null regexp)
8741 (string-match regexp (symbol-name (car pair))))
8742 (set (make-local-variable (car pair))
8743 (cdr pair))))
8744 (buffer-local-variables from-buffer)))
8746 ;;;###autoload
8747 (defun org-run-like-in-org-mode (cmd)
8748 "Run a command, pretending that the current buffer is in Org-mode.
8749 This will temporarily bind local variables that are typically bound in
8750 Org-mode to the values they have in Org-mode, and then interactively
8751 call CMD."
8752 (org-load-modules-maybe)
8753 (unless org-local-vars
8754 (setq org-local-vars (org-get-local-variables)))
8755 (eval (list 'let org-local-vars
8756 (list 'call-interactively (list 'quote cmd)))))
8758 ;;;; Archiving
8760 (defun org-get-category (&optional pos force-refresh)
8761 "Get the category applying to position POS."
8762 (save-match-data
8763 (if force-refresh (org-refresh-category-properties))
8764 (let ((pos (or pos (point))))
8765 (or (get-text-property pos 'org-category)
8766 (progn (org-refresh-category-properties)
8767 (get-text-property pos 'org-category))))))
8769 (defun org-refresh-category-properties ()
8770 "Refresh category text properties in the buffer."
8771 (let ((case-fold-search t)
8772 (inhibit-read-only t)
8773 (def-cat (cond
8774 ((null org-category)
8775 (if buffer-file-name
8776 (file-name-sans-extension
8777 (file-name-nondirectory buffer-file-name))
8778 "???"))
8779 ((symbolp org-category) (symbol-name org-category))
8780 (t org-category)))
8781 beg end cat pos optionp)
8782 (org-unmodified
8783 (save-excursion
8784 (save-restriction
8785 (widen)
8786 (goto-char (point-min))
8787 (put-text-property (point) (point-max) 'org-category def-cat)
8788 (while (re-search-forward
8789 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8790 (setq pos (match-end 0)
8791 optionp (equal (char-after (match-beginning 0)) ?#)
8792 cat (org-trim (match-string 2)))
8793 (if optionp
8794 (setq beg (point-at-bol) end (point-max))
8795 (org-back-to-heading t)
8796 (setq beg (point) end (org-end-of-subtree t t)))
8797 (put-text-property beg end 'org-category cat)
8798 (put-text-property beg end 'org-category-position beg)
8799 (goto-char pos)))))))
8802 ;;;; Link Stuff
8804 ;;; Link abbreviations
8806 (defun org-link-expand-abbrev (link)
8807 "Apply replacements as defined in `org-link-abbrev-alist'."
8808 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8809 (let* ((key (match-string 1 link))
8810 (as (or (assoc key org-link-abbrev-alist-local)
8811 (assoc key org-link-abbrev-alist)))
8812 (tag (and (match-end 2) (match-string 3 link)))
8813 rpl)
8814 (if (not as)
8815 link
8816 (setq rpl (cdr as))
8817 (cond
8818 ((symbolp rpl) (funcall rpl tag))
8819 ((string-match "%(\\([^)]+\\))" rpl)
8820 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8821 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8822 ((string-match "%h" rpl)
8823 (replace-match (url-hexify-string (or tag "")) t t rpl))
8824 (t (concat rpl tag)))))
8825 link))
8827 ;;; Storing and inserting links
8829 (defvar org-insert-link-history nil
8830 "Minibuffer history for links inserted with `org-insert-link'.")
8832 (defvar org-stored-links nil
8833 "Contains the links stored with `org-store-link'.")
8835 (defvar org-store-link-plist nil
8836 "Plist with info about the most recently link created with `org-store-link'.")
8838 (defvar org-link-protocols nil
8839 "Link protocols added to Org-mode using `org-add-link-type'.")
8841 (defvar org-store-link-functions nil
8842 "List of functions that are called to create and store a link.
8843 Each function will be called in turn until one returns a non-nil
8844 value. Each function should check if it is responsible for creating
8845 this link (for example by looking at the major mode).
8846 If not, it must exit and return nil.
8847 If yes, it should return a non-nil value after a calling
8848 `org-store-link-props' with a list of properties and values.
8849 Special properties are:
8851 :type The link prefix, like \"http\". This must be given.
8852 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8853 This is obligatory as well.
8854 :description Optional default description for the second pair
8855 of brackets in an Org-mode link. The user can still change
8856 this when inserting this link into an Org-mode buffer.
8858 In addition to these, any additional properties can be specified
8859 and then used in remember templates.")
8861 (defun org-add-link-type (type &optional follow export)
8862 "Add TYPE to the list of `org-link-types'.
8863 Re-compute all regular expressions depending on `org-link-types'
8865 FOLLOW and EXPORT are two functions.
8867 FOLLOW should take the link path as the single argument and do whatever
8868 is necessary to follow the link, for example find a file or display
8869 a mail message.
8871 EXPORT should format the link path for export to one of the export formats.
8872 It should be a function accepting three arguments:
8874 path the path of the link, the text after the prefix (like \"http:\")
8875 desc the description of the link, if any, or a description added by
8876 org-export-normalize-links if there is none
8877 format the export format, a symbol like `html' or `latex' or `ascii'..
8879 The function may use the FORMAT information to return different values
8880 depending on the format. The return value will be put literally into
8881 the exported file. If the return value is nil, this means Org should
8882 do what it normally does with links which do not have EXPORT defined.
8884 Org-mode has a built-in default for exporting links. If you are happy with
8885 this default, there is no need to define an export function for the link
8886 type. For a simple example of an export function, see `org-bbdb.el'."
8887 (add-to-list 'org-link-types type t)
8888 (org-make-link-regexps)
8889 (if (assoc type org-link-protocols)
8890 (setcdr (assoc type org-link-protocols) (list follow export))
8891 (push (list type follow export) org-link-protocols)))
8893 (defvar org-agenda-buffer-name)
8895 ;;;###autoload
8896 (defun org-store-link (arg)
8897 "\\<org-mode-map>Store an org-link to the current location.
8898 This link is added to `org-stored-links' and can later be inserted
8899 into an org-buffer with \\[org-insert-link].
8901 For some link types, a prefix arg is interpreted:
8902 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8903 For file links, arg negates `org-context-in-file-links'."
8904 (interactive "P")
8905 (org-load-modules-maybe)
8906 (setq org-store-link-plist nil) ; reset
8907 (org-with-limited-levels
8908 (let (link cpltxt desc description search txt custom-id agenda-link)
8909 (cond
8911 ((run-hook-with-args-until-success 'org-store-link-functions)
8912 (setq link (plist-get org-store-link-plist :link)
8913 desc (or (plist-get org-store-link-plist :description) link)))
8915 ((org-src-edit-buffer-p)
8916 (let (label gc)
8917 (while (or (not label)
8918 (save-excursion
8919 (save-restriction
8920 (widen)
8921 (goto-char (point-min))
8922 (re-search-forward
8923 (regexp-quote (format org-coderef-label-format label))
8924 nil t))))
8925 (when label (message "Label exists already") (sit-for 2))
8926 (setq label (read-string "Code line label: " label)))
8927 (end-of-line 1)
8928 (setq link (format org-coderef-label-format label))
8929 (setq gc (- 79 (length link)))
8930 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8931 (insert link)
8932 (setq link (concat "(" label ")") desc nil)))
8934 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8935 ;; We are in the agenda, link to referenced location
8936 (let ((m (or (get-text-property (point) 'org-hd-marker)
8937 (get-text-property (point) 'org-marker))))
8938 (when m
8939 (org-with-point-at m
8940 (setq agenda-link
8941 (if (org-called-interactively-p 'any)
8942 (call-interactively 'org-store-link)
8943 (org-store-link nil)))))))
8945 ((eq major-mode 'calendar-mode)
8946 (let ((cd (calendar-cursor-to-date)))
8947 (setq link
8948 (format-time-string
8949 (car org-time-stamp-formats)
8950 (apply 'encode-time
8951 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8952 nil nil nil))))
8953 (org-store-link-props :type "calendar" :date cd)))
8955 ((eq major-mode 'help-mode)
8956 (setq link (concat "help:" (save-excursion
8957 (goto-char (point-min))
8958 (looking-at "^[^ ]+")
8959 (match-string 0))))
8960 (org-store-link-props :type "help"))
8962 ((eq major-mode 'w3-mode)
8963 (setq cpltxt (if (and (buffer-name)
8964 (not (string-match "Untitled" (buffer-name))))
8965 (buffer-name)
8966 (url-view-url t))
8967 link (url-view-url t))
8968 (org-store-link-props :type "w3" :url (url-view-url t)))
8970 ((eq major-mode 'w3m-mode)
8971 (setq cpltxt (or w3m-current-title w3m-current-url)
8972 link w3m-current-url)
8973 (org-store-link-props :type "w3m" :url (url-view-url t)))
8975 ((setq search (run-hook-with-args-until-success
8976 'org-create-file-search-functions))
8977 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8978 "::" search))
8979 (setq cpltxt (or description link)))
8981 ((eq major-mode 'image-mode)
8982 (setq cpltxt (concat "file:"
8983 (abbreviate-file-name buffer-file-name))
8984 link cpltxt)
8985 (org-store-link-props :type "image" :file buffer-file-name))
8987 ((eq major-mode 'dired-mode)
8988 ;; link to the file in the current line
8989 (let ((file (dired-get-filename nil t)))
8990 (setq file (if file
8991 (abbreviate-file-name
8992 (expand-file-name (dired-get-filename nil t)))
8993 ;; otherwise, no file so use current directory.
8994 default-directory))
8995 (setq cpltxt (concat "file:" file)
8996 link cpltxt)))
8998 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8999 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9000 (cond
9001 ((org-in-regexp "<<\\(.*?\\)>>")
9002 (setq cpltxt
9003 (concat "file:"
9004 (abbreviate-file-name
9005 (buffer-file-name (buffer-base-buffer)))
9006 "::" (match-string 1))
9007 link cpltxt))
9008 ((and (featurep 'org-id)
9009 (or (eq org-link-to-org-use-id t)
9010 (and (org-called-interactively-p 'any)
9011 (or (eq org-link-to-org-use-id 'create-if-interactive)
9012 (and (eq org-link-to-org-use-id
9013 'create-if-interactive-and-no-custom-id)
9014 (not custom-id))))
9015 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9016 ;; We can make a link using the ID.
9017 (setq link (condition-case nil
9018 (prog1 (org-id-store-link)
9019 (setq desc (plist-get org-store-link-plist :description)))
9020 (error
9021 ;; probably before first headline, link to file only
9022 (concat "file:"
9023 (abbreviate-file-name
9024 (buffer-file-name (buffer-base-buffer))))))))
9026 ;; Just link to current headline
9027 (setq cpltxt (concat "file:"
9028 (abbreviate-file-name
9029 (buffer-file-name (buffer-base-buffer)))))
9030 ;; Add a context search string
9031 (when (org-xor org-context-in-file-links arg)
9032 (setq txt (cond
9033 ((org-at-heading-p) nil)
9034 ((org-region-active-p)
9035 (buffer-substring (region-beginning) (region-end)))))
9036 (when (or (null txt) (string-match "\\S-" txt))
9037 (setq cpltxt
9038 (concat cpltxt "::"
9039 (condition-case nil
9040 (org-make-org-heading-search-string txt)
9041 (error "")))
9042 desc (or (nth 4 (ignore-errors
9043 (org-heading-components))) "NONE"))))
9044 (if (string-match "::\\'" cpltxt)
9045 (setq cpltxt (substring cpltxt 0 -2)))
9046 (setq link cpltxt))))
9048 ((buffer-file-name (buffer-base-buffer))
9049 ;; Just link to this file here.
9050 (setq cpltxt (concat "file:"
9051 (abbreviate-file-name
9052 (buffer-file-name (buffer-base-buffer)))))
9053 ;; Add a context string
9054 (when (org-xor org-context-in-file-links arg)
9055 (setq txt (if (org-region-active-p)
9056 (buffer-substring (region-beginning) (region-end))
9057 (buffer-substring (point-at-bol) (point-at-eol))))
9058 ;; Only use search option if there is some text.
9059 (when (string-match "\\S-" txt)
9060 (setq cpltxt
9061 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9062 desc "NONE")))
9063 (setq link cpltxt))
9065 ((org-called-interactively-p 'interactive)
9066 (error "Cannot link to a buffer which is not visiting a file"))
9068 (t (setq link nil)))
9070 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9071 (setq link (or link cpltxt)
9072 desc (or desc cpltxt))
9073 (if (equal desc "NONE") (setq desc nil))
9075 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9076 (progn
9077 (setq org-stored-links
9078 (cons (list link desc) org-stored-links))
9079 (message "Stored: %s" (or desc link))
9080 (when custom-id
9081 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9082 "::#" custom-id))
9083 (setq org-stored-links
9084 (cons (list link desc) org-stored-links))))
9085 (or agenda-link (and link (org-make-link-string link desc)))))))
9087 (defun org-store-link-props (&rest plist)
9088 "Store link properties, extract names and addresses."
9089 (let (x adr)
9090 (when (setq x (plist-get plist :from))
9091 (setq adr (mail-extract-address-components x))
9092 (setq plist (plist-put plist :fromname (car adr)))
9093 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9094 (when (setq x (plist-get plist :to))
9095 (setq adr (mail-extract-address-components x))
9096 (setq plist (plist-put plist :toname (car adr)))
9097 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9098 (let ((from (plist-get plist :from))
9099 (to (plist-get plist :to)))
9100 (when (and from to org-from-is-user-regexp)
9101 (setq plist
9102 (plist-put plist :fromto
9103 (if (string-match org-from-is-user-regexp from)
9104 (concat "to %t")
9105 (concat "from %f"))))))
9106 (setq org-store-link-plist plist))
9108 (defun org-add-link-props (&rest plist)
9109 "Add these properties to the link property list."
9110 (let (key value)
9111 (while plist
9112 (setq key (pop plist) value (pop plist))
9113 (setq org-store-link-plist
9114 (plist-put org-store-link-plist key value)))))
9116 (defun org-email-link-description (&optional fmt)
9117 "Return the description part of an email link.
9118 This takes information from `org-store-link-plist' and formats it
9119 according to FMT (default from `org-email-link-description-format')."
9120 (setq fmt (or fmt org-email-link-description-format))
9121 (let* ((p org-store-link-plist)
9122 (to (plist-get p :toaddress))
9123 (from (plist-get p :fromaddress))
9124 (table
9125 (list
9126 (cons "%c" (plist-get p :fromto))
9127 (cons "%F" (plist-get p :from))
9128 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9129 (cons "%T" (plist-get p :to))
9130 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9131 (cons "%s" (plist-get p :subject))
9132 (cons "%d" (plist-get p :date))
9133 (cons "%m" (plist-get p :message-id)))))
9134 (when (string-match "%c" fmt)
9135 ;; Check if the user wrote this message
9136 (if (and org-from-is-user-regexp from to
9137 (save-match-data (string-match org-from-is-user-regexp from)))
9138 (setq fmt (replace-match "to %t" t t fmt))
9139 (setq fmt (replace-match "from %f" t t fmt))))
9140 (org-replace-escapes fmt table)))
9142 (defun org-make-org-heading-search-string (&optional string heading)
9143 "Make search string for STRING or current headline."
9144 (interactive)
9145 (let ((s (or string (org-get-heading)))
9146 (lines org-context-in-file-links))
9147 (unless (and string (not heading))
9148 ;; We are using a headline, clean up garbage in there.
9149 (if (string-match org-todo-regexp s)
9150 (setq s (replace-match "" t t s)))
9151 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9152 (setq s (replace-match "" t t s)))
9153 (setq s (org-trim s))
9154 (if (string-match (concat "^\\(" org-quote-string "\\|"
9155 org-comment-string "\\)") s)
9156 (setq s (replace-match "" t t s)))
9157 (while (string-match org-ts-regexp s)
9158 (setq s (replace-match "" t t s))))
9159 (or string (setq s (concat "*" s))) ; Add * for headlines
9160 (when (and string (integerp lines) (> lines 0))
9161 (let ((slines (org-split-string s "\n")))
9162 (when (< lines (length slines))
9163 (setq s (mapconcat
9164 'identity
9165 (reverse (nthcdr (- (length slines) lines)
9166 (reverse slines))) "\n")))))
9167 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9169 (defun org-make-link-string (link &optional description)
9170 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9171 (unless (string-match "\\S-" link)
9172 (error "Empty link"))
9173 (when (and description
9174 (stringp description)
9175 (not (string-match "\\S-" description)))
9176 (setq description nil))
9177 (when (stringp description)
9178 ;; Remove brackets from the description, they are fatal.
9179 (while (string-match "\\[" description)
9180 (setq description (replace-match "{" t t description)))
9181 (while (string-match "\\]" description)
9182 (setq description (replace-match "}" t t description))))
9183 (when (equal link description)
9184 ;; No description needed, it is identical
9185 (setq description nil))
9186 (when (and (not description)
9187 (not (string-match (org-image-file-name-regexp) link))
9188 (not (equal link (org-link-escape link))))
9189 (setq description (org-extract-attributes link)))
9190 (setq link
9191 (cond ((string-match (org-image-file-name-regexp) link) link)
9192 ((string-match org-link-types-re link)
9193 (concat (match-string 1 link)
9194 (org-link-escape (substring link (match-end 1)))))
9195 (t (org-link-escape link))))
9196 (concat "[[" link "]"
9197 (if description (concat "[" description "]") "")
9198 "]"))
9200 (defconst org-link-escape-chars
9201 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9202 "List of characters that should be escaped in link.
9203 This is the list that is used for internal purposes.")
9205 (defconst org-link-escape-chars-browser
9206 '(?\ )
9207 "List of escapes for characters that are problematic in links.
9208 This is the list that is used before handing over to the browser.")
9210 (defun org-link-escape (text &optional table merge)
9211 "Return percent escaped representation of TEXT.
9212 TEXT is a string with the text to escape.
9213 Optional argument TABLE is a list with characters that should be
9214 escaped. When nil, `org-link-escape-chars' is used.
9215 If optional argument MERGE is set, merge TABLE into
9216 `org-link-escape-chars'."
9217 (cond
9218 ((and table merge)
9219 (mapc (lambda (defchr)
9220 (unless (member defchr table)
9221 (setq table (cons defchr table)))) org-link-escape-chars))
9222 ((null table)
9223 (setq table org-link-escape-chars)))
9224 (mapconcat
9225 (lambda (char)
9226 (if (or (member char table)
9227 (and (or (< char 32) (= char 37) (> char 126))
9228 org-url-hexify-p))
9229 (mapconcat (lambda (sequence-element)
9230 (format "%%%.2X" sequence-element))
9231 (or (encode-coding-char char 'utf-8)
9232 (error "Unable to percent escape character: %s"
9233 (char-to-string char))) "")
9234 (char-to-string char))) text ""))
9236 (defun org-link-unescape (str)
9237 "Unhex hexified Unicode strings as returned from the JavaScript function
9238 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9239 (unless (and (null str) (string= "" str))
9240 (let ((pos 0) (case-fold-search t) unhexed)
9241 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9242 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9243 (setq str (replace-match unhexed t t str))
9244 (setq pos (+ pos (length unhexed))))))
9245 str)
9247 (defun org-link-unescape-compound (hex)
9248 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9249 Note: this function also decodes single byte encodings like
9250 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9251 (save-match-data
9252 (let* ((bytes (cdr (split-string hex "%")))
9253 (ret "")
9254 (eat 0)
9255 (sum 0))
9256 (while bytes
9257 (let* ((val (string-to-number (pop bytes) 16))
9258 (shift-xor
9259 (if (= 0 eat)
9260 (cond
9261 ((>= val 252) (cons 6 252))
9262 ((>= val 248) (cons 5 248))
9263 ((>= val 240) (cons 4 240))
9264 ((>= val 224) (cons 3 224))
9265 ((>= val 192) (cons 2 192))
9266 (t (cons 0 0)))
9267 (cons 6 128))))
9268 (if (>= val 192) (setq eat (car shift-xor)))
9269 (setq val (logxor val (cdr shift-xor)))
9270 (setq sum (+ (lsh sum (car shift-xor)) val))
9271 (if (> eat 0) (setq eat (- eat 1)))
9272 (cond
9273 ((= 0 eat) ;multi byte
9274 (setq ret (concat ret (org-char-to-string sum)))
9275 (setq sum 0))
9276 ((not bytes) ; single byte(s)
9277 (setq ret (org-link-unescape-single-byte-sequence hex))))
9278 )) ;; end (while bytes
9279 ret )))
9281 (defun org-link-unescape-single-byte-sequence (hex)
9282 "Unhexify hex-encoded single byte character sequences."
9283 (mapconcat (lambda (byte)
9284 (char-to-string (string-to-number byte 16)))
9285 (cdr (split-string hex "%")) ""))
9287 (defun org-xor (a b)
9288 "Exclusive or."
9289 (if a (not b) b))
9291 (defun org-fixup-message-id-for-http (s)
9292 "Replace special characters in a message id, so it can be used in an http query."
9293 (when (string-match "%" s)
9294 (setq s (mapconcat (lambda (c)
9295 (if (eq c ?%)
9296 "%25"
9297 (char-to-string c)))
9298 s "")))
9299 (while (string-match "<" s)
9300 (setq s (replace-match "%3C" t t s)))
9301 (while (string-match ">" s)
9302 (setq s (replace-match "%3E" t t s)))
9303 (while (string-match "@" s)
9304 (setq s (replace-match "%40" t t s)))
9307 (defun org-link-prettify (link)
9308 "Return a human-readable representation of LINK.
9309 The car of LINK must be a raw link the cdr of LINK must be either
9310 a link description or nil."
9311 (let ((desc (or (cadr link) "<no description>")))
9312 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9313 "<" (car link) ">")))
9315 ;;;###autoload
9316 (defun org-insert-link-global ()
9317 "Insert a link like Org-mode does.
9318 This command can be called in any mode to insert a link in Org-mode syntax."
9319 (interactive)
9320 (org-load-modules-maybe)
9321 (org-run-like-in-org-mode 'org-insert-link))
9323 (defun org-insert-all-links (&optional keep)
9324 "Insert all links in `org-stored-links'."
9325 (interactive "P")
9326 (let ((links (copy-sequence org-stored-links)) l)
9327 (while (setq l (if keep (pop links) (pop org-stored-links)))
9328 (insert "- ")
9329 (org-insert-link nil (car l) (cadr l))
9330 (insert "\n"))))
9332 (defun org-link-fontify-links-to-this-file ()
9333 "Fontify links to the current file in `org-stored-links'."
9334 (let ((f (buffer-file-name)) a b)
9335 (setq a (mapcar (lambda(l)
9336 (let ((ll (car l)))
9337 (when (and (string-match "^file:\\(.+\\)::" ll)
9338 (equal f (expand-file-name (match-string 1 ll))))
9339 ll)))
9340 org-stored-links))
9341 (when (featurep 'org-id)
9342 (setq b (mapcar (lambda(l)
9343 (let ((ll (car l)))
9344 (when (and (string-match "^id:\\(.+\\)$" ll)
9345 (equal f (expand-file-name
9346 (or (org-id-find-id-file
9347 (match-string 1 ll)) ""))))
9348 ll)))
9349 org-stored-links)))
9350 (mapcar (lambda(l)
9351 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9352 (delq nil (append a b)))))
9354 (defvar org-link-links-in-this-file nil)
9355 (defun org-insert-link (&optional complete-file link-location default-description)
9356 "Insert a link. At the prompt, enter the link.
9358 Completion can be used to insert any of the link protocol prefixes like
9359 http or ftp in use.
9361 The history can be used to select a link previously stored with
9362 `org-store-link'. When the empty string is entered (i.e. if you just
9363 press RET at the prompt), the link defaults to the most recently
9364 stored link. As SPC triggers completion in the minibuffer, you need to
9365 use M-SPC or C-q SPC to force the insertion of a space character.
9367 You will also be prompted for a description, and if one is given, it will
9368 be displayed in the buffer instead of the link.
9370 If there is already a link at point, this command will allow you to edit link
9371 and description parts.
9373 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9374 be selected using completion. The path to the file will be relative to the
9375 current directory if the file is in the current directory or a subdirectory.
9376 Otherwise, the link will be the absolute path as completed in the minibuffer
9377 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9378 option `org-link-file-path-type'.
9380 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9381 the current directory or below.
9383 With three \\[universal-argument] prefixes, negate the meaning of
9384 `org-keep-stored-link-after-insertion'.
9386 If `org-make-link-description-function' is non-nil, this function will be
9387 called with the link target, and the result will be the default
9388 link description.
9390 If the LINK-LOCATION parameter is non-nil, this value will be
9391 used as the link location instead of reading one interactively.
9393 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9394 be used as the default description."
9395 (interactive "P")
9396 (let* ((wcf (current-window-configuration))
9397 (region (if (org-region-active-p)
9398 (buffer-substring (region-beginning) (region-end))))
9399 (remove (and region (list (region-beginning) (region-end))))
9400 (desc region)
9401 tmphist ; byte-compile incorrectly complains about this
9402 (link link-location)
9403 (abbrevs org-link-abbrev-alist-local)
9404 entry file all-prefixes auto-desc)
9405 (cond
9406 (link-location) ; specified by arg, just use it.
9407 ((org-in-regexp org-bracket-link-regexp 1)
9408 ;; We do have a link at point, and we are going to edit it.
9409 (setq remove (list (match-beginning 0) (match-end 0)))
9410 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9411 (setq link (read-string "Link: "
9412 (org-link-unescape
9413 (org-match-string-no-properties 1)))))
9414 ((or (org-in-regexp org-angle-link-re)
9415 (org-in-regexp org-plain-link-re))
9416 ;; Convert to bracket link
9417 (setq remove (list (match-beginning 0) (match-end 0))
9418 link (read-string "Link: "
9419 (org-remove-angle-brackets (match-string 0)))))
9420 ((member complete-file '((4) (16)))
9421 ;; Completing read for file names.
9422 (setq link (org-file-complete-link complete-file)))
9424 ;; Read link, with completion for stored links.
9425 (org-link-fontify-links-to-this-file)
9426 (org-switch-to-buffer-other-window "*Org Links*")
9427 (with-current-buffer "*Org Links*"
9428 (erase-buffer)
9429 (insert "Insert a link.
9430 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9431 (when org-stored-links
9432 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9433 (insert (mapconcat 'org-link-prettify
9434 (reverse org-stored-links) "\n")))
9435 (goto-char (point-min)))
9436 (let ((cw (selected-window)))
9437 (select-window (get-buffer-window "*Org Links*" 'visible))
9438 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9439 (unless (pos-visible-in-window-p (point-max))
9440 (org-fit-window-to-buffer))
9441 (and (window-live-p cw) (select-window cw)))
9442 ;; Fake a link history, containing the stored links.
9443 (setq tmphist (append (mapcar 'car org-stored-links)
9444 org-insert-link-history))
9445 (setq all-prefixes (append (mapcar 'car abbrevs)
9446 (mapcar 'car org-link-abbrev-alist)
9447 org-link-types))
9448 (unwind-protect
9449 (progn
9450 (setq link
9451 (let ((org-completion-use-ido nil)
9452 (org-completion-use-iswitchb nil))
9453 (org-completing-read
9454 "Link: "
9455 (append
9456 (mapcar (lambda (x) (list (concat x ":")))
9457 all-prefixes)
9458 (mapcar 'car org-stored-links)
9459 (mapcar 'cadr org-stored-links))
9460 nil nil nil
9461 'tmphist
9462 (caar org-stored-links))))
9463 (if (not (string-match "\\S-" link))
9464 (error "No link selected"))
9465 (mapc (lambda(l)
9466 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9467 org-stored-links)
9468 (if (or (member link all-prefixes)
9469 (and (equal ":" (substring link -1))
9470 (member (substring link 0 -1) all-prefixes)
9471 (setq link (substring link 0 -1))))
9472 (setq link (org-link-try-special-completion link))))
9473 (set-window-configuration wcf)
9474 (kill-buffer "*Org Links*"))
9475 (setq entry (assoc link org-stored-links))
9476 (or entry (push link org-insert-link-history))
9477 (setq desc (or desc (nth 1 entry)))))
9479 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9480 (not org-keep-stored-link-after-insertion))
9481 (setq org-stored-links (delq (assoc link org-stored-links)
9482 org-stored-links)))
9484 (if (string-match org-plain-link-re link)
9485 ;; URL-like link, normalize the use of angular brackets.
9486 (setq link (org-remove-angle-brackets link)))
9488 ;; Check if we are linking to the current file with a search option
9489 ;; If yes, simplify the link by using only the search option.
9490 (when (and buffer-file-name
9491 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9492 (let* ((path (match-string 1 link))
9493 (case-fold-search nil)
9494 (search (match-string 2 link)))
9495 (save-match-data
9496 (if (equal (file-truename buffer-file-name) (file-truename path))
9497 ;; We are linking to this same file, with a search option
9498 (setq link search)))))
9500 ;; Check if we can/should use a relative path. If yes, simplify the link
9501 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9502 (let* ((type (match-string 1 link))
9503 (path (match-string 2 link))
9504 (origpath path)
9505 (case-fold-search nil))
9506 (cond
9507 ((or (eq org-link-file-path-type 'absolute)
9508 (equal complete-file '(16)))
9509 (setq path (abbreviate-file-name (expand-file-name path))))
9510 ((eq org-link-file-path-type 'noabbrev)
9511 (setq path (expand-file-name path)))
9512 ((eq org-link-file-path-type 'relative)
9513 (setq path (file-relative-name path)))
9515 (save-match-data
9516 (if (string-match (concat "^" (regexp-quote
9517 (expand-file-name
9518 (file-name-as-directory
9519 default-directory))))
9520 (expand-file-name path))
9521 ;; We are linking a file with relative path name.
9522 (setq path (substring (expand-file-name path)
9523 (match-end 0)))
9524 (setq path (abbreviate-file-name (expand-file-name path)))))))
9525 (setq link (concat type path))
9526 (if (equal desc origpath)
9527 (setq desc path))))
9529 (if org-make-link-description-function
9530 (setq desc (funcall org-make-link-description-function link desc))
9531 (if default-description (setq desc default-description)
9532 (setq desc (or (and auto-desc desc)
9533 (read-string "Description: " desc)))))
9535 (unless (string-match "\\S-" desc) (setq desc nil))
9536 (if remove (apply 'delete-region remove))
9537 (insert (org-make-link-string link desc))))
9539 (defun org-link-try-special-completion (type)
9540 "If there is completion support for link type TYPE, offer it."
9541 (let ((fun (intern (concat "org-" type "-complete-link"))))
9542 (if (functionp fun)
9543 (funcall fun)
9544 (read-string "Link (no completion support): " (concat type ":")))))
9546 (defun org-file-complete-link (&optional arg)
9547 "Create a file link using completion."
9548 (let (file link)
9549 (setq file (read-file-name "File: "))
9550 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9551 (pwd1 (file-name-as-directory (abbreviate-file-name
9552 (expand-file-name ".")))))
9553 (cond
9554 ((equal arg '(16))
9555 (setq link (concat
9556 "file:"
9557 (abbreviate-file-name (expand-file-name file)))))
9558 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9559 (setq link (concat "file:" (match-string 1 file))))
9560 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9561 (expand-file-name file))
9562 (setq link (concat
9563 "file:" (match-string 1 (expand-file-name file)))))
9564 (t (setq link (concat "file:" file)))))
9565 link))
9567 (defun org-completing-read (&rest args)
9568 "Completing-read with SPACE being a normal character."
9569 (let ((enable-recursive-minibuffers t)
9570 (minibuffer-local-completion-map
9571 (copy-keymap minibuffer-local-completion-map)))
9572 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9573 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9574 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9575 (apply 'org-icompleting-read args)))
9577 (defun org-completing-read-no-i (&rest args)
9578 (let (org-completion-use-ido org-completion-use-iswitchb)
9579 (apply 'org-completing-read args)))
9581 (defun org-iswitchb-completing-read (prompt choices &rest args)
9582 "Use iswitch as a completing-read replacement to choose from choices.
9583 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9584 from."
9585 (let* ((iswitchb-use-virtual-buffers nil)
9586 (iswitchb-make-buflist-hook
9587 (lambda ()
9588 (setq iswitchb-temp-buflist choices))))
9589 (iswitchb-read-buffer prompt)))
9591 (defun org-icompleting-read (&rest args)
9592 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9593 (org-without-partial-completion
9594 (if (and org-completion-use-ido
9595 (fboundp 'ido-completing-read)
9596 (boundp 'ido-mode) ido-mode
9597 (listp (second args)))
9598 (let ((ido-enter-matching-directory nil))
9599 (apply 'ido-completing-read (concat (car args))
9600 (if (consp (car (nth 1 args)))
9601 (mapcar 'car (nth 1 args))
9602 (nth 1 args))
9603 (cddr args)))
9604 (if (and org-completion-use-iswitchb
9605 (boundp 'iswitchb-mode) iswitchb-mode
9606 (listp (second args)))
9607 (apply 'org-iswitchb-completing-read (concat (car args))
9608 (if (consp (car (nth 1 args)))
9609 (mapcar 'car (nth 1 args))
9610 (nth 1 args))
9611 (cddr args))
9612 (apply 'completing-read args)))))
9614 (defun org-extract-attributes (s)
9615 "Extract the attributes cookie from a string and set as text property."
9616 (let (a attr (start 0) key value)
9617 (save-match-data
9618 (when (string-match "{{\\([^}]+\\)}}$" s)
9619 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9620 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9621 (setq key (match-string 1 a) value (match-string 2 a)
9622 start (match-end 0)
9623 attr (plist-put attr (intern key) value))))
9624 (org-add-props s nil 'org-attr attr))
9627 (defun org-extract-attributes-from-string (tag)
9628 (let (key value attr)
9629 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9630 (setq key (match-string 1 tag) value (match-string 2 tag)
9631 tag (replace-match "" t t tag)
9632 attr (plist-put attr (intern key) value)))
9633 (cons tag attr)))
9635 (defun org-attributes-to-string (plist)
9636 "Format a property list into an HTML attribute list."
9637 (let ((s "") key value)
9638 (while plist
9639 (setq key (pop plist) value (pop plist))
9640 (and value
9641 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9644 ;;; Opening/following a link
9646 (defvar org-link-search-failed nil)
9648 (defvar org-open-link-functions nil
9649 "Hook for functions finding a plain text link.
9650 These functions must take a single argument, the link content.
9651 They will be called for links that look like [[link text][description]]
9652 when LINK TEXT does not have a protocol like \"http:\" and does not look
9653 like a filename (e.g. \"./blue.png\").
9655 These functions will be called *before* Org attempts to resolve the
9656 link by doing text searches in the current buffer - so if you want a
9657 link \"[[target]]\" to still find \"<<target>>\", your function should
9658 handle this as a special case.
9660 When the function does handle the link, it must return a non-nil value.
9661 If it decides that it is not responsible for this link, it must return
9662 nil to indicate that that Org-mode can continue with other options
9663 like exact and fuzzy text search.")
9665 (defun org-next-link ()
9666 "Move forward to the next link.
9667 If the link is in hidden text, expose it."
9668 (interactive)
9669 (when (and org-link-search-failed (eq this-command last-command))
9670 (goto-char (point-min))
9671 (message "Link search wrapped back to beginning of buffer"))
9672 (setq org-link-search-failed nil)
9673 (let* ((pos (point))
9674 (ct (org-context))
9675 (a (assoc :link ct)))
9676 (if a (goto-char (nth 2 a)))
9677 (if (re-search-forward org-any-link-re nil t)
9678 (progn
9679 (goto-char (match-beginning 0))
9680 (if (outline-invisible-p) (org-show-context)))
9681 (goto-char pos)
9682 (setq org-link-search-failed t)
9683 (error "No further link found"))))
9685 (defun org-previous-link ()
9686 "Move backward to the previous link.
9687 If the link is in hidden text, expose it."
9688 (interactive)
9689 (when (and org-link-search-failed (eq this-command last-command))
9690 (goto-char (point-max))
9691 (message "Link search wrapped back to end of buffer"))
9692 (setq org-link-search-failed nil)
9693 (let* ((pos (point))
9694 (ct (org-context))
9695 (a (assoc :link ct)))
9696 (if a (goto-char (nth 1 a)))
9697 (if (re-search-backward org-any-link-re nil t)
9698 (progn
9699 (goto-char (match-beginning 0))
9700 (if (outline-invisible-p) (org-show-context)))
9701 (goto-char pos)
9702 (setq org-link-search-failed t)
9703 (error "No further link found"))))
9705 (defun org-translate-link (s)
9706 "Translate a link string if a translation function has been defined."
9707 (if (and org-link-translation-function
9708 (fboundp org-link-translation-function)
9709 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9710 (progn
9711 (setq s (funcall org-link-translation-function
9712 (match-string 1 s) (match-string 2 s)))
9713 (concat (car s) ":" (cdr s)))
9716 (defun org-translate-link-from-planner (type path)
9717 "Translate a link from Emacs Planner syntax so that Org can follow it.
9718 This is still an experimental function, your mileage may vary."
9719 (cond
9720 ((member type '("http" "https" "news" "ftp"))
9721 ;; standard Internet links are the same.
9722 nil)
9723 ((and (equal type "irc") (string-match "^//" path))
9724 ;; Planner has two / at the beginning of an irc link, we have 1.
9725 ;; We should have zero, actually....
9726 (setq path (substring path 1)))
9727 ((and (equal type "lisp") (string-match "^/" path))
9728 ;; Planner has a slash, we do not.
9729 (setq type "elisp" path (substring path 1)))
9730 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9731 ;; A typical message link. Planner has the id after the final slash,
9732 ;; we separate it with a hash mark
9733 (setq path (concat (match-string 1 path) "#"
9734 (org-remove-angle-brackets (match-string 2 path)))))
9736 (cons type path))
9738 (defun org-find-file-at-mouse (ev)
9739 "Open file link or URL at mouse."
9740 (interactive "e")
9741 (mouse-set-point ev)
9742 (org-open-at-point 'in-emacs))
9744 (defun org-open-at-mouse (ev)
9745 "Open file link or URL at mouse.
9746 See the docstring of `org-open-file' for details."
9747 (interactive "e")
9748 (mouse-set-point ev)
9749 (if (eq major-mode 'org-agenda-mode)
9750 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9751 (org-open-at-point))
9753 (defvar org-window-config-before-follow-link nil
9754 "The window configuration before following a link.
9755 This is saved in case the need arises to restore it.")
9757 (defvar org-open-link-marker (make-marker)
9758 "Marker pointing to the location where `org-open-at-point; was called.")
9760 ;;;###autoload
9761 (defun org-open-at-point-global ()
9762 "Follow a link like Org-mode does.
9763 This command can be called in any mode to follow a link that has
9764 Org-mode syntax."
9765 (interactive)
9766 (org-run-like-in-org-mode 'org-open-at-point))
9768 ;;;###autoload
9769 (defun org-open-link-from-string (s &optional arg reference-buffer)
9770 "Open a link in the string S, as if it was in Org-mode."
9771 (interactive "sLink: \nP")
9772 (let ((reference-buffer (or reference-buffer (current-buffer))))
9773 (with-temp-buffer
9774 (let ((org-inhibit-startup (not reference-buffer)))
9775 (org-mode)
9776 (insert s)
9777 (goto-char (point-min))
9778 (when reference-buffer
9779 (setq org-link-abbrev-alist-local
9780 (with-current-buffer reference-buffer
9781 org-link-abbrev-alist-local)))
9782 (org-open-at-point arg reference-buffer)))))
9784 (defvar org-open-at-point-functions nil
9785 "Hook that is run when following a link at point.
9787 Functions in this hook must return t if they identify and follow
9788 a link at point. If they don't find anything interesting at point,
9789 they must return nil.")
9791 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9792 (defun org-open-at-point (&optional arg reference-buffer)
9793 "Open link at or after point.
9794 If there is no link at point, this function will search forward up to
9795 the end of the current line.
9796 Normally, files will be opened by an appropriate application. If the
9797 optional prefix argument ARG is non-nil, Emacs will visit the file.
9798 With a double prefix argument, try to open outside of Emacs, in the
9799 application the system uses for this file type."
9800 (interactive "P")
9801 ;; if in a code block, then open the block's results
9802 (unless (call-interactively #'org-babel-open-src-block-result)
9803 (org-load-modules-maybe)
9804 (move-marker org-open-link-marker (point))
9805 (setq org-window-config-before-follow-link (current-window-configuration))
9806 (org-remove-occur-highlights nil nil t)
9807 (cond
9808 ((and (org-at-heading-p)
9809 (not (org-at-timestamp-p t))
9810 (not (org-in-regexp
9811 (concat org-plain-link-re "\\|"
9812 org-bracket-link-regexp "\\|"
9813 org-angle-link-re "\\|"
9814 "[ \t]:[^ \t\n]+:[ \t]*$")))
9815 (not (get-text-property (point) 'org-linked-text)))
9816 (or (org-offer-links-in-entry arg)
9817 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9818 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9819 ((org-at-timestamp-p t) (org-follow-timestamp-link))
9820 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9821 (not (org-in-regexp org-bracket-link-regexp)))
9822 (org-footnote-action))
9824 (let (type path link line search (pos (point)))
9825 (catch 'match
9826 (save-excursion
9827 (skip-chars-forward "^]\n\r")
9828 (when (org-in-regexp org-bracket-link-regexp 1)
9829 (setq link (org-extract-attributes
9830 (org-link-unescape (org-match-string-no-properties 1))))
9831 (while (string-match " *\n *" link)
9832 (setq link (replace-match " " t t link)))
9833 (setq link (org-link-expand-abbrev link))
9834 (cond
9835 ((or (file-name-absolute-p link)
9836 (string-match "^\\.\\.?/" link))
9837 (setq type "file" path link))
9838 ((string-match org-link-re-with-space3 link)
9839 (setq type (match-string 1 link) path (match-string 2 link)))
9840 ((string-match "^help:+\\(.+\\)" link)
9841 (setq type "help" path (match-string 1 link)))
9842 (t (setq type "thisfile" path link)))
9843 (throw 'match t)))
9845 (when (get-text-property (point) 'org-linked-text)
9846 (setq type "thisfile"
9847 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9848 (1+ (point)) (point))
9849 path (buffer-substring
9850 (or (previous-single-property-change pos 'org-linked-text)
9851 (point-min))
9852 (or (next-single-property-change pos 'org-linked-text)
9853 (point-max))))
9854 (throw 'match t))
9856 (save-excursion
9857 (when (or (org-in-regexp org-angle-link-re)
9858 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9859 (save-match-data (not (looking-back "\\[\\[")))))
9860 (setq type (match-string 1)
9861 path (org-link-unescape (match-string 2)))
9862 (throw 'match t)))
9863 (save-excursion
9864 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9865 (setq type "tags"
9866 path (match-string 1))
9867 (while (string-match ":" path)
9868 (setq path (replace-match "+" t t path)))
9869 (throw 'match t)))
9870 (when (org-in-regexp "<\\([^><\n]+\\)>")
9871 (setq type "tree-match"
9872 path (match-string 1))
9873 (throw 'match t)))
9874 (unless path
9875 (error "No link found"))
9877 ;; switch back to reference buffer
9878 ;; needed when if called in a temporary buffer through
9879 ;; org-open-link-from-string
9880 (with-current-buffer (or reference-buffer (current-buffer))
9882 ;; Remove any trailing spaces in path
9883 (if (string-match " +\\'" path)
9884 (setq path (replace-match "" t t path)))
9885 (if (and org-link-translation-function
9886 (fboundp org-link-translation-function))
9887 ;; Check if we need to translate the link
9888 (let ((tmp (funcall org-link-translation-function type path)))
9889 (setq type (car tmp) path (cdr tmp))))
9891 (cond
9893 ((assoc type org-link-protocols)
9894 (funcall (nth 1 (assoc type org-link-protocols)) path))
9896 ((equal type "help")
9897 (let ((f-or-v (intern path)))
9898 (cond ((fboundp f-or-v)
9899 (describe-function f-or-v))
9900 ((boundp f-or-v)
9901 (describe-variable f-or-v))
9902 (t (error "Not a known function or variable")))))
9904 ((equal type "mailto")
9905 (let ((cmd (car org-link-mailto-program))
9906 (args (cdr org-link-mailto-program)) args1
9907 (address path) (subject "") a)
9908 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9909 (setq address (match-string 1 path)
9910 subject (org-link-escape (match-string 2 path))))
9911 (while args
9912 (cond
9913 ((not (stringp (car args))) (push (pop args) args1))
9914 (t (setq a (pop args))
9915 (if (string-match "%a" a)
9916 (setq a (replace-match address t t a)))
9917 (if (string-match "%s" a)
9918 (setq a (replace-match subject t t a)))
9919 (push a args1))))
9920 (apply cmd (nreverse args1))))
9922 ((member type '("http" "https" "ftp" "news"))
9923 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9924 (org-link-escape
9925 path org-link-escape-chars-browser)
9926 path))))
9928 ((string= type "doi")
9929 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9930 (org-link-escape
9931 path org-link-escape-chars-browser)
9932 path))))
9934 ((member type '("message"))
9935 (browse-url (concat type ":" path)))
9937 ((string= type "tags")
9938 (org-tags-view arg path))
9940 ((string= type "tree-match")
9941 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9943 ((string= type "file")
9944 (if (string-match "::\\([0-9]+\\)\\'" path)
9945 (setq line (string-to-number (match-string 1 path))
9946 path (substring path 0 (match-beginning 0)))
9947 (if (string-match "::\\(.+\\)\\'" path)
9948 (setq search (match-string 1 path)
9949 path (substring path 0 (match-beginning 0)))))
9950 (if (string-match "[*?{]" (file-name-nondirectory path))
9951 (dired path)
9952 (org-open-file path arg line search)))
9954 ((string= type "shell")
9955 (let ((buf (generate-new-buffer "*Org Shell Output"))
9956 (cmd path))
9957 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9958 (string-match org-confirm-shell-link-not-regexp cmd))
9959 (not org-confirm-shell-link-function)
9960 (funcall org-confirm-shell-link-function
9961 (format "Execute \"%s\" in shell? "
9962 (org-add-props cmd nil
9963 'face 'org-warning))))
9964 (progn
9965 (message "Executing %s" cmd)
9966 (shell-command cmd buf)
9967 (if (featurep 'midnight)
9968 (setq clean-buffer-list-kill-buffer-names
9969 (cons buf clean-buffer-list-kill-buffer-names))))
9970 (error "Abort"))))
9972 ((string= type "elisp")
9973 (let ((cmd path))
9974 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9975 (string-match org-confirm-elisp-link-not-regexp cmd))
9976 (not org-confirm-elisp-link-function)
9977 (funcall org-confirm-elisp-link-function
9978 (format "Execute \"%s\" as elisp? "
9979 (org-add-props cmd nil
9980 'face 'org-warning))))
9981 (message "%s => %s" cmd
9982 (if (equal (string-to-char cmd) ?\()
9983 (eval (read cmd))
9984 (call-interactively (read cmd))))
9985 (error "Abort"))))
9987 ((and (string= type "thisfile")
9988 (run-hook-with-args-until-success
9989 'org-open-link-functions path)))
9991 ((string= type "thisfile")
9992 (if arg
9993 (switch-to-buffer-other-window
9994 (org-get-buffer-for-internal-link (current-buffer)))
9995 (org-mark-ring-push))
9996 (let ((cmd `(org-link-search
9997 ,path
9998 ,(cond ((equal arg '(4)) ''occur)
9999 ((equal arg '(16)) ''org-occur))
10000 ,pos)))
10001 (condition-case nil (let ((org-link-search-inhibit-query t))
10002 (eval cmd))
10003 (error (progn (widen) (eval cmd))))))
10005 (t (browse-url-at-point)))))))
10006 (move-marker org-open-link-marker nil)
10007 (run-hook-with-args 'org-follow-link-hook)))
10009 (defun org-offer-links-in-entry (&optional nth zero)
10010 "Offer links in the current entry and follow the selected link.
10011 If there is only one link, follow it immediately as well.
10012 If NTH is an integer, immediately pick the NTH link found.
10013 If ZERO is a string, check also this string for a link, and if
10014 there is one, offer it as link number zero."
10015 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10016 "\\(" org-angle-link-re "\\)\\|"
10017 "\\(" org-plain-link-re "\\)"))
10018 (cnt ?0)
10019 (in-emacs (if (integerp nth) nil nth))
10020 have-zero end links link c)
10021 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10022 (push (match-string 0 zero) links)
10023 (setq cnt (1- cnt) have-zero t))
10024 (save-excursion
10025 (org-back-to-heading t)
10026 (setq end (save-excursion (outline-next-heading) (point)))
10027 (while (re-search-forward re end t)
10028 (push (match-string 0) links))
10029 (setq links (org-uniquify (reverse links))))
10031 (cond
10032 ((null links)
10033 (message "No links"))
10034 ((equal (length links) 1)
10035 (setq link (list (car links))))
10036 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10037 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10038 (t ; we have to select a link
10039 (save-excursion
10040 (save-window-excursion
10041 (delete-other-windows)
10042 (with-output-to-temp-buffer "*Select Link*"
10043 (mapc (lambda (l)
10044 (if (not (string-match org-bracket-link-regexp l))
10045 (princ (format "[%c] %s\n" (incf cnt)
10046 (org-remove-angle-brackets l)))
10047 (if (match-end 3)
10048 (princ (format "[%c] %s (%s)\n" (incf cnt)
10049 (match-string 3 l) (match-string 1 l)))
10050 (princ (format "[%c] %s\n" (incf cnt)
10051 (match-string 1 l))))))
10052 links))
10053 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10054 (message "Select link to open, RET to open all:")
10055 (setq c (read-char-exclusive))
10056 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10057 (when (equal c ?q) (error "Abort"))
10058 (if (equal c ?\C-m)
10059 (setq link links)
10060 (setq nth (- c ?0))
10061 (if have-zero (setq nth (1+ nth)))
10062 (unless (and (integerp nth) (>= (length links) nth))
10063 (error "Invalid link selection"))
10064 (setq link (list (nth (1- nth) links))))))
10065 (if link
10066 (let ((buf (current-buffer)))
10067 (dolist (l link)
10068 (org-open-link-from-string l in-emacs buf))
10070 nil)))
10072 ;; Add special file links that specify the way of opening
10074 (org-add-link-type "file+sys" 'org-open-file-with-system)
10075 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10076 (defun org-open-file-with-system (path)
10077 "Open file at PATH using the system way of opening it."
10078 (org-open-file path 'system))
10079 (defun org-open-file-with-emacs (path)
10080 "Open file at PATH in Emacs."
10081 (org-open-file path 'emacs))
10082 (defun org-remove-file-link-modifiers ()
10083 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10084 (goto-char (point-min))
10085 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10086 (org-if-unprotected
10087 (replace-match "file:" t t))))
10088 (eval-after-load "org-exp"
10089 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10090 'org-remove-file-link-modifiers))
10092 ;;;; Time estimates
10094 (defun org-get-effort (&optional pom)
10095 "Get the effort estimate for the current entry."
10096 (org-entry-get pom org-effort-property))
10098 ;;; File search
10100 (defvar org-create-file-search-functions nil
10101 "List of functions to construct the right search string for a file link.
10102 These functions are called in turn with point at the location to
10103 which the link should point.
10105 A function in the hook should first test if it would like to
10106 handle this file type, for example by checking the `major-mode'
10107 or the file extension. If it decides not to handle this file, it
10108 should just return nil to give other functions a chance. If it
10109 does handle the file, it must return the search string to be used
10110 when following the link. The search string will be part of the
10111 file link, given after a double colon, and `org-open-at-point'
10112 will automatically search for it. If special measures must be
10113 taken to make the search successful, another function should be
10114 added to the companion hook `org-execute-file-search-functions',
10115 which see.
10117 A function in this hook may also use `setq' to set the variable
10118 `description' to provide a suggestion for the descriptive text to
10119 be used for this link when it gets inserted into an Org-mode
10120 buffer with \\[org-insert-link].")
10122 (defvar org-execute-file-search-functions nil
10123 "List of functions to execute a file search triggered by a link.
10125 Functions added to this hook must accept a single argument, the
10126 search string that was part of the file link, the part after the
10127 double colon. The function must first check if it would like to
10128 handle this search, for example by checking the `major-mode' or
10129 the file extension. If it decides not to handle this search, it
10130 should just return nil to give other functions a chance. If it
10131 does handle the search, it must return a non-nil value to keep
10132 other functions from trying.
10134 Each function can access the current prefix argument through the
10135 variable `current-prefix-argument'. Note that a single prefix is
10136 used to force opening a link in Emacs, so it may be good to only
10137 use a numeric or double prefix to guide the search function.
10139 In case this is needed, a function in this hook can also restore
10140 the window configuration before `org-open-at-point' was called using:
10142 (set-window-configuration org-window-config-before-follow-link)")
10144 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10145 (defun org-link-search (s &optional type avoid-pos stealth)
10146 "Search for a link search option.
10147 If S is surrounded by forward slashes, it is interpreted as a
10148 regular expression. In org-mode files, this will create an `org-occur'
10149 sparse tree. In ordinary files, `occur' will be used to list matches.
10150 If the current buffer is in `dired-mode', grep will be used to search
10151 in all files. If AVOID-POS is given, ignore matches near that position.
10153 When optional argument STEALTH is non-nil, do not modify
10154 visibility around point, thus ignoring
10155 `org-show-hierarchy-above', `org-show-following-heading' and
10156 `org-show-siblings' variables."
10157 (let ((case-fold-search t)
10158 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10159 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10160 (append '(("") (" ") ("\t") ("\n"))
10161 org-emphasis-alist)
10162 "\\|") "\\)"))
10163 (pos (point))
10164 (pre nil) (post nil)
10165 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10166 (cond
10167 ;; First check if there are any special search functions
10168 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10169 ;; Now try the builtin stuff
10170 ((and (equal (string-to-char s0) ?#)
10171 (> (length s0) 1)
10172 (save-excursion
10173 (goto-char (point-min))
10174 (and
10175 (re-search-forward
10176 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10177 (setq type 'dedicated
10178 pos (match-beginning 0))))
10179 ;; There is an exact target for this
10180 (goto-char pos)
10181 (org-back-to-heading t)))
10182 ((save-excursion
10183 (goto-char (point-min))
10184 (and
10185 (re-search-forward
10186 (concat "<<" (regexp-quote s0) ">>") nil t)
10187 (setq type 'dedicated
10188 pos (match-beginning 0))))
10189 ;; There is an exact target for this
10190 (goto-char pos))
10191 ((save-excursion
10192 (goto-char (point-min))
10193 (and
10194 (re-search-forward
10195 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10196 (setq type 'dedicated pos (match-beginning 0))))
10197 ;; Found an invisible target.
10198 (goto-char pos))
10199 ((save-excursion
10200 (goto-char (point-min))
10201 (and
10202 (re-search-forward
10203 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10204 (setq type 'dedicated pos (match-beginning 0))))
10205 ;; Found an element with a matching #+name affiliated keyword.
10206 (goto-char pos))
10207 ((and (string-match "^(\\(.*\\))$" s0)
10208 (save-excursion
10209 (goto-char (point-min))
10210 (and
10211 (re-search-forward
10212 (concat "[^[]" (regexp-quote
10213 (format org-coderef-label-format
10214 (match-string 1 s0))))
10215 nil t)
10216 (setq type 'dedicated
10217 pos (1+ (match-beginning 0))))))
10218 ;; There is a coderef target for this
10219 (goto-char pos))
10220 ((string-match "^/\\(.*\\)/$" s)
10221 ;; A regular expression
10222 (cond
10223 ((derived-mode-p 'org-mode)
10224 (org-occur (match-string 1 s)))
10225 ;;((eq major-mode 'dired-mode)
10226 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10227 (t (org-do-occur (match-string 1 s)))))
10228 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10229 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10230 (goto-char (point-min))
10231 (cond
10232 ((let (case-fold-search)
10233 (re-search-forward (format org-complex-heading-regexp-format
10234 (regexp-quote s))
10235 nil t))
10236 ;; OK, found a match
10237 (setq type 'dedicated)
10238 (goto-char (match-beginning 0)))
10239 ((and (not org-link-search-inhibit-query)
10240 (eq org-link-search-must-match-exact-headline 'query-to-create)
10241 (y-or-n-p "No match - create this as a new heading? "))
10242 (goto-char (point-max))
10243 (or (bolp) (newline))
10244 (insert "* " s "\n")
10245 (beginning-of-line 0))
10247 (goto-char pos)
10248 (error "No match"))))
10250 ;; A normal search string
10251 (when (equal (string-to-char s) ?*)
10252 ;; Anchor on headlines, post may include tags.
10253 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10254 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10255 s (substring s 1)))
10256 (remove-text-properties
10257 0 (length s)
10258 '(face nil mouse-face nil keymap nil fontified nil) s)
10259 ;; Make a series of regular expressions to find a match
10260 (setq words (org-split-string s "[ \n\r\t]+")
10262 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10263 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10264 "\\)" markers)
10265 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10266 re2a (concat "[ \t\r\n]" re2a_)
10267 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10268 re4 (concat "[^a-zA-Z_]" re4_)
10270 re1 (concat pre re2 post)
10271 re3 (concat pre (if pre re4_ re4) post)
10272 re5 (concat pre ".*" re4)
10273 re2 (concat pre re2)
10274 re2a (concat pre (if pre re2a_ re2a))
10275 re4 (concat pre (if pre re4_ re4))
10276 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10277 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10278 re5 "\\)"
10280 (cond
10281 ((eq type 'org-occur) (org-occur reall))
10282 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10283 (t (goto-char (point-min))
10284 (setq type 'fuzzy)
10285 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10286 (org-search-not-self 1 re1 nil t)
10287 (org-search-not-self 1 re2 nil t)
10288 (org-search-not-self 1 re2a nil t)
10289 (org-search-not-self 1 re3 nil t)
10290 (org-search-not-self 1 re4 nil t)
10291 (org-search-not-self 1 re5 nil t)
10293 (goto-char (match-beginning 1))
10294 (goto-char pos)
10295 (error "No match"))))))
10296 (and (derived-mode-p 'org-mode)
10297 (not stealth)
10298 (org-show-context 'link-search))
10299 type))
10301 (defun org-search-not-self (group &rest args)
10302 "Execute `re-search-forward', but only accept matches that do not
10303 enclose the position of `org-open-link-marker'."
10304 (let ((m org-open-link-marker))
10305 (catch 'exit
10306 (while (apply 're-search-forward args)
10307 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10308 (goto-char (match-end group))
10309 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10310 (> (match-beginning 0) (marker-position m))
10311 (< (match-end 0) (marker-position m)))
10312 (save-match-data
10313 (or (not (org-in-regexp
10314 org-bracket-link-analytic-regexp 1))
10315 (not (match-end 4)) ; no description
10316 (and (<= (match-beginning 4) (point))
10317 (>= (match-end 4) (point))))))
10318 (throw 'exit (point))))))))
10320 (defun org-get-buffer-for-internal-link (buffer)
10321 "Return a buffer to be used for displaying the link target of internal links."
10322 (cond
10323 ((not org-display-internal-link-with-indirect-buffer)
10324 buffer)
10325 ((string-match "(Clone)$" (buffer-name buffer))
10326 (message "Buffer is already a clone, not making another one")
10327 ;; we also do not modify visibility in this case
10328 buffer)
10329 (t ; make a new indirect buffer for displaying the link
10330 (let* ((bn (buffer-name buffer))
10331 (ibn (concat bn "(Clone)"))
10332 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10333 (with-current-buffer ib (org-overview))
10334 ib))))
10336 (defun org-do-occur (regexp &optional cleanup)
10337 "Call the Emacs command `occur'.
10338 If CLEANUP is non-nil, remove the printout of the regular expression
10339 in the *Occur* buffer. This is useful if the regex is long and not useful
10340 to read."
10341 (occur regexp)
10342 (when cleanup
10343 (let ((cwin (selected-window)) win beg end)
10344 (when (setq win (get-buffer-window "*Occur*"))
10345 (select-window win))
10346 (goto-char (point-min))
10347 (when (re-search-forward "match[a-z]+" nil t)
10348 (setq beg (match-end 0))
10349 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10350 (setq end (1- (match-beginning 0)))))
10351 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10352 (goto-char (point-min))
10353 (select-window cwin))))
10355 ;;; The mark ring for links jumps
10357 (defvar org-mark-ring nil
10358 "Mark ring for positions before jumps in Org-mode.")
10359 (defvar org-mark-ring-last-goto nil
10360 "Last position in the mark ring used to go back.")
10361 ;; Fill and close the ring
10362 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10363 (loop for i from 1 to org-mark-ring-length do
10364 (push (make-marker) org-mark-ring))
10365 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10366 org-mark-ring)
10368 (defun org-mark-ring-push (&optional pos buffer)
10369 "Put the current position or POS into the mark ring and rotate it."
10370 (interactive)
10371 (setq pos (or pos (point)))
10372 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10373 (move-marker (car org-mark-ring)
10374 (or pos (point))
10375 (or buffer (current-buffer)))
10376 (message "%s"
10377 (substitute-command-keys
10378 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10380 (defun org-mark-ring-goto (&optional n)
10381 "Jump to the previous position in the mark ring.
10382 With prefix arg N, jump back that many stored positions. When
10383 called several times in succession, walk through the entire ring.
10384 Org-mode commands jumping to a different position in the current file,
10385 or to another Org-mode file, automatically push the old position
10386 onto the ring."
10387 (interactive "p")
10388 (let (p m)
10389 (if (eq last-command this-command)
10390 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10391 (setq p org-mark-ring))
10392 (setq org-mark-ring-last-goto p)
10393 (setq m (car p))
10394 (org-pop-to-buffer-same-window (marker-buffer m))
10395 (goto-char m)
10396 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10398 (defun org-remove-angle-brackets (s)
10399 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10400 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10402 (defun org-add-angle-brackets (s)
10403 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10404 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10406 (defun org-remove-double-quotes (s)
10407 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10408 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10411 ;;; Following specific links
10413 (defun org-follow-timestamp-link ()
10414 (cond
10415 ((org-at-date-range-p t)
10416 (let ((org-agenda-start-on-weekday)
10417 (t1 (match-string 1))
10418 (t2 (match-string 2)))
10419 (setq t1 (time-to-days (org-time-string-to-time t1))
10420 t2 (time-to-days (org-time-string-to-time t2)))
10421 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10422 ((org-at-timestamp-p t)
10423 (org-agenda-list nil (time-to-days (org-time-string-to-time
10424 (substring (match-string 1) 0 10)))
10426 (t (error "This should not happen"))))
10429 ;;; Following file links
10430 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10431 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10432 (declare-function mailcap-mime-info
10433 "mailcap" (string &optional request no-decode))
10434 (defvar org-wait nil)
10435 (defun org-open-file (path &optional in-emacs line search)
10436 "Open the file at PATH.
10437 First, this expands any special file name abbreviations. Then the
10438 configuration variable `org-file-apps' is checked if it contains an
10439 entry for this file type, and if yes, the corresponding command is launched.
10441 If no application is found, Emacs simply visits the file.
10443 With optional prefix argument IN-EMACS, Emacs will visit the file.
10444 With a double \\[universal-argument] \\[universal-argument] \
10445 prefix arg, Org tries to avoid opening in Emacs
10446 and to use an external application to visit the file.
10448 Optional LINE specifies a line to go to, optional SEARCH a string
10449 to search for. If LINE or SEARCH is given, the file will be
10450 opened in Emacs, unless an entry from org-file-apps that makes
10451 use of groups in a regexp matches.
10453 If you want to change the way frames are used when following a
10454 link, please customize `org-link-frame-setup'.
10456 If the file does not exist, an error is thrown."
10457 (let* ((file (if (equal path "")
10458 buffer-file-name
10459 (substitute-in-file-name (expand-file-name path))))
10460 (file-apps (append org-file-apps (org-default-apps)))
10461 (apps (org-remove-if
10462 'org-file-apps-entry-match-against-dlink-p file-apps))
10463 (apps-dlink (org-remove-if-not
10464 'org-file-apps-entry-match-against-dlink-p file-apps))
10465 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10466 (dirp (if remp nil (file-directory-p file)))
10467 (file (if (and dirp org-open-directory-means-index-dot-org)
10468 (concat (file-name-as-directory file) "index.org")
10469 file))
10470 (a-m-a-p (assq 'auto-mode apps))
10471 (dfile (downcase file))
10472 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10473 (link (cond ((and (eq line nil)
10474 (eq search nil))
10475 file)
10476 (line
10477 (concat file "::" (number-to-string line)))
10478 (search
10479 (concat file "::" search))))
10480 (dlink (downcase link))
10481 (old-buffer (current-buffer))
10482 (old-pos (point))
10483 (old-mode major-mode)
10484 ext cmd link-match-data)
10485 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10486 (setq ext (match-string 1 dfile))
10487 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10488 (setq ext (match-string 1 dfile))))
10489 (cond
10490 ((member in-emacs '((16) system))
10491 (setq cmd (cdr (assoc 'system apps))))
10492 (in-emacs (setq cmd 'emacs))
10494 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10495 (and dirp (cdr (assoc 'directory apps)))
10496 ; first, try matching against apps-dlink
10497 ; if we get a match here, store the match data for later
10498 (let ((match (assoc-default dlink apps-dlink
10499 'string-match)))
10500 (if match
10501 (progn (setq link-match-data (match-data))
10502 match)
10503 (progn (setq in-emacs (or in-emacs line search))
10504 nil))) ; if we have no match in apps-dlink,
10505 ; always open the file in emacs if line or search
10506 ; is given (for backwards compatibility)
10507 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10508 'string-match)
10509 (cdr (assoc ext apps))
10510 (cdr (assoc t apps))))))
10511 (when (eq cmd 'system)
10512 (setq cmd (cdr (assoc 'system apps))))
10513 (when (eq cmd 'default)
10514 (setq cmd (cdr (assoc t apps))))
10515 (when (eq cmd 'mailcap)
10516 (require 'mailcap)
10517 (mailcap-parse-mailcaps)
10518 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10519 (command (mailcap-mime-info mime-type)))
10520 (if (stringp command)
10521 (setq cmd command)
10522 (setq cmd 'emacs))))
10523 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10524 (not (file-exists-p file))
10525 (not org-open-non-existing-files))
10526 (error "No such file: %s" file))
10527 (cond
10528 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10529 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10530 (while (string-match "['\"]%s['\"]" cmd)
10531 (setq cmd (replace-match "%s" t t cmd)))
10532 (while (string-match "%s" cmd)
10533 (setq cmd (replace-match
10534 (save-match-data
10535 (shell-quote-argument
10536 (convert-standard-filename file)))
10537 t t cmd)))
10539 ;; Replace "%1", "%2" etc. in command with group matches from regex
10540 (save-match-data
10541 (let ((match-index 1)
10542 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10543 (set-match-data link-match-data)
10544 (while (<= match-index number-of-groups)
10545 (let ((regex (concat "%" (number-to-string match-index)))
10546 (replace-with (match-string match-index dlink)))
10547 (while (string-match regex cmd)
10548 (setq cmd (replace-match replace-with t t cmd))))
10549 (setq match-index (+ match-index 1)))))
10551 (save-window-excursion
10552 (message "Running %s...done" cmd)
10553 (start-process-shell-command cmd nil cmd)
10554 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10555 ((or (stringp cmd)
10556 (eq cmd 'emacs))
10557 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10558 (widen)
10559 (if line (org-goto-line line)
10560 (if search (org-link-search search))))
10561 ((consp cmd)
10562 (let ((file (convert-standard-filename file)))
10563 (save-match-data
10564 (set-match-data link-match-data)
10565 (eval cmd))))
10566 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10567 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10568 (or (not (equal old-buffer (current-buffer)))
10569 (not (equal old-pos (point))))
10570 (org-mark-ring-push old-pos old-buffer))))
10572 (defun org-file-apps-entry-match-against-dlink-p (entry)
10573 "This function returns non-nil if `entry' uses a regular
10574 expression which should be matched against the whole link by
10575 org-open-file.
10577 It assumes that is the case when the entry uses a regular
10578 expression which has at least one grouping construct and the
10579 action is either a lisp form or a command string containing
10580 '%1', i.e. using at least one subexpression match as a
10581 parameter."
10582 (let ((selector (car entry))
10583 (action (cdr entry)))
10584 (if (stringp selector)
10585 (and (> (regexp-opt-depth selector) 0)
10586 (or (and (stringp action)
10587 (string-match "%[0-9]" action))
10588 (consp action)))
10589 nil)))
10591 (defun org-default-apps ()
10592 "Return the default applications for this operating system."
10593 (cond
10594 ((eq system-type 'darwin)
10595 org-file-apps-defaults-macosx)
10596 ((eq system-type 'windows-nt)
10597 org-file-apps-defaults-windowsnt)
10598 (t org-file-apps-defaults-gnu)))
10600 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10601 "Convert extensions to regular expressions in the cars of LIST.
10602 Also, weed out any non-string entries, because the return value is used
10603 only for regexp matching.
10604 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10605 point to the symbol `emacs', indicating that the file should
10606 be opened in Emacs."
10607 (append
10608 (delq nil
10609 (mapcar (lambda (x)
10610 (if (not (stringp (car x)))
10612 (if (string-match "\\W" (car x))
10614 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10615 list))
10616 (if add-auto-mode
10617 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10619 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10620 (defun org-file-remote-p (file)
10621 "Test whether FILE specifies a location on a remote system.
10622 Return non-nil if the location is indeed remote.
10624 For example, the filename \"/user@host:/foo\" specifies a location
10625 on the system \"/user@host:\"."
10626 (cond ((fboundp 'file-remote-p)
10627 (file-remote-p file))
10628 ((fboundp 'tramp-handle-file-remote-p)
10629 (tramp-handle-file-remote-p file))
10630 ((and (boundp 'ange-ftp-name-format)
10631 (string-match (car ange-ftp-name-format) file))
10632 t)))
10635 ;;;; Refiling
10637 (defun org-get-org-file ()
10638 "Read a filename, with default directory `org-directory'."
10639 (let ((default (or org-default-notes-file remember-data-file)))
10640 (read-file-name (format "File name [%s]: " default)
10641 (file-name-as-directory org-directory)
10642 default)))
10644 (defun org-notes-order-reversed-p ()
10645 "Check if the current file should receive notes in reversed order."
10646 (cond
10647 ((not org-reverse-note-order) nil)
10648 ((eq t org-reverse-note-order) t)
10649 ((not (listp org-reverse-note-order)) nil)
10650 (t (catch 'exit
10651 (let ((all org-reverse-note-order)
10652 entry)
10653 (while (setq entry (pop all))
10654 (if (string-match (car entry) buffer-file-name)
10655 (throw 'exit (cdr entry))))
10656 nil)))))
10658 (defvar org-refile-target-table nil
10659 "The list of refile targets, created by `org-refile'.")
10661 (defvar org-agenda-new-buffers nil
10662 "Buffers created to visit agenda files.")
10664 (defvar org-refile-cache nil
10665 "Cache for refile targets.")
10667 (defvar org-refile-markers nil
10668 "All the markers used for caching refile locations.")
10670 (defun org-refile-marker (pos)
10671 "Get a new refile marker, but only if caching is in use."
10672 (if (not org-refile-use-cache)
10674 (let ((m (make-marker)))
10675 (move-marker m pos)
10676 (push m org-refile-markers)
10677 m)))
10679 (defun org-refile-cache-clear ()
10680 "Clear the refile cache and disable all the markers."
10681 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10682 (setq org-refile-markers nil)
10683 (setq org-refile-cache nil)
10684 (message "Refile cache has been cleared"))
10686 (defun org-refile-cache-check-set (set)
10687 "Check if all the markers in the cache still have live buffers."
10688 (let (marker)
10689 (catch 'exit
10690 (while (and set (setq marker (nth 3 (pop set))))
10691 ;; if org-refile-use-outline-path is 'file, marker may be nil
10692 (when (and marker (null (marker-buffer marker)))
10693 (message "not found") (sit-for 3)
10694 (throw 'exit nil)))
10695 t)))
10697 (defun org-refile-cache-put (set &rest identifiers)
10698 "Push the refile targets SET into the cache, under IDENTIFIERS."
10699 (let* ((key (sha1 (prin1-to-string identifiers)))
10700 (entry (assoc key org-refile-cache)))
10701 (if entry
10702 (setcdr entry set)
10703 (push (cons key set) org-refile-cache))))
10705 (defun org-refile-cache-get (&rest identifiers)
10706 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10707 (cond
10708 ((not org-refile-cache) nil)
10709 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10711 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10712 org-refile-cache))))
10713 (and set (org-refile-cache-check-set set) set)))))
10715 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10716 "Produce a table with refile targets."
10717 (let ((case-fold-search nil)
10718 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10719 (entries (or org-refile-targets '((nil . (:level . 1)))))
10720 targets tgs txt re files f desc descre fast-path-p level pos0)
10721 (message "Getting targets...")
10722 (with-current-buffer (or default-buffer (current-buffer))
10723 (while (setq entry (pop entries))
10724 (setq files (car entry) desc (cdr entry))
10725 (setq fast-path-p nil)
10726 (cond
10727 ((null files) (setq files (list (current-buffer))))
10728 ((eq files 'org-agenda-files)
10729 (setq files (org-agenda-files 'unrestricted)))
10730 ((and (symbolp files) (fboundp files))
10731 (setq files (funcall files)))
10732 ((and (symbolp files) (boundp files))
10733 (setq files (symbol-value files))))
10734 (if (stringp files) (setq files (list files)))
10735 (cond
10736 ((eq (car desc) :tag)
10737 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10738 ((eq (car desc) :todo)
10739 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10740 ((eq (car desc) :regexp)
10741 (setq descre (cdr desc)))
10742 ((eq (car desc) :level)
10743 (setq descre (concat "^\\*\\{" (number-to-string
10744 (if org-odd-levels-only
10745 (1- (* 2 (cdr desc)))
10746 (cdr desc)))
10747 "\\}[ \t]")))
10748 ((eq (car desc) :maxlevel)
10749 (setq fast-path-p t)
10750 (setq descre (concat "^\\*\\{1," (number-to-string
10751 (if org-odd-levels-only
10752 (1- (* 2 (cdr desc)))
10753 (cdr desc)))
10754 "\\}[ \t]")))
10755 (t (error "Bad refiling target description %s" desc)))
10756 (while (setq f (pop files))
10757 (with-current-buffer
10758 (if (bufferp f) f (org-get-agenda-file-buffer f))
10760 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10761 (progn
10762 (if (bufferp f) (setq f (buffer-file-name
10763 (buffer-base-buffer f))))
10764 (setq f (and f (expand-file-name f)))
10765 (if (eq org-refile-use-outline-path 'file)
10766 (push (list (file-name-nondirectory f) f nil nil) tgs))
10767 (save-excursion
10768 (save-restriction
10769 (widen)
10770 (goto-char (point-min))
10771 (while (re-search-forward descre nil t)
10772 (goto-char (setq pos0 (point-at-bol)))
10773 (catch 'next
10774 (when org-refile-target-verify-function
10775 (save-match-data
10776 (or (funcall org-refile-target-verify-function)
10777 (throw 'next t))))
10778 (when (and (looking-at org-complex-heading-regexp)
10779 (not (member (match-string 4) excluded-entries))
10780 (match-string 4))
10781 (setq level (org-reduced-level
10782 (- (match-end 1) (match-beginning 1)))
10783 txt (org-link-display-format (match-string 4))
10784 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10785 re (format org-complex-heading-regexp-format
10786 (regexp-quote (match-string 4))))
10787 (when org-refile-use-outline-path
10788 (setq txt (mapconcat
10789 'org-protect-slash
10790 (append
10791 (if (eq org-refile-use-outline-path
10792 'file)
10793 (list (file-name-nondirectory
10794 (buffer-file-name
10795 (buffer-base-buffer))))
10796 (if (eq org-refile-use-outline-path
10797 'full-file-path)
10798 (list (buffer-file-name
10799 (buffer-base-buffer)))))
10800 (org-get-outline-path fast-path-p
10801 level txt)
10802 (list txt))
10803 "/")))
10804 (push (list txt f re (org-refile-marker (point)))
10805 tgs)))
10806 (when (= (point) pos0)
10807 ;; verification function has not moved point
10808 (goto-char (point-at-eol))))))))
10809 (when org-refile-use-cache
10810 (org-refile-cache-put tgs (buffer-file-name) descre))
10811 (setq targets (append tgs targets))
10812 ))))
10813 (message "Getting targets...done")
10814 (nreverse targets)))
10816 (defun org-protect-slash (s)
10817 (while (string-match "/" s)
10818 (setq s (replace-match "\\" t t s)))
10821 (defvar org-olpa (make-vector 20 nil))
10823 (defun org-get-outline-path (&optional fastp level heading)
10824 "Return the outline path to the current entry, as a list.
10826 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10827 routine which makes outline path derivations for an entire file,
10828 avoiding backtracing. Refile target collection makes use of that."
10829 (if fastp
10830 (progn
10831 (if (> level 19)
10832 (error "Outline path failure, more than 19 levels"))
10833 (loop for i from level upto 19 do
10834 (aset org-olpa i nil))
10835 (prog1
10836 (delq nil (append org-olpa nil))
10837 (aset org-olpa level heading)))
10838 (let (rtn case-fold-search)
10839 (save-excursion
10840 (save-restriction
10841 (widen)
10842 (while (org-up-heading-safe)
10843 (when (looking-at org-complex-heading-regexp)
10844 (push (org-match-string-no-properties 4) rtn)))
10845 rtn)))))
10847 (defun org-format-outline-path (path &optional width prefix)
10848 "Format the outline path PATH for display.
10849 Width is the maximum number of characters that is available.
10850 Prefix is a prefix to be included in the returned string,
10851 such as the file name."
10852 (setq width (or width 79))
10853 (if prefix (setq width (- width (length prefix))))
10854 (if (not path)
10855 (or prefix "")
10856 (let* ((nsteps (length path))
10857 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10858 (maxwidth (if (<= total-width width)
10859 10000 ;; everything fits
10860 ;; we need to shorten the level headings
10861 (/ (- width nsteps) nsteps)))
10862 (org-odd-levels-only nil)
10863 (n 0)
10864 (total (1+ (length prefix))))
10865 (setq maxwidth (max maxwidth 10))
10866 (concat prefix
10867 (mapconcat
10868 (lambda (h)
10869 (setq n (1+ n))
10870 (if (and (= n nsteps) (< maxwidth 10000))
10871 (setq maxwidth (- total-width total)))
10872 (if (< (length h) maxwidth)
10873 (progn (setq total (+ total (length h) 1)) h)
10874 (setq h (substring h 0 (- maxwidth 2))
10875 total (+ total maxwidth 1))
10876 (if (string-match "[ \t]+\\'" h)
10877 (setq h (substring h 0 (match-beginning 0))))
10878 (setq h (concat h "..")))
10879 (org-add-props h nil 'face
10880 (nth (% (1- n) org-n-level-faces)
10881 org-level-faces))
10883 path "/")))))
10885 (defun org-display-outline-path (&optional file current)
10886 "Display the current outline path in the echo area."
10887 (interactive "P")
10888 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10889 (case-fold-search nil)
10890 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10891 (if current (setq path (append path
10892 (save-excursion
10893 (org-back-to-heading t)
10894 (if (looking-at org-complex-heading-regexp)
10895 (list (match-string 4)))))))
10896 (message "%s"
10897 (org-format-outline-path
10898 path
10899 (1- (frame-width))
10900 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10902 (defvar org-refile-history nil
10903 "History for refiling operations.")
10905 (defvar org-after-refile-insert-hook nil
10906 "Hook run after `org-refile' has inserted its stuff at the new location.
10907 Note that this is still *before* the stuff will be removed from
10908 the *old* location.")
10910 (defvar org-capture-last-stored-marker)
10911 (defun org-refile (&optional goto default-buffer rfloc)
10912 "Move the entry or entries at point to another heading.
10913 The list of target headings is compiled using the information in
10914 `org-refile-targets', which see.
10916 At the target location, the entry is filed as a subitem of the target
10917 heading. Depending on `org-reverse-note-order', the new subitem will
10918 either be the first or the last subitem.
10920 If there is an active region, all entries in that region will be moved.
10921 However, the region must fulfill the requirement that the first heading
10922 is the first one sets the top-level of the moved text - at most siblings
10923 below it are allowed.
10925 With prefix arg GOTO, the command will only visit the target location
10926 and not actually move anything.
10928 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10929 go to the location where the last refiling operation has put the subtree.
10930 With a prefix argument of `2', refile to the running clock.
10932 RFLOC can be a refile location obtained in a different way.
10934 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10936 If you are using target caching (see `org-refile-use-cache'),
10937 you have to clear the target cache in order to find new targets.
10938 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10939 prefix argument (`C-u C-u C-u C-c C-w')."
10941 (interactive "P")
10942 (if (member goto '(0 (64)))
10943 (org-refile-cache-clear)
10944 (let* ((cbuf (current-buffer))
10945 (regionp (org-region-active-p))
10946 (region-start (and regionp (region-beginning)))
10947 (region-end (and regionp (region-end)))
10948 (region-length (and regionp (- region-end region-start)))
10949 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10950 pos it nbuf file re level reversed)
10951 (setq last-command nil)
10952 (when regionp
10953 (goto-char region-start)
10954 (or (bolp) (goto-char (point-at-bol)))
10955 (setq region-start (point))
10956 (unless (or (org-kill-is-subtree-p
10957 (buffer-substring region-start region-end))
10958 (prog1 org-refile-active-region-within-subtree
10959 (org-toggle-heading)))
10960 (error "The region is not a (sequence of) subtree(s)")))
10961 (if (equal goto '(16))
10962 (org-refile-goto-last-stored)
10963 (when (or
10964 (and (equal goto 2)
10965 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10966 (prog1
10967 (setq it (list (or org-clock-heading "running clock")
10968 (buffer-file-name
10969 (marker-buffer org-clock-hd-marker))
10971 (marker-position org-clock-hd-marker)))
10972 (setq goto nil)))
10973 (setq it (or rfloc
10974 (let (heading-text)
10975 (save-excursion
10976 (unless goto
10977 (org-back-to-heading t)
10978 (setq heading-text
10979 (nth 4 (org-heading-components))))
10980 (org-refile-get-location
10981 (cond (goto "Goto")
10982 (regionp "Refile region to")
10983 (t (concat "Refile subtree \""
10984 heading-text "\" to")))
10985 default-buffer
10986 (and (not (equal '(4) goto))
10987 org-refile-allow-creating-parent-nodes)
10988 goto))))))
10989 (setq file (nth 1 it)
10990 re (nth 2 it)
10991 pos (nth 3 it))
10992 (if (and (not goto)
10994 (equal (buffer-file-name) file)
10995 (if regionp
10996 (and (>= pos region-start)
10997 (<= pos region-end))
10998 (and (>= pos (point))
10999 (< pos (save-excursion
11000 (org-end-of-subtree t t))))))
11001 (error "Cannot refile to position inside the tree or region"))
11003 (setq nbuf (or (find-buffer-visiting file)
11004 (find-file-noselect file)))
11005 (if goto
11006 (progn
11007 (org-pop-to-buffer-same-window nbuf)
11008 (goto-char pos)
11009 (org-show-context 'org-goto))
11010 (if regionp
11011 (progn
11012 (org-kill-new (buffer-substring region-start region-end))
11013 (org-save-markers-in-region region-start region-end))
11014 (org-copy-subtree 1 nil t))
11015 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11016 (find-file-noselect file)))
11017 (setq reversed (org-notes-order-reversed-p))
11018 (save-excursion
11019 (save-restriction
11020 (widen)
11021 (if pos
11022 (progn
11023 (goto-char pos)
11024 (looking-at org-outline-regexp)
11025 (setq level (org-get-valid-level (funcall outline-level) 1))
11026 (goto-char
11027 (if reversed
11028 (or (outline-next-heading) (point-max))
11029 (or (save-excursion (org-get-next-sibling))
11030 (org-end-of-subtree t t)
11031 (point-max)))))
11032 (setq level 1)
11033 (if (not reversed)
11034 (goto-char (point-max))
11035 (goto-char (point-min))
11036 (or (outline-next-heading) (goto-char (point-max)))))
11037 (if (not (bolp)) (newline))
11038 (org-paste-subtree level)
11039 (when org-log-refile
11040 (org-add-log-setup 'refile nil nil 'findpos
11041 org-log-refile)
11042 (unless (eq org-log-refile 'note)
11043 (save-excursion (org-add-log-note))))
11044 (and org-auto-align-tags
11045 (let ((org-loop-over-headlines-in-active-region nil))
11046 (org-set-tags nil t)))
11047 (bookmark-set "org-refile-last-stored")
11048 ;; If we are refiling for capture, make sure that the
11049 ;; last-capture pointers point here
11050 (when (org-bound-and-true-p org-refile-for-capture)
11051 (bookmark-set "org-capture-last-stored-marker")
11052 (move-marker org-capture-last-stored-marker (point)))
11053 (if (fboundp 'deactivate-mark) (deactivate-mark))
11054 (run-hooks 'org-after-refile-insert-hook))))
11055 (if regionp
11056 (delete-region (point) (+ (point) region-length))
11057 (org-cut-subtree))
11058 (when (featurep 'org-inlinetask)
11059 (org-inlinetask-remove-END-maybe))
11060 (setq org-markers-to-move nil)
11061 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11063 (defun org-refile-goto-last-stored ()
11064 "Go to the location where the last refile was stored."
11065 (interactive)
11066 (bookmark-jump "org-refile-last-stored")
11067 (message "This is the location of the last refile"))
11069 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11070 no-exclude)
11071 "Prompt the user for a refile location, using PROMPT.
11072 PROMPT should not be suffixed with a colon and a space, because
11073 this function appends the default value from
11074 `org-refile-history' automatically, if that is not empty.
11075 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11076 this is used for the GOTO interface."
11077 (let ((org-refile-targets org-refile-targets)
11078 (org-refile-use-outline-path org-refile-use-outline-path)
11079 excluded-entries)
11080 (when (and (derived-mode-p 'org-mode)
11081 (not org-refile-use-cache)
11082 (not no-exclude))
11083 (org-map-tree
11084 (lambda()
11085 (setq excluded-entries
11086 (append excluded-entries (list (org-get-heading t t)))))))
11087 (setq org-refile-target-table
11088 (org-refile-get-targets default-buffer excluded-entries)))
11089 (unless org-refile-target-table
11090 (error "No refile targets"))
11091 (let* ((prompt (concat prompt
11092 (and (car org-refile-history)
11093 (concat " (default " (car org-refile-history) ")"))
11094 ": "))
11095 (cbuf (current-buffer))
11096 (partial-completion-mode nil)
11097 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11098 (cfunc (if (and org-refile-use-outline-path
11099 org-outline-path-complete-in-steps)
11100 'org-olpath-completing-read
11101 'org-icompleting-read))
11102 (extra (if org-refile-use-outline-path "/" ""))
11103 (filename (and cfn (expand-file-name cfn)))
11104 (tbl (mapcar
11105 (lambda (x)
11106 (if (and (not (member org-refile-use-outline-path
11107 '(file full-file-path)))
11108 (not (equal filename (nth 1 x))))
11109 (cons (concat (car x) extra " ("
11110 (file-name-nondirectory (nth 1 x)) ")")
11111 (cdr x))
11112 (cons (concat (car x) extra) (cdr x))))
11113 org-refile-target-table))
11114 (completion-ignore-case t)
11115 pa answ parent-target child parent old-hist)
11116 (setq old-hist org-refile-history)
11117 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11118 nil 'org-refile-history (car org-refile-history)))
11119 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11120 (org-refile-check-position pa)
11121 (if pa
11122 (progn
11123 (when (or (not org-refile-history)
11124 (not (eq old-hist org-refile-history))
11125 (not (equal (car pa) (car org-refile-history))))
11126 (setq org-refile-history
11127 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11128 org-refile-history
11129 (cdr org-refile-history))))
11130 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11131 (pop org-refile-history)))
11133 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11134 (progn
11135 (setq parent (match-string 1 answ)
11136 child (match-string 2 answ))
11137 (setq parent-target (or (assoc parent tbl)
11138 (assoc (concat parent "/") tbl)))
11139 (when (and parent-target
11140 (or (eq new-nodes t)
11141 (and (eq new-nodes 'confirm)
11142 (y-or-n-p (format "Create new node \"%s\"? "
11143 child)))))
11144 (org-refile-new-child parent-target child)))
11145 (error "Invalid target location")))))
11147 (declare-function org-string-nw-p "org-macs.el" (s))
11148 (defun org-refile-check-position (refile-pointer)
11149 "Check if the refile pointer matches the readline to which it points."
11150 (let* ((file (nth 1 refile-pointer))
11151 (re (nth 2 refile-pointer))
11152 (pos (nth 3 refile-pointer))
11153 buffer)
11154 (when (org-string-nw-p re)
11155 (setq buffer (if (markerp pos)
11156 (marker-buffer pos)
11157 (or (find-buffer-visiting file)
11158 (find-file-noselect file))))
11159 (with-current-buffer buffer
11160 (save-excursion
11161 (save-restriction
11162 (widen)
11163 (goto-char pos)
11164 (beginning-of-line 1)
11165 (unless (org-looking-at-p re)
11166 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11168 (defun org-refile-new-child (parent-target child)
11169 "Use refile target PARENT-TARGET to add new CHILD below it."
11170 (unless parent-target
11171 (error "Cannot find parent for new node"))
11172 (let ((file (nth 1 parent-target))
11173 (pos (nth 3 parent-target))
11174 level)
11175 (with-current-buffer (or (find-buffer-visiting file)
11176 (find-file-noselect file))
11177 (save-excursion
11178 (save-restriction
11179 (widen)
11180 (if pos
11181 (goto-char pos)
11182 (goto-char (point-max))
11183 (if (not (bolp)) (newline)))
11184 (when (looking-at org-outline-regexp)
11185 (setq level (funcall outline-level))
11186 (org-end-of-subtree t t))
11187 (org-back-over-empty-lines)
11188 (insert "\n" (make-string
11189 (if pos (org-get-valid-level level 1) 1) ?*)
11190 " " child "\n")
11191 (beginning-of-line 0)
11192 (list (concat (car parent-target) "/" child) file "" (point)))))))
11194 (defun org-olpath-completing-read (prompt collection &rest args)
11195 "Read an outline path like a file name."
11196 (let ((thetable collection)
11197 (org-completion-use-ido nil) ; does not work with ido.
11198 (org-completion-use-iswitchb nil)) ; or iswitchb
11199 (apply
11200 'org-icompleting-read prompt
11201 (lambda (string predicate &optional flag)
11202 (let (rtn r f (l (length string)))
11203 (cond
11204 ((eq flag nil)
11205 ;; try completion
11206 (try-completion string thetable))
11207 ((eq flag t)
11208 ;; all-completions
11209 (setq rtn (all-completions string thetable predicate))
11210 (mapcar
11211 (lambda (x)
11212 (setq r (substring x l))
11213 (if (string-match " ([^)]*)$" x)
11214 (setq f (match-string 0 x))
11215 (setq f ""))
11216 (if (string-match "/" r)
11217 (concat string (substring r 0 (match-end 0)) f)
11219 rtn))
11220 ((eq flag 'lambda)
11221 ;; exact match?
11222 (assoc string thetable)))))
11223 args)))
11225 ;;;; Dynamic blocks
11227 (defun org-find-dblock (name)
11228 "Find the first dynamic block with name NAME in the buffer.
11229 If not found, stay at current position and return nil."
11230 (let ((case-fold-search t) pos)
11231 (save-excursion
11232 (goto-char (point-min))
11233 (setq pos (and (re-search-forward
11234 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11235 (match-beginning 0))))
11236 (if pos (goto-char pos))
11237 pos))
11239 (defconst org-dblock-start-re
11240 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11241 "Matches the start line of a dynamic block, with parameters.")
11243 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11244 "Matches the end of a dynamic block.")
11246 (defun org-create-dblock (plist)
11247 "Create a dynamic block section, with parameters taken from PLIST.
11248 PLIST must contain a :name entry which is used as name of the block."
11249 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11250 (end-of-line 1)
11251 (newline))
11252 (let ((col (current-column))
11253 (name (plist-get plist :name)))
11254 (insert "#+BEGIN: " name)
11255 (while plist
11256 (if (eq (car plist) :name)
11257 (setq plist (cddr plist))
11258 (insert " " (prin1-to-string (pop plist)))))
11259 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11260 (beginning-of-line -2)))
11262 (defun org-prepare-dblock ()
11263 "Prepare dynamic block for refresh.
11264 This empties the block, puts the cursor at the insert position and returns
11265 the property list including an extra property :name with the block name."
11266 (unless (looking-at org-dblock-start-re)
11267 (error "Not at a dynamic block"))
11268 (let* ((begdel (1+ (match-end 0)))
11269 (name (org-no-properties (match-string 1)))
11270 (params (append (list :name name)
11271 (read (concat "(" (match-string 3) ")")))))
11272 (save-excursion
11273 (beginning-of-line 1)
11274 (skip-chars-forward " \t")
11275 (setq params (plist-put params :indentation-column (current-column))))
11276 (unless (re-search-forward org-dblock-end-re nil t)
11277 (error "Dynamic block not terminated"))
11278 (setq params
11279 (append params
11280 (list :content (buffer-substring
11281 begdel (match-beginning 0)))))
11282 (delete-region begdel (match-beginning 0))
11283 (goto-char begdel)
11284 (open-line 1)
11285 params))
11287 (defun org-map-dblocks (&optional command)
11288 "Apply COMMAND to all dynamic blocks in the current buffer.
11289 If COMMAND is not given, use `org-update-dblock'."
11290 (let ((cmd (or command 'org-update-dblock)))
11291 (save-excursion
11292 (goto-char (point-min))
11293 (while (re-search-forward org-dblock-start-re nil t)
11294 (goto-char (match-beginning 0))
11295 (save-excursion
11296 (condition-case nil
11297 (funcall cmd)
11298 (error (message "Error during update of dynamic block"))))
11299 (unless (re-search-forward org-dblock-end-re nil t)
11300 (error "Dynamic block not terminated"))))))
11302 (defun org-dblock-update (&optional arg)
11303 "User command for updating dynamic blocks.
11304 Update the dynamic block at point. With prefix ARG, update all dynamic
11305 blocks in the buffer."
11306 (interactive "P")
11307 (if arg
11308 (org-update-all-dblocks)
11309 (or (looking-at org-dblock-start-re)
11310 (org-beginning-of-dblock))
11311 (org-update-dblock)))
11313 (defun org-update-dblock ()
11314 "Update the dynamic block at point.
11315 This means to empty the block, parse for parameters and then call
11316 the correct writing function."
11317 (interactive)
11318 (save-window-excursion
11319 (let* ((pos (point))
11320 (line (org-current-line))
11321 (params (org-prepare-dblock))
11322 (name (plist-get params :name))
11323 (indent (plist-get params :indentation-column))
11324 (cmd (intern (concat "org-dblock-write:" name))))
11325 (message "Updating dynamic block `%s' at line %d..." name line)
11326 (funcall cmd params)
11327 (message "Updating dynamic block `%s' at line %d...done" name line)
11328 (goto-char pos)
11329 (when (and indent (> indent 0))
11330 (setq indent (make-string indent ?\ ))
11331 (save-excursion
11332 (org-beginning-of-dblock)
11333 (forward-line 1)
11334 (while (not (looking-at org-dblock-end-re))
11335 (insert indent)
11336 (beginning-of-line 2))
11337 (when (looking-at org-dblock-end-re)
11338 (and (looking-at "[ \t]+")
11339 (replace-match ""))
11340 (insert indent)))))))
11342 (defun org-beginning-of-dblock ()
11343 "Find the beginning of the dynamic block at point.
11344 Error if there is no such block at point."
11345 (let ((pos (point))
11346 beg)
11347 (end-of-line 1)
11348 (if (and (re-search-backward org-dblock-start-re nil t)
11349 (setq beg (match-beginning 0))
11350 (re-search-forward org-dblock-end-re nil t)
11351 (> (match-end 0) pos))
11352 (goto-char beg)
11353 (goto-char pos)
11354 (error "Not in a dynamic block"))))
11356 ;;;###autoload
11357 (defun org-update-all-dblocks ()
11358 "Update all dynamic blocks in the buffer.
11359 This function can be used in a hook."
11360 (interactive)
11361 (when (derived-mode-p 'org-mode)
11362 (org-map-dblocks 'org-update-dblock)))
11365 ;;;; Completion
11367 (defconst org-additional-option-like-keywords
11368 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11369 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11370 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11371 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11372 "BEGIN:" "END:"
11373 "ORGTBL" "TBLFM:" "TBLNAME:"
11374 "BEGIN_EXAMPLE" "END_EXAMPLE"
11375 "BEGIN_VERBATIM" "END_VERBATIM"
11376 "BEGIN_QUOTE" "END_QUOTE"
11377 "BEGIN_VERSE" "END_VERSE"
11378 "BEGIN_CENTER" "END_CENTER"
11379 "BEGIN_SRC" "END_SRC"
11380 "BEGIN_RESULT" "END_RESULT"
11381 "BEGIN_lstlisting" "END_lstlisting"
11382 "NAME:" "RESULTS:"
11383 "HEADER:" "HEADERS:"
11384 "COLUMNS:" "PROPERTY:"
11385 "CAPTION:" "LABEL:"
11386 "SETUPFILE:"
11387 "INCLUDE:"
11388 "BIND:"
11389 "MACRO:"))
11391 (defconst org-options-keywords
11392 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11393 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11394 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11395 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11396 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11397 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:"
11398 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11400 (defconst org-additional-option-like-keywords-for-flyspell
11401 (delete-dups
11402 (split-string
11403 (mapconcat (lambda(k)
11404 (replace-regexp-in-string
11405 "_\\|:" " "
11406 (concat k " " (downcase k) " " (upcase k))))
11407 (append org-options-keywords org-additional-option-like-keywords)
11408 " ")
11409 " +" t)))
11411 (defcustom org-structure-template-alist
11413 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11414 "<src lang=\"?\">\n\n</src>")
11415 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11416 "<example>\n?\n</example>")
11417 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11418 "<quote>\n?\n</quote>")
11419 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11420 "<verse>\n?\n</verse>")
11421 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11422 "<center>\n?\n</center>")
11423 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11424 "<literal style=\"latex\">\n?\n</literal>")
11425 ("L" "#+LaTeX: "
11426 "<literal style=\"latex\">?</literal>")
11427 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11428 "<literal style=\"html\">\n?\n</literal>")
11429 ("H" "#+HTML: "
11430 "<literal style=\"html\">?</literal>")
11431 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11432 ("A" "#+ASCII: ")
11433 ("i" "#+INDEX: ?"
11434 "#+INDEX: ?")
11435 ("I" "#+INCLUDE: %file ?"
11436 "<include file=%file markup=\"?\">")
11438 "Structure completion elements.
11439 This is a list of abbreviation keys and values. The value gets inserted
11440 if you type `<' followed by the key and then press the completion key,
11441 usually `M-TAB'. %file will be replaced by a file name after prompting
11442 for the file using completion. The cursor will be placed at the position
11443 of the `?` in the template.
11444 There are two templates for each key, the first uses the original Org syntax,
11445 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11446 the default when the /org-mtags.el/ module has been loaded. See also the
11447 variable `org-mtags-prefer-muse-templates'."
11448 :group 'org-completion
11449 :type '(repeat
11450 (string :tag "Key")
11451 (string :tag "Template")
11452 (string :tag "Muse Template")))
11454 (defun org-try-structure-completion ()
11455 "Try to complete a structure template before point.
11456 This looks for strings like \"<e\" on an otherwise empty line and
11457 expands them."
11458 (let ((l (buffer-substring (point-at-bol) (point)))
11460 (when (and (looking-at "[ \t]*$")
11461 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11462 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11463 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11464 (match-beginning 1)) a)
11465 t)))
11467 (defun org-complete-expand-structure-template (start cell)
11468 "Expand a structure template."
11469 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11470 (rpl (nth (if musep 2 1) cell))
11471 (ind ""))
11472 (delete-region start (point))
11473 (when (string-match "\\`#\\+" rpl)
11474 (cond
11475 ((bolp))
11476 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11477 (setq ind (buffer-substring (point-at-bol) (point))))
11478 (t (newline))))
11479 (setq start (point))
11480 (if (string-match "%file" rpl)
11481 (setq rpl (replace-match
11482 (concat
11483 "\""
11484 (save-match-data
11485 (abbreviate-file-name (read-file-name "Include file: ")))
11486 "\"")
11487 t t rpl)))
11488 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11489 (concat "\n" ind)))
11490 (insert rpl)
11491 (if (re-search-backward "\\?" start t) (delete-char 1))))
11493 ;;;; TODO, DEADLINE, Comments
11495 (defun org-toggle-comment ()
11496 "Change the COMMENT state of an entry."
11497 (interactive)
11498 (save-excursion
11499 (org-back-to-heading)
11500 (let (case-fold-search)
11501 (cond
11502 ((looking-at (format org-heading-keyword-regexp-format
11503 org-comment-string))
11504 (goto-char (match-end 1))
11505 (looking-at (concat " +" org-comment-string))
11506 (replace-match "" t t)
11507 (when (eolp) (insert " ")))
11508 ((looking-at org-outline-regexp)
11509 (goto-char (match-end 0))
11510 (insert org-comment-string " "))))))
11512 (defvar org-last-todo-state-is-todo nil
11513 "This is non-nil when the last TODO state change led to a TODO state.
11514 If the last change removed the TODO tag or switched to DONE, then
11515 this is nil.")
11517 (defvar org-setting-tags nil) ; dynamically skipped
11519 (defvar org-todo-setup-filter-hook nil
11520 "Hook for functions that pre-filter todo specs.
11521 Each function takes a todo spec and returns either nil or the spec
11522 transformed into canonical form." )
11524 (defvar org-todo-get-default-hook nil
11525 "Hook for functions that get a default item for todo.
11526 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11527 nil or a string to be used for the todo mark." )
11529 (defvar org-agenda-headline-snapshot-before-repeat)
11531 (defun org-current-effective-time ()
11532 "Return current time adjusted for `org-extend-today-until' variable."
11533 (let* ((ct (org-current-time))
11534 (dct (decode-time ct))
11535 (ct1
11536 (if (and org-use-effective-time
11537 (< (nth 2 dct) org-extend-today-until))
11538 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11539 ct)))
11540 ct1))
11542 (defun org-todo-yesterday (&optional arg)
11543 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11544 (interactive "P")
11545 (if (eq major-mode 'org-agenda-mode)
11546 (apply 'org-agenda-todo-yesterday arg)
11547 (let* ((hour (third (decode-time
11548 (org-current-time))))
11549 (org-extend-today-until (1+ hour)))
11550 (org-todo arg))))
11552 (defun org-todo (&optional arg)
11553 "Change the TODO state of an item.
11554 The state of an item is given by a keyword at the start of the heading,
11555 like
11556 *** TODO Write paper
11557 *** DONE Call mom
11559 The different keywords are specified in the variable `org-todo-keywords'.
11560 By default the available states are \"TODO\" and \"DONE\".
11561 So for this example: when the item starts with TODO, it is changed to DONE.
11562 When it starts with DONE, the DONE is removed. And when neither TODO nor
11563 DONE are present, add TODO at the beginning of the heading.
11565 With \\[universal-argument] prefix arg, use completion to determine the new \
11566 state.
11567 With numeric prefix arg, switch to that state.
11568 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11569 keywords (nextset).
11570 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11571 With a numeric prefix arg of 0, inhibit note taking for the change.
11573 For calling through lisp, arg is also interpreted in the following way:
11574 'none -> empty state
11575 \"\"(empty string) -> switch to empty state
11576 'done -> switch to DONE
11577 'nextset -> switch to the next set of keywords
11578 'previousset -> switch to the previous set of keywords
11579 \"WAITING\" -> switch to the specified keyword, but only if it
11580 really is a member of `org-todo-keywords'."
11581 (interactive "P")
11582 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11583 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11584 'region-start-level 'region))
11585 org-loop-over-headlines-in-active-region)
11586 (org-map-entries
11587 `(org-todo ,arg)
11588 org-loop-over-headlines-in-active-region
11589 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11590 (if (equal arg '(16)) (setq arg 'nextset))
11591 (let ((org-blocker-hook org-blocker-hook)
11592 (case-fold-search nil))
11593 (when (equal arg '(64))
11594 (setq arg nil org-blocker-hook nil))
11595 (when (and org-blocker-hook
11596 (or org-inhibit-blocking
11597 (org-entry-get nil "NOBLOCKING")))
11598 (setq org-blocker-hook nil))
11599 (save-excursion
11600 (catch 'exit
11601 (org-back-to-heading t)
11602 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11603 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11604 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11605 (let* ((match-data (match-data))
11606 (startpos (point-at-bol))
11607 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11608 (org-log-done org-log-done)
11609 (org-log-repeat org-log-repeat)
11610 (org-todo-log-states org-todo-log-states)
11611 (org-inhibit-logging
11612 (if (equal arg 0)
11613 (progn (setq arg nil) 'note) org-inhibit-logging))
11614 (this (match-string 1))
11615 (hl-pos (match-beginning 0))
11616 (head (org-get-todo-sequence-head this))
11617 (ass (assoc head org-todo-kwd-alist))
11618 (interpret (nth 1 ass))
11619 (done-word (nth 3 ass))
11620 (final-done-word (nth 4 ass))
11621 (org-last-state (or this ""))
11622 (completion-ignore-case t)
11623 (member (member this org-todo-keywords-1))
11624 (tail (cdr member))
11625 (org-state (cond
11626 ((and org-todo-key-trigger
11627 (or (and (equal arg '(4))
11628 (eq org-use-fast-todo-selection 'prefix))
11629 (and (not arg) org-use-fast-todo-selection
11630 (not (eq org-use-fast-todo-selection
11631 'prefix)))))
11632 ;; Use fast selection
11633 (org-fast-todo-selection))
11634 ((and (equal arg '(4))
11635 (or (not org-use-fast-todo-selection)
11636 (not org-todo-key-trigger)))
11637 ;; Read a state with completion
11638 (org-icompleting-read
11639 "State: " (mapcar (lambda(x) (list x))
11640 org-todo-keywords-1)
11641 nil t))
11642 ((eq arg 'right)
11643 (if this
11644 (if tail (car tail) nil)
11645 (car org-todo-keywords-1)))
11646 ((eq arg 'left)
11647 (if (equal member org-todo-keywords-1)
11649 (if this
11650 (nth (- (length org-todo-keywords-1)
11651 (length tail) 2)
11652 org-todo-keywords-1)
11653 (org-last org-todo-keywords-1))))
11654 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11655 (setq arg nil))) ; hack to fall back to cycling
11656 (arg
11657 ;; user or caller requests a specific state
11658 (cond
11659 ((equal arg "") nil)
11660 ((eq arg 'none) nil)
11661 ((eq arg 'done) (or done-word (car org-done-keywords)))
11662 ((eq arg 'nextset)
11663 (or (car (cdr (member head org-todo-heads)))
11664 (car org-todo-heads)))
11665 ((eq arg 'previousset)
11666 (let ((org-todo-heads (reverse org-todo-heads)))
11667 (or (car (cdr (member head org-todo-heads)))
11668 (car org-todo-heads))))
11669 ((car (member arg org-todo-keywords-1)))
11670 ((stringp arg)
11671 (error "State `%s' not valid in this file" arg))
11672 ((nth (1- (prefix-numeric-value arg))
11673 org-todo-keywords-1))))
11674 ((null member) (or head (car org-todo-keywords-1)))
11675 ((equal this final-done-word) nil) ;; -> make empty
11676 ((null tail) nil) ;; -> first entry
11677 ((memq interpret '(type priority))
11678 (if (eq this-command last-command)
11679 (car tail)
11680 (if (> (length tail) 0)
11681 (or done-word (car org-done-keywords))
11682 nil)))
11684 (car tail))))
11685 (org-state (or
11686 (run-hook-with-args-until-success
11687 'org-todo-get-default-hook org-state org-last-state)
11688 org-state))
11689 (next (if org-state (concat " " org-state " ") " "))
11690 (change-plist (list :type 'todo-state-change :from this :to org-state
11691 :position startpos))
11692 dolog now-done-p)
11693 (when org-blocker-hook
11694 (setq org-last-todo-state-is-todo
11695 (not (member this org-done-keywords)))
11696 (unless (save-excursion
11697 (save-match-data
11698 (org-with-wide-buffer
11699 (run-hook-with-args-until-failure
11700 'org-blocker-hook change-plist))))
11701 (if (org-called-interactively-p 'interactive)
11702 (error "TODO state change from %s to %s blocked" this org-state)
11703 ;; fail silently
11704 (message "TODO state change from %s to %s blocked" this org-state)
11705 (throw 'exit nil))))
11706 (store-match-data match-data)
11707 (replace-match next t t)
11708 (unless (pos-visible-in-window-p hl-pos)
11709 (message "TODO state changed to %s" (org-trim next)))
11710 (unless head
11711 (setq head (org-get-todo-sequence-head org-state)
11712 ass (assoc head org-todo-kwd-alist)
11713 interpret (nth 1 ass)
11714 done-word (nth 3 ass)
11715 final-done-word (nth 4 ass)))
11716 (when (memq arg '(nextset previousset))
11717 (message "Keyword-Set %d/%d: %s"
11718 (- (length org-todo-sets) -1
11719 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11720 (length org-todo-sets)
11721 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11722 (setq org-last-todo-state-is-todo
11723 (not (member org-state org-done-keywords)))
11724 (setq now-done-p (and (member org-state org-done-keywords)
11725 (not (member this org-done-keywords))))
11726 (and logging (org-local-logging logging))
11727 (when (and (or org-todo-log-states org-log-done)
11728 (not (eq org-inhibit-logging t))
11729 (not (memq arg '(nextset previousset))))
11730 ;; we need to look at recording a time and note
11731 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11732 (nth 2 (assoc this org-todo-log-states))))
11733 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11734 (setq dolog 'time))
11735 (when (and org-state
11736 (member org-state org-not-done-keywords)
11737 (not (member this org-not-done-keywords)))
11738 ;; This is now a todo state and was not one before
11739 ;; If there was a CLOSED time stamp, get rid of it.
11740 (org-add-planning-info nil nil 'closed))
11741 (when (and now-done-p org-log-done)
11742 ;; It is now done, and it was not done before
11743 (org-add-planning-info 'closed (org-current-effective-time))
11744 (if (and (not dolog) (eq 'note org-log-done))
11745 (org-add-log-setup 'done org-state this 'findpos 'note)))
11746 (when (and org-state dolog)
11747 ;; This is a non-nil state, and we need to log it
11748 (org-add-log-setup 'state org-state this 'findpos dolog)))
11749 ;; Fixup tag positioning
11750 (org-todo-trigger-tag-changes org-state)
11751 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11752 (when org-provide-todo-statistics
11753 (org-update-parent-todo-statistics))
11754 (run-hooks 'org-after-todo-state-change-hook)
11755 (if (and arg (not (member org-state org-done-keywords)))
11756 (setq head (org-get-todo-sequence-head org-state)))
11757 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11758 ;; Do we need to trigger a repeat?
11759 (when now-done-p
11760 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11761 ;; This is for the agenda, take a snapshot of the headline.
11762 (save-match-data
11763 (setq org-agenda-headline-snapshot-before-repeat
11764 (org-get-heading))))
11765 (org-auto-repeat-maybe org-state))
11766 ;; Fixup cursor location if close to the keyword
11767 (if (and (outline-on-heading-p)
11768 (not (bolp))
11769 (save-excursion (beginning-of-line 1)
11770 (looking-at org-todo-line-regexp))
11771 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11772 (progn
11773 (goto-char (or (match-end 2) (match-end 1)))
11774 (and (looking-at " ") (just-one-space))))
11775 (when org-trigger-hook
11776 (save-excursion
11777 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11779 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11780 "Block turning an entry into a TODO, using the hierarchy.
11781 This checks whether the current task should be blocked from state
11782 changes. Such blocking occurs when:
11784 1. The task has children which are not all in a completed state.
11786 2. A task has a parent with the property :ORDERED:, and there
11787 are siblings prior to the current task with incomplete
11788 status.
11790 3. The parent of the task is blocked because it has siblings that should
11791 be done first, or is child of a block grandparent TODO entry."
11793 (if (not org-enforce-todo-dependencies)
11794 t ; if locally turned off don't block
11795 (catch 'dont-block
11796 ;; If this is not a todo state change, or if this entry is already DONE,
11797 ;; do not block
11798 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11799 (member (plist-get change-plist :from)
11800 (cons 'done org-done-keywords))
11801 (member (plist-get change-plist :to)
11802 (cons 'todo org-not-done-keywords))
11803 (not (plist-get change-plist :to)))
11804 (throw 'dont-block t))
11805 ;; If this task has children, and any are undone, it's blocked
11806 (save-excursion
11807 (org-back-to-heading t)
11808 (let ((this-level (funcall outline-level)))
11809 (outline-next-heading)
11810 (let ((child-level (funcall outline-level)))
11811 (while (and (not (eobp))
11812 (> child-level this-level))
11813 ;; this todo has children, check whether they are all
11814 ;; completed
11815 (if (and (not (org-entry-is-done-p))
11816 (org-entry-is-todo-p))
11817 (throw 'dont-block nil))
11818 (outline-next-heading)
11819 (setq child-level (funcall outline-level))))))
11820 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11821 ;; any previous siblings are undone, it's blocked
11822 (save-excursion
11823 (org-back-to-heading t)
11824 (let* ((pos (point))
11825 (parent-pos (and (org-up-heading-safe) (point))))
11826 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11827 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11828 (forward-line 1)
11829 (re-search-forward org-not-done-heading-regexp pos t))
11830 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11831 ;; Search further up the hierarchy, to see if an ancestor is blocked
11832 (while t
11833 (goto-char parent-pos)
11834 (if (not (looking-at org-not-done-heading-regexp))
11835 (throw 'dont-block t)) ; do not block, parent is not a TODO
11836 (setq pos (point))
11837 (setq parent-pos (and (org-up-heading-safe) (point)))
11838 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11839 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11840 (forward-line 1)
11841 (re-search-forward org-not-done-heading-regexp pos t))
11842 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11844 (defcustom org-track-ordered-property-with-tag nil
11845 "Should the ORDERED property also be shown as a tag?
11846 The ORDERED property decides if an entry should require subtasks to be
11847 completed in sequence. Since a property is not very visible, setting
11848 this option means that toggling the ORDERED property with the command
11849 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11850 not relevant for the behavior, but it makes things more visible.
11852 Note that toggling the tag with tags commands will not change the property
11853 and therefore not influence behavior!
11855 This can be t, meaning the tag ORDERED should be used, It can also be a
11856 string to select a different tag for this task."
11857 :group 'org-todo
11858 :type '(choice
11859 (const :tag "No tracking" nil)
11860 (const :tag "Track with ORDERED tag" t)
11861 (string :tag "Use other tag")))
11863 (defun org-toggle-ordered-property ()
11864 "Toggle the ORDERED property of the current entry.
11865 For better visibility, you can track the value of this property with a tag.
11866 See variable `org-track-ordered-property-with-tag'."
11867 (interactive)
11868 (let* ((t1 org-track-ordered-property-with-tag)
11869 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11870 (save-excursion
11871 (org-back-to-heading)
11872 (if (org-entry-get nil "ORDERED")
11873 (progn
11874 (org-delete-property "ORDERED")
11875 (and tag (org-toggle-tag tag 'off))
11876 (message "Subtasks can be completed in arbitrary order"))
11877 (org-entry-put nil "ORDERED" "t")
11878 (and tag (org-toggle-tag tag 'on))
11879 (message "Subtasks must be completed in sequence")))))
11881 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11882 (defun org-block-todo-from-checkboxes (change-plist)
11883 "Block turning an entry into a TODO, using checkboxes.
11884 This checks whether the current task should be blocked from state
11885 changes because there are unchecked boxes in this entry."
11886 (if (not org-enforce-todo-checkbox-dependencies)
11887 t ; if locally turned off don't block
11888 (catch 'dont-block
11889 ;; If this is not a todo state change, or if this entry is already DONE,
11890 ;; do not block
11891 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11892 (member (plist-get change-plist :from)
11893 (cons 'done org-done-keywords))
11894 (member (plist-get change-plist :to)
11895 (cons 'todo org-not-done-keywords))
11896 (not (plist-get change-plist :to)))
11897 (throw 'dont-block t))
11898 ;; If this task has checkboxes that are not checked, it's blocked
11899 (save-excursion
11900 (org-back-to-heading t)
11901 (let ((beg (point)) end)
11902 (outline-next-heading)
11903 (setq end (point))
11904 (goto-char beg)
11905 (if (org-list-search-forward
11906 (concat (org-item-beginning-re)
11907 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11908 "\\[[- ]\\]")
11909 end t)
11910 (progn
11911 (if (boundp 'org-blocked-by-checkboxes)
11912 (setq org-blocked-by-checkboxes t))
11913 (throw 'dont-block nil)))))
11914 t))) ; do not block
11916 (defun org-entry-blocked-p ()
11917 "Is the current entry blocked?"
11918 (if (org-entry-get nil "NOBLOCKING")
11919 nil ;; Never block this entry
11920 (not
11921 (run-hook-with-args-until-failure
11922 'org-blocker-hook
11923 (list :type 'todo-state-change
11924 :position (point)
11925 :from 'todo
11926 :to 'done)))))
11928 (defun org-update-statistics-cookies (all)
11929 "Update the statistics cookie, either from TODO or from checkboxes.
11930 This should be called with the cursor in a line with a statistics cookie."
11931 (interactive "P")
11932 (if all
11933 (progn
11934 (org-update-checkbox-count 'all)
11935 (org-map-entries 'org-update-parent-todo-statistics))
11936 (if (not (org-at-heading-p))
11937 (org-update-checkbox-count)
11938 (let ((pos (move-marker (make-marker) (point)))
11939 end l1 l2)
11940 (ignore-errors (org-back-to-heading t))
11941 (if (not (org-at-heading-p))
11942 (org-update-checkbox-count)
11943 (setq l1 (org-outline-level))
11944 (setq end (save-excursion
11945 (outline-next-heading)
11946 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11947 (point)))
11948 (if (and (save-excursion
11949 (re-search-forward
11950 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11951 (not (save-excursion (re-search-forward
11952 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11953 (org-update-checkbox-count)
11954 (if (and l2 (> l2 l1))
11955 (progn
11956 (goto-char end)
11957 (org-update-parent-todo-statistics))
11958 (goto-char pos)
11959 (beginning-of-line 1)
11960 (while (re-search-forward
11961 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11962 (point-at-eol) t)
11963 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11964 (goto-char pos)
11965 (move-marker pos nil)))))
11967 (defvar org-entry-property-inherited-from) ;; defined below
11968 (defun org-update-parent-todo-statistics ()
11969 "Update any statistics cookie in the parent of the current headline.
11970 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11971 the entire subtree and this will travel up the hierarchy and update
11972 statistics everywhere."
11973 (let* ((prop (save-excursion (org-up-heading-safe)
11974 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11975 (recursive (or (not org-hierarchical-todo-statistics)
11976 (and prop (string-match "\\<recursive\\>" prop))))
11977 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11979 (first t)
11980 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11981 level ltoggle l1 new ndel
11982 (cnt-all 0) (cnt-done 0) is-percent kwd
11983 checkbox-beg ov ovs ove cookie-present)
11984 (catch 'exit
11985 (save-excursion
11986 (beginning-of-line 1)
11987 (setq ltoggle (funcall outline-level))
11988 ;; Three situations are to consider:
11990 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11991 ;; to the top-level ancestor on the headline;
11993 ;; 2. If parent has "recursive" property, repeat up to the
11994 ;; headline setting that property, taking inheritance into
11995 ;; account;
11997 ;; 3. Else, move up to direct parent and proceed only once.
11998 (while (and (setq level (org-up-heading-safe))
11999 (or recursive first)
12000 (>= (point) lim))
12001 (setq first nil cookie-present nil)
12002 (unless (and level
12003 (not (string-match
12004 "\\<checkbox\\>"
12005 (downcase (or (org-entry-get nil "COOKIE_DATA")
12006 "")))))
12007 (throw 'exit nil))
12008 (while (re-search-forward box-re (point-at-eol) t)
12009 (setq cnt-all 0 cnt-done 0 cookie-present t)
12010 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12011 (save-match-data
12012 (unless (outline-next-heading) (throw 'exit nil))
12013 (while (and (looking-at org-complex-heading-regexp)
12014 (> (setq l1 (length (match-string 1))) level))
12015 (setq kwd (and (or recursive (= l1 ltoggle))
12016 (match-string 2)))
12017 (if (or (eq org-provide-todo-statistics 'all-headlines)
12018 (and (listp org-provide-todo-statistics)
12019 (or (member kwd org-provide-todo-statistics)
12020 (member kwd org-done-keywords))))
12021 (setq cnt-all (1+ cnt-all))
12022 (if (eq org-provide-todo-statistics t)
12023 (and kwd (setq cnt-all (1+ cnt-all)))))
12024 (and (member kwd org-done-keywords)
12025 (setq cnt-done (1+ cnt-done)))
12026 (outline-next-heading)))
12027 (setq new
12028 (if is-percent
12029 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12030 (format "[%d/%d]" cnt-done cnt-all))
12031 ndel (- (match-end 0) checkbox-beg))
12032 ;; handle overlays when updating cookie from column view
12033 (when (setq ov (car (overlays-at checkbox-beg)))
12034 (setq ovs (overlay-start ov) ove (overlay-end ov))
12035 (delete-overlay ov))
12036 (goto-char checkbox-beg)
12037 (insert new)
12038 (delete-region (point) (+ (point) ndel))
12039 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12040 (when ov (move-overlay ov ovs ove)))
12041 (when cookie-present
12042 (run-hook-with-args 'org-after-todo-statistics-hook
12043 cnt-done (- cnt-all cnt-done))))))
12044 (run-hooks 'org-todo-statistics-hook)))
12046 (defvar org-after-todo-statistics-hook nil
12047 "Hook that is called after a TODO statistics cookie has been updated.
12048 Each function is called with two arguments: the number of not-done entries
12049 and the number of done entries.
12051 For example, the following function, when added to this hook, will switch
12052 an entry to DONE when all children are done, and back to TODO when new
12053 entries are set to a TODO status. Note that this hook is only called
12054 when there is a statistics cookie in the headline!
12056 (defun org-summary-todo (n-done n-not-done)
12057 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12058 (let (org-log-done org-log-states) ; turn off logging
12059 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12062 (defvar org-todo-statistics-hook nil
12063 "Hook that is run whenever Org thinks TODO statistics should be updated.
12064 This hook runs even if there is no statistics cookie present, in which case
12065 `org-after-todo-statistics-hook' would not run.")
12067 (defun org-todo-trigger-tag-changes (state)
12068 "Apply the changes defined in `org-todo-state-tags-triggers'."
12069 (let ((l org-todo-state-tags-triggers)
12070 changes)
12071 (when (or (not state) (equal state ""))
12072 (setq changes (append changes (cdr (assoc "" l)))))
12073 (when (and (stringp state) (> (length state) 0))
12074 (setq changes (append changes (cdr (assoc state l)))))
12075 (when (member state org-not-done-keywords)
12076 (setq changes (append changes (cdr (assoc 'todo l)))))
12077 (when (member state org-done-keywords)
12078 (setq changes (append changes (cdr (assoc 'done l)))))
12079 (dolist (c changes)
12080 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12082 (defun org-local-logging (value)
12083 "Get logging settings from a property VALUE."
12084 (let* (words w a)
12085 ;; directly set the variables, they are already local.
12086 (setq org-log-done nil
12087 org-log-repeat nil
12088 org-todo-log-states nil)
12089 (setq words (org-split-string value))
12090 (while (setq w (pop words))
12091 (cond
12092 ((setq a (assoc w org-startup-options))
12093 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12094 (set (nth 1 a) (nth 2 a))))
12095 ((setq a (org-extract-log-state-settings w))
12096 (and (member (car a) org-todo-keywords-1)
12097 (push a org-todo-log-states)))))))
12099 (defun org-get-todo-sequence-head (kwd)
12100 "Return the head of the TODO sequence to which KWD belongs.
12101 If KWD is not set, check if there is a text property remembering the
12102 right sequence."
12103 (let (p)
12104 (cond
12105 ((not kwd)
12106 (or (get-text-property (point-at-bol) 'org-todo-head)
12107 (progn
12108 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12109 nil (point-at-eol)))
12110 (get-text-property p 'org-todo-head))))
12111 ((not (member kwd org-todo-keywords-1))
12112 (car org-todo-keywords-1))
12113 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12115 (defun org-fast-todo-selection ()
12116 "Fast TODO keyword selection with single keys.
12117 Returns the new TODO keyword, or nil if no state change should occur."
12118 (let* ((fulltable org-todo-key-alist)
12119 (done-keywords org-done-keywords) ;; needed for the faces.
12120 (maxlen (apply 'max (mapcar
12121 (lambda (x)
12122 (if (stringp (car x)) (string-width (car x)) 0))
12123 fulltable)))
12124 (expert nil)
12125 (fwidth (+ maxlen 3 1 3))
12126 (ncol (/ (- (window-width) 4) fwidth))
12127 tg cnt e c tbl
12128 groups ingroup)
12129 (save-excursion
12130 (save-window-excursion
12131 (if expert
12132 (set-buffer (get-buffer-create " *Org todo*"))
12133 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12134 (erase-buffer)
12135 (org-set-local 'org-done-keywords done-keywords)
12136 (setq tbl fulltable cnt 0)
12137 (while (setq e (pop tbl))
12138 (cond
12139 ((equal e '(:startgroup))
12140 (push '() groups) (setq ingroup t)
12141 (when (not (= cnt 0))
12142 (setq cnt 0)
12143 (insert "\n"))
12144 (insert "{ "))
12145 ((equal e '(:endgroup))
12146 (setq ingroup nil cnt 0)
12147 (insert "}\n"))
12148 ((equal e '(:newline))
12149 (when (not (= cnt 0))
12150 (setq cnt 0)
12151 (insert "\n")
12152 (setq e (car tbl))
12153 (while (equal (car tbl) '(:newline))
12154 (insert "\n")
12155 (setq tbl (cdr tbl)))))
12157 (setq tg (car e) c (cdr e))
12158 (if ingroup (push tg (car groups)))
12159 (setq tg (org-add-props tg nil 'face
12160 (org-get-todo-face tg)))
12161 (if (and (= cnt 0) (not ingroup)) (insert " "))
12162 (insert "[" c "] " tg (make-string
12163 (- fwidth 4 (length tg)) ?\ ))
12164 (when (= (setq cnt (1+ cnt)) ncol)
12165 (insert "\n")
12166 (if ingroup (insert " "))
12167 (setq cnt 0)))))
12168 (insert "\n")
12169 (goto-char (point-min))
12170 (if (not expert) (org-fit-window-to-buffer))
12171 (message "[a-z..]:Set [SPC]:clear")
12172 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12173 (cond
12174 ((or (= c ?\C-g)
12175 (and (= c ?q) (not (rassoc c fulltable))))
12176 (setq quit-flag t))
12177 ((= c ?\ ) nil)
12178 ((setq e (rassoc c fulltable) tg (car e))
12180 (t (setq quit-flag t)))))))
12182 (defun org-entry-is-todo-p ()
12183 (member (org-get-todo-state) org-not-done-keywords))
12185 (defun org-entry-is-done-p ()
12186 (member (org-get-todo-state) org-done-keywords))
12188 (defun org-get-todo-state ()
12189 (save-excursion
12190 (org-back-to-heading t)
12191 (and (looking-at org-todo-line-regexp)
12192 (match-end 2)
12193 (match-string 2))))
12195 (defun org-at-date-range-p (&optional inactive-ok)
12196 "Is the cursor inside a date range?"
12197 (interactive)
12198 (save-excursion
12199 (catch 'exit
12200 (let ((pos (point)))
12201 (skip-chars-backward "^[<\r\n")
12202 (skip-chars-backward "<[")
12203 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12204 (>= (match-end 0) pos)
12205 (throw 'exit t))
12206 (skip-chars-backward "^<[\r\n")
12207 (skip-chars-backward "<[")
12208 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12209 (>= (match-end 0) pos)
12210 (throw 'exit t)))
12211 nil)))
12213 (defun org-get-repeat (&optional tagline)
12214 "Check if there is a deadline/schedule with repeater in this entry."
12215 (save-match-data
12216 (save-excursion
12217 (org-back-to-heading t)
12218 (and (re-search-forward (if tagline
12219 (concat tagline "\\s-*" org-repeat-re)
12220 org-repeat-re)
12221 (org-entry-end-position) t)
12222 (match-string-no-properties 1)))))
12224 (defvar org-last-changed-timestamp)
12225 (defvar org-last-inserted-timestamp)
12226 (defvar org-log-post-message)
12227 (defvar org-log-note-purpose)
12228 (defvar org-log-note-how)
12229 (defvar org-log-note-extra)
12230 (defun org-auto-repeat-maybe (done-word)
12231 "Check if the current headline contains a repeated deadline/schedule.
12232 If yes, set TODO state back to what it was and change the base date
12233 of repeating deadline/scheduled time stamps to new date.
12234 This function is run automatically after each state change to a DONE state."
12235 ;; last-state is dynamically scoped into this function
12236 (let* ((repeat (org-get-repeat))
12237 (aa (assoc org-last-state org-todo-kwd-alist))
12238 (interpret (nth 1 aa))
12239 (head (nth 2 aa))
12240 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12241 (msg "Entry repeats: ")
12242 (org-log-done nil)
12243 (org-todo-log-states nil)
12244 re type n what ts time to-state)
12245 (when repeat
12246 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12247 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12248 org-todo-repeat-to-state))
12249 (unless (and to-state (member to-state org-todo-keywords-1))
12250 (setq to-state (if (eq interpret 'type) org-last-state head)))
12251 (org-todo to-state)
12252 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12253 (org-entry-put nil "LAST_REPEAT" (format-time-string
12254 (org-time-stamp-format t t))))
12255 (when org-log-repeat
12256 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12257 (memq 'org-add-log-note post-command-hook))
12258 ;; OK, we are already setup for some record
12259 (if (eq org-log-repeat 'note)
12260 ;; make sure we take a note, not only a time stamp
12261 (setq org-log-note-how 'note))
12262 ;; Set up for taking a record
12263 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12264 org-last-state
12265 'findpos org-log-repeat)))
12266 (org-back-to-heading t)
12267 (org-add-planning-info nil nil 'closed)
12268 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12269 org-deadline-time-regexp "\\)\\|\\("
12270 org-ts-regexp "\\)"))
12271 (while (re-search-forward
12272 re (save-excursion (outline-next-heading) (point)) t)
12273 (setq type (if (match-end 1) org-scheduled-string
12274 (if (match-end 3) org-deadline-string "Plain:"))
12275 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12276 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12277 (setq n (string-to-number (match-string 2 ts))
12278 what (match-string 3 ts))
12279 (if (equal what "w") (setq n (* n 7) what "d"))
12280 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12281 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12282 ;; Preparation, see if we need to modify the start date for the change
12283 (when (match-end 1)
12284 (setq time (save-match-data (org-time-string-to-time ts)))
12285 (cond
12286 ((equal (match-string 1 ts) ".")
12287 ;; Shift starting date to today
12288 (org-timestamp-change
12289 (- (org-today) (time-to-days time))
12290 'day))
12291 ((equal (match-string 1 ts) "+")
12292 (let ((nshiftmax 10) (nshift 0))
12293 (while (or (= nshift 0)
12294 (<= (time-to-days time)
12295 (time-to-days (current-time))))
12296 (when (= (incf nshift) nshiftmax)
12297 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12298 (error "Abort")))
12299 (org-timestamp-change n (cdr (assoc what whata)))
12300 (org-at-timestamp-p t)
12301 (setq ts (match-string 1))
12302 (setq time (save-match-data (org-time-string-to-time ts)))))
12303 (org-timestamp-change (- n) (cdr (assoc what whata)))
12304 ;; rematch, so that we have everything in place for the real shift
12305 (org-at-timestamp-p t)
12306 (setq ts (match-string 1))
12307 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12308 (org-timestamp-change n (cdr (assoc what whata)))
12309 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12310 (setq org-log-post-message msg)
12311 (message "%s" msg))))
12313 (defun org-show-todo-tree (arg)
12314 "Make a compact tree which shows all headlines marked with TODO.
12315 The tree will show the lines where the regexp matches, and all higher
12316 headlines above the match.
12317 With a \\[universal-argument] prefix, prompt for a regexp to match.
12318 With a numeric prefix N, construct a sparse tree for the Nth element
12319 of `org-todo-keywords-1'."
12320 (interactive "P")
12321 (let ((case-fold-search nil)
12322 (kwd-re
12323 (cond ((null arg) org-not-done-regexp)
12324 ((equal arg '(4))
12325 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12326 (mapcar 'list org-todo-keywords-1))))
12327 (concat "\\("
12328 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12329 "\\)\\>")))
12330 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12331 (regexp-quote (nth (1- (prefix-numeric-value arg))
12332 org-todo-keywords-1)))
12333 (t (error "Invalid prefix argument: %s" arg)))))
12334 (message "%d TODO entries found"
12335 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12337 (defun org-deadline (&optional remove time)
12338 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12339 With argument REMOVE, remove any deadline from the item.
12340 With argument TIME, set the deadline at the corresponding date. TIME
12341 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12342 (interactive "P")
12343 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12344 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12345 'region-start-level 'region))
12346 org-loop-over-headlines-in-active-region)
12347 (org-map-entries
12348 `(org-deadline ',remove ,time)
12349 org-loop-over-headlines-in-active-region
12350 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12351 (let* ((old-date (org-entry-get nil "DEADLINE"))
12352 (repeater (and old-date
12353 (string-match
12354 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12355 old-date)
12356 (match-string 1 old-date))))
12357 (if remove
12358 (progn
12359 (when (and old-date org-log-redeadline)
12360 (org-add-log-setup 'deldeadline nil old-date 'findpos
12361 org-log-redeadline))
12362 (org-remove-timestamp-with-keyword org-deadline-string)
12363 (message "Item no longer has a deadline."))
12364 (org-add-planning-info 'deadline time 'closed)
12365 (when (and old-date org-log-redeadline
12366 (not (equal old-date
12367 (substring org-last-inserted-timestamp 1 -1))))
12368 (org-add-log-setup 'redeadline nil old-date 'findpos
12369 org-log-redeadline))
12370 (when repeater
12371 (save-excursion
12372 (org-back-to-heading t)
12373 (when (re-search-forward (concat org-deadline-string " "
12374 org-last-inserted-timestamp)
12375 (save-excursion
12376 (outline-next-heading) (point)) t)
12377 (goto-char (1- (match-end 0)))
12378 (insert " " repeater)
12379 (setq org-last-inserted-timestamp
12380 (concat (substring org-last-inserted-timestamp 0 -1)
12381 " " repeater
12382 (substring org-last-inserted-timestamp -1))))))
12383 (message "Deadline on %s" org-last-inserted-timestamp)))))
12385 (defun org-schedule (&optional remove time)
12386 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12387 With argument REMOVE, remove any scheduling date from the item.
12388 With argument TIME, scheduled at the corresponding date. TIME can
12389 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12390 (interactive "P")
12391 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12392 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12393 'region-start-level 'region))
12394 org-loop-over-headlines-in-active-region)
12395 (org-map-entries
12396 `(org-schedule ',remove ,time)
12397 org-loop-over-headlines-in-active-region
12398 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12399 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12400 (repeater (and old-date
12401 (string-match
12402 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12403 old-date)
12404 (match-string 1 old-date))))
12405 (if remove
12406 (progn
12407 (when (and old-date org-log-reschedule)
12408 (org-add-log-setup 'delschedule nil old-date 'findpos
12409 org-log-reschedule))
12410 (org-remove-timestamp-with-keyword org-scheduled-string)
12411 (message "Item is no longer scheduled."))
12412 (org-add-planning-info 'scheduled time 'closed)
12413 (when (and old-date org-log-reschedule
12414 (not (equal old-date
12415 (substring org-last-inserted-timestamp 1 -1))))
12416 (org-add-log-setup 'reschedule nil old-date 'findpos
12417 org-log-reschedule))
12418 (when repeater
12419 (save-excursion
12420 (org-back-to-heading t)
12421 (when (re-search-forward (concat org-scheduled-string " "
12422 org-last-inserted-timestamp)
12423 (save-excursion
12424 (outline-next-heading) (point)) t)
12425 (goto-char (1- (match-end 0)))
12426 (insert " " repeater)
12427 (setq org-last-inserted-timestamp
12428 (concat (substring org-last-inserted-timestamp 0 -1)
12429 " " repeater
12430 (substring org-last-inserted-timestamp -1))))))
12431 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12433 (defun org-get-scheduled-time (pom &optional inherit)
12434 "Get the scheduled time as a time tuple, of a format suitable
12435 for calling org-schedule with, or if there is no scheduling,
12436 returns nil."
12437 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12438 (when time
12439 (apply 'encode-time (org-parse-time-string time)))))
12441 (defun org-get-deadline-time (pom &optional inherit)
12442 "Get the deadline as a time tuple, of a format suitable for
12443 calling org-deadline with, or if there is no scheduling, returns
12444 nil."
12445 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12446 (when time
12447 (apply 'encode-time (org-parse-time-string time)))))
12449 (defun org-remove-timestamp-with-keyword (keyword)
12450 "Remove all time stamps with KEYWORD in the current entry."
12451 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12452 beg)
12453 (save-excursion
12454 (org-back-to-heading t)
12455 (setq beg (point))
12456 (outline-next-heading)
12457 (while (re-search-backward re beg t)
12458 (replace-match "")
12459 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12460 (equal (char-before) ?\ ))
12461 (backward-delete-char 1)
12462 (if (string-match "^[ \t]*$" (buffer-substring
12463 (point-at-bol) (point-at-eol)))
12464 (delete-region (point-at-bol)
12465 (min (point-max) (1+ (point-at-eol))))))))))
12467 (defun org-add-planning-info (what &optional time &rest remove)
12468 "Insert new timestamp with keyword in the line directly after the headline.
12469 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12470 If non is given, the user is prompted for a date.
12471 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12472 be removed."
12473 (interactive)
12474 (let (org-time-was-given org-end-time-was-given ts
12475 end default-time default-input)
12477 (catch 'exit
12478 (when (and (memq what '(scheduled deadline))
12479 (or (not time)
12480 (and (stringp time)
12481 (string-match "^[-+]+[0-9]" time))))
12482 ;; Try to get a default date/time from existing timestamp
12483 (save-excursion
12484 (org-back-to-heading t)
12485 (setq end (save-excursion (outline-next-heading) (point)))
12486 (when (re-search-forward (if (eq what 'scheduled)
12487 org-scheduled-time-regexp
12488 org-deadline-time-regexp)
12489 end t)
12490 (setq ts (match-string 1)
12491 default-time
12492 (apply 'encode-time (org-parse-time-string ts))
12493 default-input (and ts (org-get-compact-tod ts))))))
12494 (when what
12495 (setq time
12496 (if (stringp time)
12497 ;; This is a string (relative or absolute), set proper date
12498 (apply 'encode-time
12499 (org-read-date-analyze
12500 time default-time (decode-time default-time)))
12501 ;; If necessary, get the time from the user
12502 (or time (org-read-date nil 'to-time nil nil
12503 default-time default-input)))))
12505 (when (and org-insert-labeled-timestamps-at-point
12506 (member what '(scheduled deadline)))
12507 (insert
12508 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12509 (org-insert-time-stamp time org-time-was-given
12510 nil nil nil (list org-end-time-was-given))
12511 (setq what nil))
12512 (save-excursion
12513 (save-restriction
12514 (let (col list elt ts buffer-invisibility-spec)
12515 (org-back-to-heading t)
12516 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12517 (goto-char (match-end 1))
12518 (setq col (current-column))
12519 (goto-char (match-end 0))
12520 (if (eobp) (insert "\n") (forward-char 1))
12521 (when (and (not what)
12522 (not (looking-at
12523 (concat "[ \t]*"
12524 org-keyword-time-not-clock-regexp))))
12525 ;; Nothing to add, nothing to remove...... :-)
12526 (throw 'exit nil))
12527 (if (and (not (looking-at org-outline-regexp))
12528 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12529 "[^\r\n]*"))
12530 (not (equal (match-string 1) org-clock-string)))
12531 (narrow-to-region (match-beginning 0) (match-end 0))
12532 (insert-before-markers "\n")
12533 (backward-char 1)
12534 (narrow-to-region (point) (point))
12535 (and org-adapt-indentation (org-indent-to-column col)))
12536 ;; Check if we have to remove something.
12537 (setq list (cons what remove))
12538 (while list
12539 (setq elt (pop list))
12540 (when (or (and (eq elt 'scheduled)
12541 (re-search-forward org-scheduled-time-regexp nil t))
12542 (and (eq elt 'deadline)
12543 (re-search-forward org-deadline-time-regexp nil t))
12544 (and (eq elt 'closed)
12545 (re-search-forward org-closed-time-regexp nil t)))
12546 (replace-match "")
12547 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12548 (and (looking-at "[ \t]+") (replace-match ""))
12549 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12550 (when what
12551 (insert
12552 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12553 (cond ((eq what 'scheduled) org-scheduled-string)
12554 ((eq what 'deadline) org-deadline-string)
12555 ((eq what 'closed) org-closed-string))
12556 " ")
12557 (setq ts (org-insert-time-stamp
12558 time
12559 (or org-time-was-given
12560 (and (eq what 'closed) org-log-done-with-time))
12561 (eq what 'closed)
12562 nil nil (list org-end-time-was-given)))
12563 (insert
12564 (if (not (or (bolp) (eq (char-before) ?\ )
12565 (memq (char-after) '(32 10))
12566 (eobp))) " " ""))
12567 (end-of-line 1))
12568 (goto-char (point-min))
12569 (widen)
12570 (if (and (looking-at "[ \t]*\n")
12571 (equal (char-before) ?\n))
12572 (delete-region (1- (point)) (point-at-eol)))
12573 ts))))))
12575 (defvar org-log-note-marker (make-marker))
12576 (defvar org-log-note-purpose nil)
12577 (defvar org-log-note-state nil)
12578 (defvar org-log-note-previous-state nil)
12579 (defvar org-log-note-how nil)
12580 (defvar org-log-note-extra nil)
12581 (defvar org-log-note-window-configuration nil)
12582 (defvar org-log-note-return-to (make-marker))
12583 (defvar org-log-note-effective-time nil
12584 "Remembered current time so that dynamically scoped
12585 `org-extend-today-until' affects tha timestamps in state change
12586 log")
12588 (defvar org-log-post-message nil
12589 "Message to be displayed after a log note has been stored.
12590 The auto-repeater uses this.")
12592 (defun org-add-note ()
12593 "Add a note to the current entry.
12594 This is done in the same way as adding a state change note."
12595 (interactive)
12596 (org-add-log-setup 'note nil nil 'findpos nil))
12598 (defvar org-property-end-re)
12599 (defun org-add-log-setup (&optional purpose state prev-state
12600 findpos how extra)
12601 "Set up the post command hook to take a note.
12602 If this is about to TODO state change, the new state is expected in STATE.
12603 When FINDPOS is non-nil, find the correct position for the note in
12604 the current entry. If not, assume that it can be inserted at point.
12605 HOW is an indicator what kind of note should be created.
12606 EXTRA is additional text that will be inserted into the notes buffer."
12607 (let* ((org-log-into-drawer (org-log-into-drawer))
12608 (drawer (cond ((stringp org-log-into-drawer)
12609 org-log-into-drawer)
12610 (org-log-into-drawer "LOGBOOK"))))
12611 (save-restriction
12612 (save-excursion
12613 (when findpos
12614 (org-back-to-heading t)
12615 (narrow-to-region (point) (save-excursion
12616 (outline-next-heading) (point)))
12617 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12618 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12619 "[^\r\n]*\\)?"))
12620 (goto-char (match-end 0))
12621 (cond
12622 (drawer
12623 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12624 nil t)
12625 (progn
12626 (goto-char (match-end 0))
12627 (or org-log-states-order-reversed
12628 (and (re-search-forward org-property-end-re nil t)
12629 (goto-char (1- (match-beginning 0))))))
12630 (insert "\n:" drawer ":\n:END:")
12631 (beginning-of-line 0)
12632 (org-indent-line)
12633 (beginning-of-line 2)
12634 (org-indent-line)
12635 (end-of-line 0)))
12636 ((and org-log-state-notes-insert-after-drawers
12637 (save-excursion
12638 (forward-line) (looking-at org-drawer-regexp)))
12639 (forward-line)
12640 (while (looking-at org-drawer-regexp)
12641 (goto-char (match-end 0))
12642 (re-search-forward org-property-end-re (point-max) t)
12643 (forward-line))
12644 (forward-line -1)))
12645 (unless org-log-states-order-reversed
12646 (and (= (char-after) ?\n) (forward-char 1))
12647 (org-skip-over-state-notes)
12648 (skip-chars-backward " \t\n\r")))
12649 (move-marker org-log-note-marker (point))
12650 (setq org-log-note-purpose purpose
12651 org-log-note-state state
12652 org-log-note-previous-state prev-state
12653 org-log-note-how how
12654 org-log-note-extra extra
12655 org-log-note-effective-time (org-current-effective-time))
12656 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12658 (defun org-skip-over-state-notes ()
12659 "Skip past the list of State notes in an entry."
12660 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12661 (when (ignore-errors (goto-char (org-in-item-p)))
12662 (let* ((struct (org-list-struct))
12663 (prevs (org-list-prevs-alist struct)))
12664 (while (looking-at "[ \t]*- State")
12665 (goto-char (or (org-list-get-next-item (point) struct prevs)
12666 (org-list-get-item-end (point) struct)))))))
12668 (defun org-add-log-note (&optional purpose)
12669 "Pop up a window for taking a note, and add this note later at point."
12670 (remove-hook 'post-command-hook 'org-add-log-note)
12671 (setq org-log-note-window-configuration (current-window-configuration))
12672 (delete-other-windows)
12673 (move-marker org-log-note-return-to (point))
12674 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12675 (goto-char org-log-note-marker)
12676 (org-switch-to-buffer-other-window "*Org Note*")
12677 (erase-buffer)
12678 (if (memq org-log-note-how '(time state))
12679 (let (current-prefix-arg) (org-store-log-note))
12680 (let ((org-inhibit-startup t)) (org-mode))
12681 (insert (format "# Insert note for %s.
12682 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12683 (cond
12684 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12685 ((eq org-log-note-purpose 'done) "closed todo item")
12686 ((eq org-log-note-purpose 'state)
12687 (format "state change from \"%s\" to \"%s\""
12688 (or org-log-note-previous-state "")
12689 (or org-log-note-state "")))
12690 ((eq org-log-note-purpose 'reschedule)
12691 "rescheduling")
12692 ((eq org-log-note-purpose 'delschedule)
12693 "no longer scheduled")
12694 ((eq org-log-note-purpose 'redeadline)
12695 "changing deadline")
12696 ((eq org-log-note-purpose 'deldeadline)
12697 "removing deadline")
12698 ((eq org-log-note-purpose 'refile)
12699 "refiling")
12700 ((eq org-log-note-purpose 'note)
12701 "this entry")
12702 (t (error "This should not happen")))))
12703 (if org-log-note-extra (insert org-log-note-extra))
12704 (org-set-local 'org-finish-function 'org-store-log-note)
12705 (run-hooks 'org-log-buffer-setup-hook)))
12707 (defvar org-note-abort nil) ; dynamically scoped
12708 (defun org-store-log-note ()
12709 "Finish taking a log note, and insert it to where it belongs."
12710 (let ((txt (buffer-string))
12711 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12712 lines ind bul)
12713 (kill-buffer (current-buffer))
12714 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12715 (setq txt (replace-match "" t t txt)))
12716 (if (string-match "\\s-+\\'" txt)
12717 (setq txt (replace-match "" t t txt)))
12718 (setq lines (org-split-string txt "\n"))
12719 (when (and note (string-match "\\S-" note))
12720 (setq note
12721 (org-replace-escapes
12722 note
12723 (list (cons "%u" (user-login-name))
12724 (cons "%U" user-full-name)
12725 (cons "%t" (format-time-string
12726 (org-time-stamp-format 'long 'inactive)
12727 org-log-note-effective-time))
12728 (cons "%T" (format-time-string
12729 (org-time-stamp-format 'long nil)
12730 org-log-note-effective-time))
12731 (cons "%d" (format-time-string
12732 (org-time-stamp-format nil 'inactive)
12733 org-log-note-effective-time))
12734 (cons "%D" (format-time-string
12735 (org-time-stamp-format nil nil)
12736 org-log-note-effective-time))
12737 (cons "%s" (if org-log-note-state
12738 (concat "\"" org-log-note-state "\"")
12739 ""))
12740 (cons "%S" (if org-log-note-previous-state
12741 (concat "\"" org-log-note-previous-state "\"")
12742 "\"\"")))))
12743 (if lines (setq note (concat note " \\\\")))
12744 (push note lines))
12745 (when (or current-prefix-arg org-note-abort)
12746 (when org-log-into-drawer
12747 (org-remove-empty-drawer-at
12748 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12749 org-log-note-marker))
12750 (setq lines nil))
12751 (when lines
12752 (with-current-buffer (marker-buffer org-log-note-marker)
12753 (save-excursion
12754 (goto-char org-log-note-marker)
12755 (move-marker org-log-note-marker nil)
12756 (end-of-line 1)
12757 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12758 (setq ind (save-excursion
12759 (if (ignore-errors (goto-char (org-in-item-p)))
12760 (let ((struct (org-list-struct)))
12761 (org-list-get-ind
12762 (org-list-get-top-point struct) struct))
12763 (skip-chars-backward " \r\t\n")
12764 (cond
12765 ((and (org-at-heading-p)
12766 org-adapt-indentation)
12767 (1+ (org-current-level)))
12768 ((org-at-heading-p) 0)
12769 (t (org-get-indentation))))))
12770 (setq bul (org-list-bullet-string "-"))
12771 (org-indent-line-to ind)
12772 (insert bul (pop lines))
12773 (let ((ind-body (+ (length bul) ind)))
12774 (while lines
12775 (insert "\n")
12776 (org-indent-line-to ind-body)
12777 (insert (pop lines))))
12778 (message "Note stored")
12779 (org-back-to-heading t)
12780 (org-cycle-hide-drawers 'children)))))
12781 (set-window-configuration org-log-note-window-configuration)
12782 (with-current-buffer (marker-buffer org-log-note-return-to)
12783 (goto-char org-log-note-return-to))
12784 (move-marker org-log-note-return-to nil)
12785 (and org-log-post-message (message "%s" org-log-post-message)))
12787 (defun org-remove-empty-drawer-at (drawer pos)
12788 "Remove an empty drawer DRAWER at position POS.
12789 POS may also be a marker."
12790 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12791 (save-excursion
12792 (save-restriction
12793 (widen)
12794 (goto-char pos)
12795 (if (org-in-regexp
12796 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12797 (replace-match ""))))))
12799 (defvar org-ts-type nil)
12800 (defun org-sparse-tree (&optional arg type)
12801 "Create a sparse tree, prompt for the details.
12802 This command can create sparse trees. You first need to select the type
12803 of match used to create the tree:
12805 t Show all TODO entries.
12806 T Show entries with a specific TODO keyword.
12807 m Show entries selected by a tags/property match.
12808 p Enter a property name and its value (both with completion on existing
12809 names/values) and show entries with that property.
12810 r Show entries matching a regular expression (`/' can be used as well).
12811 b Show deadlines and scheduled items before a date.
12812 a Show deadlines and scheduled items after a date.
12813 d Show deadlines due within `org-deadline-warning-days'.
12814 D Show deadlines and scheduled items between a date range."
12815 (interactive "P")
12816 (let (ans kwd value ts-type)
12817 (setq type (or type org-sparse-tree-default-date-type))
12818 (setq org-ts-type type)
12819 (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"
12820 (cond ((eq type 'all) "all timestamps")
12821 ((eq type 'scheduled) "only scheduled")
12822 ((eq type 'deadline) "only deadline")
12823 ((eq type 'active) "only active timestamps")
12824 ((eq type 'inactive) "only inactive timestamps")
12825 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12826 (t "scheduled/deadline")))
12827 (setq ans (read-char-exclusive))
12828 (cond
12829 ((equal ans ?c)
12830 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12831 ((equal ans ?d)
12832 (call-interactively 'org-check-deadlines))
12833 ((equal ans ?b)
12834 (call-interactively 'org-check-before-date))
12835 ((equal ans ?a)
12836 (call-interactively 'org-check-after-date))
12837 ((equal ans ?D)
12838 (call-interactively 'org-check-dates-range))
12839 ((equal ans ?t)
12840 (org-show-todo-tree nil))
12841 ((equal ans ?T)
12842 (org-show-todo-tree '(4)))
12843 ((member ans '(?T ?m))
12844 (call-interactively 'org-match-sparse-tree))
12845 ((member ans '(?p ?P))
12846 (setq kwd (org-icompleting-read "Property: "
12847 (mapcar 'list (org-buffer-property-keys))))
12848 (setq value (org-icompleting-read "Value: "
12849 (mapcar 'list (org-property-values kwd))))
12850 (unless (string-match "\\`{.*}\\'" value)
12851 (setq value (concat "\"" value "\"")))
12852 (org-match-sparse-tree arg (concat kwd "=" value)))
12853 ((member ans '(?r ?R ?/))
12854 (call-interactively 'org-occur))
12855 (t (error "No such sparse tree command \"%c\"" ans)))))
12857 (defvar org-occur-highlights nil
12858 "List of overlays used for occur matches.")
12859 (make-variable-buffer-local 'org-occur-highlights)
12860 (defvar org-occur-parameters nil
12861 "Parameters of the active org-occur calls.
12862 This is a list, each call to org-occur pushes as cons cell,
12863 containing the regular expression and the callback, onto the list.
12864 The list can contain several entries if `org-occur' has been called
12865 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12866 will only contain one set of parameters. When the highlights are
12867 removed (for example with `C-c C-c', or with the next edit (depending
12868 on `org-remove-highlights-with-change'), this variable is emptied
12869 as well.")
12870 (make-variable-buffer-local 'org-occur-parameters)
12872 (defun org-occur (regexp &optional keep-previous callback)
12873 "Make a compact tree which shows all matches of REGEXP.
12874 The tree will show the lines where the regexp matches, and all higher
12875 headlines above the match. It will also show the heading after the match,
12876 to make sure editing the matching entry is easy.
12877 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12878 call to `org-occur' will be kept, to allow stacking of calls to this
12879 command.
12880 If CALLBACK is non-nil, it is a function which is called to confirm
12881 that the match should indeed be shown."
12882 (interactive "sRegexp: \nP")
12883 (when (equal regexp "")
12884 (error "Regexp cannot be empty"))
12885 (unless keep-previous
12886 (org-remove-occur-highlights nil nil t))
12887 (push (cons regexp callback) org-occur-parameters)
12888 (let ((cnt 0))
12889 (save-excursion
12890 (goto-char (point-min))
12891 (if (or (not keep-previous) ; do not want to keep
12892 (not org-occur-highlights)) ; no previous matches
12893 ;; hide everything
12894 (org-overview))
12895 (while (re-search-forward regexp nil t)
12896 (when (or (not callback)
12897 (save-match-data (funcall callback)))
12898 (setq cnt (1+ cnt))
12899 (when org-highlight-sparse-tree-matches
12900 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12901 (org-show-context 'occur-tree))))
12902 (when org-remove-highlights-with-change
12903 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12904 nil 'local))
12905 (unless org-sparse-tree-open-archived-trees
12906 (org-hide-archived-subtrees (point-min) (point-max)))
12907 (run-hooks 'org-occur-hook)
12908 (if (org-called-interactively-p 'interactive)
12909 (message "%d match(es) for regexp %s" cnt regexp))
12910 cnt))
12912 (defun org-occur-next-match (&optional n reset)
12913 "Function for `next-error-function' to find sparse tree matches.
12914 N is the number of matches to move, when negative move backwards.
12915 RESET is entirely ignored - this function always goes back to the
12916 starting point when no match is found."
12917 (let* ((limit (if (< n 0) (point-min) (point-max)))
12918 (search-func (if (< n 0)
12919 'previous-single-char-property-change
12920 'next-single-char-property-change))
12921 (n (abs n))
12922 (pos (point))
12924 (catch 'exit
12925 (while (setq p1 (funcall search-func (point) 'org-type))
12926 (when (equal p1 limit)
12927 (goto-char pos)
12928 (error "No more matches"))
12929 (when (equal (get-char-property p1 'org-type) 'org-occur)
12930 (setq n (1- n))
12931 (when (= n 0)
12932 (goto-char p1)
12933 (throw 'exit (point))))
12934 (goto-char p1))
12935 (goto-char p1)
12936 (error "No more matches"))))
12938 (defun org-show-context (&optional key)
12939 "Make sure point and context are visible.
12940 How much context is shown depends upon the variables
12941 `org-show-hierarchy-above', `org-show-following-heading',
12942 `org-show-entry-below' and `org-show-siblings'."
12943 (let ((heading-p (org-at-heading-p t))
12944 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12945 (following-p (org-get-alist-option org-show-following-heading key))
12946 (entry-p (org-get-alist-option org-show-entry-below key))
12947 (siblings-p (org-get-alist-option org-show-siblings key)))
12948 (catch 'exit
12949 ;; Show heading or entry text
12950 (if (and heading-p (not entry-p))
12951 (org-flag-heading nil) ; only show the heading
12952 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12953 (org-show-hidden-entry))) ; show entire entry
12954 (when following-p
12955 ;; Show next sibling, or heading below text
12956 (save-excursion
12957 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12958 (org-flag-heading nil))))
12959 (when siblings-p (org-show-siblings))
12960 (when hierarchy-p
12961 ;; show all higher headings, possibly with siblings
12962 (save-excursion
12963 (while (and (condition-case nil
12964 (progn (org-up-heading-all 1) t)
12965 (error nil))
12966 (not (bobp)))
12967 (org-flag-heading nil)
12968 (when siblings-p (org-show-siblings))))))))
12970 (defvar org-reveal-start-hook nil
12971 "Hook run before revealing a location.")
12973 (defun org-reveal (&optional siblings)
12974 "Show current entry, hierarchy above it, and the following headline.
12975 This can be used to show a consistent set of context around locations
12976 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12977 not t for the search context.
12979 With optional argument SIBLINGS, on each level of the hierarchy all
12980 siblings are shown. This repairs the tree structure to what it would
12981 look like when opened with hierarchical calls to `org-cycle'.
12982 With double optional argument \\[universal-argument] \\[universal-argument], \
12983 go to the parent and show the
12984 entire tree."
12985 (interactive "P")
12986 (run-hooks 'org-reveal-start-hook)
12987 (let ((org-show-hierarchy-above t)
12988 (org-show-following-heading t)
12989 (org-show-siblings (if siblings t org-show-siblings)))
12990 (org-show-context nil))
12991 (when (equal siblings '(16))
12992 (save-excursion
12993 (when (org-up-heading-safe)
12994 (org-show-subtree)
12995 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12997 (defun org-highlight-new-match (beg end)
12998 "Highlight from BEG to END and mark the highlight is an occur headline."
12999 (let ((ov (make-overlay beg end)))
13000 (overlay-put ov 'face 'secondary-selection)
13001 (overlay-put ov 'org-type 'org-occur)
13002 (push ov org-occur-highlights)))
13004 (defun org-remove-occur-highlights (&optional beg end noremove)
13005 "Remove the occur highlights from the buffer.
13006 BEG and END are ignored. If NOREMOVE is nil, remove this function
13007 from the `before-change-functions' in the current buffer."
13008 (interactive)
13009 (unless org-inhibit-highlight-removal
13010 (mapc 'delete-overlay org-occur-highlights)
13011 (setq org-occur-highlights nil)
13012 (setq org-occur-parameters nil)
13013 (unless noremove
13014 (remove-hook 'before-change-functions
13015 'org-remove-occur-highlights 'local))))
13017 ;;;; Priorities
13019 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13020 "Regular expression matching the priority indicator.")
13022 (defvar org-remove-priority-next-time nil)
13024 (defun org-priority-up ()
13025 "Increase the priority of the current item."
13026 (interactive)
13027 (org-priority 'up))
13029 (defun org-priority-down ()
13030 "Decrease the priority of the current item."
13031 (interactive)
13032 (org-priority 'down))
13034 (defun org-priority (&optional action)
13035 "Change the priority of an item.
13036 ACTION can be `set', `up', `down', or a character."
13037 (interactive)
13038 (unless org-enable-priority-commands
13039 (error "Priority commands are disabled"))
13040 (setq action (or action 'set))
13041 (let (current new news have remove)
13042 (save-excursion
13043 (org-back-to-heading t)
13044 (if (looking-at org-priority-regexp)
13045 (setq current (string-to-char (match-string 2))
13046 have t))
13047 (cond
13048 ((eq action 'remove)
13049 (setq remove t new ?\ ))
13050 ((or (eq action 'set)
13051 (if (featurep 'xemacs) (characterp action) (integerp action)))
13052 (if (not (eq action 'set))
13053 (setq new action)
13054 (message "Priority %c-%c, SPC to remove: "
13055 org-highest-priority org-lowest-priority)
13056 (save-match-data
13057 (setq new (read-char-exclusive))))
13058 (if (and (= (upcase org-highest-priority) org-highest-priority)
13059 (= (upcase org-lowest-priority) org-lowest-priority))
13060 (setq new (upcase new)))
13061 (cond ((equal new ?\ ) (setq remove t))
13062 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13063 (error "Priority must be between `%c' and `%c'"
13064 org-highest-priority org-lowest-priority))))
13065 ((eq action 'up)
13066 (setq new (if have
13067 (1- current) ; normal cycling
13068 ;; last priority was empty
13069 (if (eq last-command this-command)
13070 org-lowest-priority ; wrap around empty to lowest
13071 ;; default
13072 (if org-priority-start-cycle-with-default
13073 org-default-priority
13074 (1- org-default-priority))))))
13075 ((eq action 'down)
13076 (setq new (if have
13077 (1+ current) ; normal cycling
13078 ;; last priority was empty
13079 (if (eq last-command this-command)
13080 org-highest-priority ; wrap around empty to highest
13081 ;; default
13082 (if org-priority-start-cycle-with-default
13083 org-default-priority
13084 (1+ org-default-priority))))))
13085 (t (error "Invalid action")))
13086 (if (or (< (upcase new) org-highest-priority)
13087 (> (upcase new) org-lowest-priority))
13088 (if (and (memq action '(up down))
13089 (not have) (not (eq last-command this-command)))
13090 ;; `new' is from default priority
13091 (error
13092 "The default can not be set, see `org-default-priority' why")
13093 ;; normal cycling: `new' is beyond highest/lowest priority
13094 ;; and is wrapped around to the empty priority
13095 (setq remove t)))
13096 (setq news (format "%c" new))
13097 (if have
13098 (if remove
13099 (replace-match "" t t nil 1)
13100 (replace-match news t t nil 2))
13101 (if remove
13102 (error "No priority cookie found in line")
13103 (let ((case-fold-search nil))
13104 (looking-at org-todo-line-regexp))
13105 (if (match-end 2)
13106 (progn
13107 (goto-char (match-end 2))
13108 (insert " [#" news "]"))
13109 (goto-char (match-beginning 3))
13110 (insert "[#" news "] "))))
13111 (org-preserve-lc (org-set-tags nil 'align)))
13112 (if remove
13113 (message "Priority removed")
13114 (message "Priority of current item set to %s" news))))
13116 (defun org-get-priority (s)
13117 "Find priority cookie and return priority."
13118 (if (functionp org-get-priority-function)
13119 (funcall org-get-priority-function)
13120 (save-match-data
13121 (if (not (string-match org-priority-regexp s))
13122 (* 1000 (- org-lowest-priority org-default-priority))
13123 (* 1000 (- org-lowest-priority
13124 (string-to-char (match-string 2 s))))))))
13126 ;;;; Tags
13128 (defvar org-agenda-archives-mode)
13129 (defvar org-map-continue-from nil
13130 "Position from where mapping should continue.
13131 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13133 (defvar org-scanner-tags nil
13134 "The current tag list while the tags scanner is running.")
13135 (defvar org-trust-scanner-tags nil
13136 "Should `org-get-tags-at' use the tags for the scanner.
13137 This is for internal dynamical scoping only.
13138 When this is non-nil, the function `org-get-tags-at' will return the value
13139 of `org-scanner-tags' instead of building the list by itself. This
13140 can lead to large speed-ups when the tags scanner is used in a file with
13141 many entries, and when the list of tags is retrieved, for example to
13142 obtain a list of properties. Building the tags list for each entry in such
13143 a file becomes an N^2 operation - but with this variable set, it scales
13144 as N.")
13146 (defun org-scan-tags (action matcher todo-only &optional start-level)
13147 "Scan headline tags with inheritance and produce output ACTION.
13149 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13150 or `agenda' to produce an entry list for an agenda view. It can also be
13151 a Lisp form or a function that should be called at each matched headline, in
13152 this case the return value is a list of all return values from these calls.
13154 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13155 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13156 only lines with a not-done TODO keyword are included in the output.
13157 This should be the same variable that was scoped into
13158 and set by `org-make-tags-matcher' when it constructed MATCHER.
13160 START-LEVEL can be a string with asterisks, reducing the scope to
13161 headlines matching this string."
13162 (require 'org-agenda)
13163 (let* ((re (concat "^"
13164 (if start-level
13165 ;; Get the correct level to match
13166 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13167 org-outline-regexp)
13168 " *\\(\\<\\("
13169 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13170 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13171 (props (list 'face 'default
13172 'done-face 'org-agenda-done
13173 'undone-face 'default
13174 'mouse-face 'highlight
13175 'org-not-done-regexp org-not-done-regexp
13176 'org-todo-regexp org-todo-regexp
13177 'org-complex-heading-regexp org-complex-heading-regexp
13178 'help-echo
13179 (format "mouse-2 or RET jump to org file %s"
13180 (abbreviate-file-name
13181 (or (buffer-file-name (buffer-base-buffer))
13182 (buffer-name (buffer-base-buffer)))))))
13183 (case-fold-search nil)
13184 (org-map-continue-from nil)
13185 lspos tags tags-list
13186 (tags-alist (list (cons 0 org-file-tags)))
13187 (llast 0) rtn rtn1 level category i txt
13188 todo marker entry priority)
13189 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13190 (setq action (list 'lambda nil action)))
13191 (save-excursion
13192 (goto-char (point-min))
13193 (when (eq action 'sparse-tree)
13194 (org-overview)
13195 (org-remove-occur-highlights))
13196 (while (re-search-forward re nil t)
13197 (setq org-map-continue-from nil)
13198 (catch :skip
13199 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13200 tags (if (match-end 4) (org-match-string-no-properties 4)))
13201 (goto-char (setq lspos (match-beginning 0)))
13202 (setq level (org-reduced-level (funcall outline-level))
13203 category (org-get-category))
13204 (setq i llast llast level)
13205 ;; remove tag lists from same and sublevels
13206 (while (>= i level)
13207 (when (setq entry (assoc i tags-alist))
13208 (setq tags-alist (delete entry tags-alist)))
13209 (setq i (1- i)))
13210 ;; add the next tags
13211 (when tags
13212 (setq tags (org-split-string tags ":")
13213 tags-alist
13214 (cons (cons level tags) tags-alist)))
13215 ;; compile tags for current headline
13216 (setq tags-list
13217 (if org-use-tag-inheritance
13218 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13219 tags)
13220 org-scanner-tags tags-list)
13221 (when org-use-tag-inheritance
13222 (setcdr (car tags-alist)
13223 (mapcar (lambda (x)
13224 (setq x (copy-sequence x))
13225 (org-add-prop-inherited x))
13226 (cdar tags-alist))))
13227 (when (and tags org-use-tag-inheritance
13228 (or (not (eq t org-use-tag-inheritance))
13229 org-tags-exclude-from-inheritance))
13230 ;; selective inheritance, remove uninherited ones
13231 (setcdr (car tags-alist)
13232 (org-remove-uninherited-tags (cdar tags-alist))))
13233 (when (and
13235 ;; eval matcher only when the todo condition is OK
13236 (and (or (not todo-only) (member todo org-not-done-keywords))
13237 (let ((case-fold-search t) (org-trust-scanner-tags t))
13238 (eval matcher)))
13240 ;; Call the skipper, but return t if it does not skip,
13241 ;; so that the `and' form continues evaluating
13242 (progn
13243 (unless (eq action 'sparse-tree) (org-agenda-skip))
13246 ;; Check if timestamps are deselecting this entry
13247 (or (not todo-only)
13248 (and (member todo org-not-done-keywords)
13249 (or (not org-agenda-tags-todo-honor-ignore-options)
13250 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13252 ;; Extra check for the archive tag
13253 ;; FIXME: Does the skipper already do this????
13255 (not (member org-archive-tag tags-list))
13256 ;; we have an archive tag, should we use this anyway?
13257 (or (not org-agenda-skip-archived-trees)
13258 (and (eq action 'agenda) org-agenda-archives-mode))))
13260 ;; select this headline
13262 (cond
13263 ((eq action 'sparse-tree)
13264 (and org-highlight-sparse-tree-matches
13265 (org-get-heading) (match-end 0)
13266 (org-highlight-new-match
13267 (match-beginning 1) (match-end 1)))
13268 (org-show-context 'tags-tree))
13269 ((eq action 'agenda)
13270 (setq txt (org-agenda-format-item
13272 (concat
13273 (if (eq org-tags-match-list-sublevels 'indented)
13274 (make-string (1- level) ?.) "")
13275 (org-get-heading))
13276 category
13277 tags-list)
13278 priority (org-get-priority txt))
13279 (goto-char lspos)
13280 (setq marker (org-agenda-new-marker))
13281 (org-add-props txt props
13282 'org-marker marker 'org-hd-marker marker 'org-category category
13283 'todo-state todo
13284 'priority priority 'type "tagsmatch")
13285 (push txt rtn))
13286 ((functionp action)
13287 (setq org-map-continue-from nil)
13288 (save-excursion
13289 (setq rtn1 (funcall action))
13290 (push rtn1 rtn)))
13291 (t (error "Invalid action")))
13293 ;; if we are to skip sublevels, jump to end of subtree
13294 (unless org-tags-match-list-sublevels
13295 (org-end-of-subtree t)
13296 (backward-char 1))))
13297 ;; Get the correct position from where to continue
13298 (if org-map-continue-from
13299 (goto-char org-map-continue-from)
13300 (and (= (point) lspos) (end-of-line 1)))))
13301 (when (and (eq action 'sparse-tree)
13302 (not org-sparse-tree-open-archived-trees))
13303 (org-hide-archived-subtrees (point-min) (point-max)))
13304 (nreverse rtn)))
13306 (defun org-remove-uninherited-tags (tags)
13307 "Remove all tags that are not inherited from the list TAGS."
13308 (cond
13309 ((eq org-use-tag-inheritance t)
13310 (if org-tags-exclude-from-inheritance
13311 (org-delete-all org-tags-exclude-from-inheritance tags)
13312 tags))
13313 ((not org-use-tag-inheritance) nil)
13314 ((stringp org-use-tag-inheritance)
13315 (delq nil (mapcar
13316 (lambda (x)
13317 (if (and (string-match org-use-tag-inheritance x)
13318 (not (member x org-tags-exclude-from-inheritance)))
13319 x nil))
13320 tags)))
13321 ((listp org-use-tag-inheritance)
13322 (delq nil (mapcar
13323 (lambda (x)
13324 (if (member x org-use-tag-inheritance) x nil))
13325 tags)))))
13327 (defun org-match-sparse-tree (&optional todo-only match)
13328 "Create a sparse tree according to tags string MATCH.
13329 MATCH can contain positive and negative selection of tags, like
13330 \"+WORK+URGENT-WITHBOSS\".
13331 If optional argument TODO-ONLY is non-nil, only select lines that are
13332 also TODO lines."
13333 (interactive "P")
13334 (org-agenda-prepare-buffers (list (current-buffer)))
13335 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13337 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13339 (defvar org-cached-props nil)
13340 (defun org-cached-entry-get (pom property)
13341 (if (or (eq t org-use-property-inheritance)
13342 (and (stringp org-use-property-inheritance)
13343 (string-match org-use-property-inheritance property))
13344 (and (listp org-use-property-inheritance)
13345 (member property org-use-property-inheritance)))
13346 ;; Caching is not possible, check it directly
13347 (org-entry-get pom property 'inherit)
13348 ;; Get all properties, so that we can do complicated checks easily
13349 (cdr (assoc property (or org-cached-props
13350 (setq org-cached-props
13351 (org-entry-properties pom)))))))
13353 (defun org-global-tags-completion-table (&optional files)
13354 "Return the list of all tags in all agenda buffer/files.
13355 Optional FILES argument is a list of files which can be used
13356 instead of the agenda files."
13357 (save-excursion
13358 (org-uniquify
13359 (delq nil
13360 (apply 'append
13361 (mapcar
13362 (lambda (file)
13363 (set-buffer (find-file-noselect file))
13364 (append (org-get-buffer-tags)
13365 (mapcar (lambda (x) (if (stringp (car-safe x))
13366 (list (car-safe x)) nil))
13367 org-tag-alist)))
13368 (if (and files (car files))
13369 files
13370 (org-agenda-files))))))))
13372 (defun org-make-tags-matcher (match)
13373 "Create the TAGS/TODO matcher form for the selection string MATCH.
13375 The variable `todo-only' is scoped dynamically into this function.
13376 It will be set to t if the matcher restricts matching to TODO entries,
13377 otherwise will not be touched.
13379 Returns a cons of the selection string MATCH and the constructed
13380 lisp form implementing the matcher. The matcher is to be evaluated
13381 at an Org entry, with point on the headline, and returns t if the
13382 entry matches the selection string MATCH. The returned lisp form
13383 references two variables with information about the entry, which
13384 must be bound around the form's evaluation: todo, the TODO keyword
13385 at the entry (or nil of none); and tags-list, the list of all tags
13386 at the entry including inherited ones. Additionally, the category
13387 of the entry (if any) must be specified as the text property
13388 'org-category on the headline.
13390 See also `org-scan-tags'.
13392 (declare (special todo-only))
13393 (unless (boundp 'todo-only)
13394 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13395 (unless match
13396 ;; Get a new match request, with completion
13397 (let ((org-last-tags-completion-table
13398 (org-global-tags-completion-table)))
13399 (setq match (org-completing-read-no-i
13400 "Match: " 'org-tags-completion-function nil nil nil
13401 'org-tags-history))))
13403 ;; Parse the string and create a lisp form
13404 (let ((match0 match)
13405 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13406 minus tag mm
13407 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13408 orterms term orlist re-p str-p level-p level-op time-p
13409 prop-p pn pv po gv rest)
13410 (if (string-match "/+" match)
13411 ;; match contains also a todo-matching request
13412 (progn
13413 (setq tagsmatch (substring match 0 (match-beginning 0))
13414 todomatch (substring match (match-end 0)))
13415 (if (string-match "^!" todomatch)
13416 (setq todo-only t todomatch (substring todomatch 1)))
13417 (if (string-match "^\\s-*$" todomatch)
13418 (setq todomatch nil)))
13419 ;; only matching tags
13420 (setq tagsmatch match todomatch nil))
13422 ;; Make the tags matcher
13423 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13424 (setq tagsmatcher t)
13425 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13426 (while (setq term (pop orterms))
13427 (while (and (equal (substring term -1) "\\") orterms)
13428 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13429 (while (string-match re term)
13430 (setq rest (substring term (match-end 0))
13431 minus (and (match-end 1)
13432 (equal (match-string 1 term) "-"))
13433 tag (save-match-data (replace-regexp-in-string
13434 "\\\\-" "-"
13435 (match-string 2 term)))
13436 re-p (equal (string-to-char tag) ?{)
13437 level-p (match-end 4)
13438 prop-p (match-end 5)
13439 mm (cond
13440 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13441 (level-p
13442 (setq level-op (org-op-to-function (match-string 3 term)))
13443 `(,level-op level ,(string-to-number
13444 (match-string 4 term))))
13445 (prop-p
13446 (setq pn (match-string 5 term)
13447 po (match-string 6 term)
13448 pv (match-string 7 term)
13449 re-p (equal (string-to-char pv) ?{)
13450 str-p (equal (string-to-char pv) ?\")
13451 time-p (save-match-data
13452 (string-match "^\"[[<].*[]>]\"$" pv))
13453 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13454 (if time-p (setq pv (org-matcher-time pv)))
13455 (setq po (org-op-to-function po (if time-p 'time str-p)))
13456 (cond
13457 ((equal pn "CATEGORY")
13458 (setq gv '(get-text-property (point) 'org-category)))
13459 ((equal pn "TODO")
13460 (setq gv 'todo))
13462 (setq gv `(org-cached-entry-get nil ,pn))))
13463 (if re-p
13464 (if (eq po 'org<>)
13465 `(not (string-match ,pv (or ,gv "")))
13466 `(string-match ,pv (or ,gv "")))
13467 (if str-p
13468 `(,po (or ,gv "") ,pv)
13469 `(,po (string-to-number (or ,gv ""))
13470 ,(string-to-number pv) ))))
13471 (t `(member ,tag tags-list)))
13472 mm (if minus (list 'not mm) mm)
13473 term rest)
13474 (push mm tagsmatcher))
13475 (push (if (> (length tagsmatcher) 1)
13476 (cons 'and tagsmatcher)
13477 (car tagsmatcher))
13478 orlist)
13479 (setq tagsmatcher nil))
13480 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13481 (setq tagsmatcher
13482 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13483 ;; Make the todo matcher
13484 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13485 (setq todomatcher t)
13486 (setq orterms (org-split-string todomatch "|") orlist nil)
13487 (while (setq term (pop orterms))
13488 (while (string-match re term)
13489 (setq minus (and (match-end 1)
13490 (equal (match-string 1 term) "-"))
13491 kwd (match-string 2 term)
13492 re-p (equal (string-to-char kwd) ?{)
13493 term (substring term (match-end 0))
13494 mm (if re-p
13495 `(string-match ,(substring kwd 1 -1) todo)
13496 (list 'equal 'todo kwd))
13497 mm (if minus (list 'not mm) mm))
13498 (push mm todomatcher))
13499 (push (if (> (length todomatcher) 1)
13500 (cons 'and todomatcher)
13501 (car todomatcher))
13502 orlist)
13503 (setq todomatcher nil))
13504 (setq todomatcher (if (> (length orlist) 1)
13505 (cons 'or orlist) (car orlist))))
13507 ;; Return the string and lisp forms of the matcher
13508 (setq matcher (if todomatcher
13509 (list 'and tagsmatcher todomatcher)
13510 tagsmatcher))
13511 (when todo-only
13512 (setq matcher (list 'and '(member todo org-not-done-keywords)
13513 matcher)))
13514 (cons match0 matcher)))
13516 (defun org-op-to-function (op &optional stringp)
13517 "Turn an operator into the appropriate function."
13518 (setq op
13519 (cond
13520 ((equal op "<" ) '(< string< org-time<))
13521 ((equal op ">" ) '(> org-string> org-time>))
13522 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13523 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13524 ((member op '("=" "==")) '(= string= org-time=))
13525 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13526 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13528 (defun org<> (a b) (not (= a b)))
13529 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13530 (defun org-string>= (a b) (not (string< a b)))
13531 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13532 (defun org-string<> (a b) (not (string= 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) (>= a b)))
13538 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13539 (defun org-2ft (s)
13540 "Convert S to a floating point time.
13541 If S is already a number, just return it. If it is a string, parse
13542 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13543 (cond
13544 ((numberp s) s)
13545 ((stringp s)
13546 (condition-case nil
13547 (float-time (apply 'encode-time (org-parse-time-string s)))
13548 (error 0.)))
13549 (t 0.)))
13551 (defun org-time-today ()
13552 "Time in seconds today at 0:00.
13553 Returns the float number of seconds since the beginning of the
13554 epoch to the beginning of today (00:00)."
13555 (float-time (apply 'encode-time
13556 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13558 (defun org-matcher-time (s)
13559 "Interpret a time comparison value."
13560 (save-match-data
13561 (cond
13562 ((string= s "<now>") (float-time))
13563 ((string= s "<today>") (org-time-today))
13564 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13565 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13566 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13567 (+ (org-time-today)
13568 (* (string-to-number (match-string 1 s))
13569 (cdr (assoc (match-string 2 s)
13570 '(("d" . 86400.0) ("w" . 604800.0)
13571 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13572 (t (org-2ft s)))))
13574 (defun org-match-any-p (re list)
13575 "Does re match any element of list?"
13576 (setq list (mapcar (lambda (x) (string-match re x)) list))
13577 (delq nil list))
13579 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13580 (defvar org-tags-overlay (make-overlay 1 1))
13581 (org-detach-overlay org-tags-overlay)
13583 (defun org-get-local-tags-at (&optional pos)
13584 "Get a list of tags defined in the current headline."
13585 (org-get-tags-at pos 'local))
13587 (defun org-get-local-tags ()
13588 "Get a list of tags defined in the current headline."
13589 (org-get-tags-at nil 'local))
13591 (defun org-get-tags-at (&optional pos local)
13592 "Get a list of all headline tags applicable at POS.
13593 POS defaults to point. If tags are inherited, the list contains
13594 the targets in the same sequence as the headlines appear, i.e.
13595 the tags of the current headline come last.
13596 When LOCAL is non-nil, only return tags from the current headline,
13597 ignore inherited ones."
13598 (interactive)
13599 (if (and org-trust-scanner-tags
13600 (or (not pos) (equal pos (point)))
13601 (not local))
13602 org-scanner-tags
13603 (let (tags ltags lastpos parent)
13604 (save-excursion
13605 (save-restriction
13606 (widen)
13607 (goto-char (or pos (point)))
13608 (save-match-data
13609 (catch 'done
13610 (condition-case nil
13611 (progn
13612 (org-back-to-heading t)
13613 (while (not (equal lastpos (point)))
13614 (setq lastpos (point))
13615 (when (looking-at
13616 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13617 (setq ltags (org-split-string
13618 (org-match-string-no-properties 1) ":"))
13619 (when parent
13620 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13621 (setq tags (append
13622 (if parent
13623 (org-remove-uninherited-tags ltags)
13624 ltags)
13625 tags)))
13626 (or org-use-tag-inheritance (throw 'done t))
13627 (if local (throw 'done t))
13628 (or (org-up-heading-safe) (error nil))
13629 (setq parent t)))
13630 (error nil)))))
13631 (if local
13632 tags
13633 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13635 (defun org-add-prop-inherited (s)
13636 (add-text-properties 0 (length s) '(inherited t) s)
13639 (defun org-toggle-tag (tag &optional onoff)
13640 "Toggle the tag TAG for the current line.
13641 If ONOFF is `on' or `off', don't toggle but set to this state."
13642 (let (res current)
13643 (save-excursion
13644 (org-back-to-heading t)
13645 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13646 (point-at-eol) t)
13647 (progn
13648 (setq current (match-string 1))
13649 (replace-match ""))
13650 (setq current ""))
13651 (setq current (nreverse (org-split-string current ":")))
13652 (cond
13653 ((eq onoff 'on)
13654 (setq res t)
13655 (or (member tag current) (push tag current)))
13656 ((eq onoff 'off)
13657 (or (not (member tag current)) (setq current (delete tag current))))
13658 (t (if (member tag current)
13659 (setq current (delete tag current))
13660 (setq res t)
13661 (push tag current))))
13662 (end-of-line 1)
13663 (if current
13664 (progn
13665 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13666 (org-set-tags nil t))
13667 (delete-horizontal-space))
13668 (run-hooks 'org-after-tags-change-hook))
13669 res))
13671 (defun org-align-tags-here (to-col)
13672 ;; Assumes that this is a headline
13673 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13674 (beginning-of-line 1)
13675 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13676 (< pos (match-beginning 2)))
13677 (progn
13678 (setq tags-l (- (match-end 2) (match-beginning 2)))
13679 (goto-char (match-beginning 1))
13680 (insert " ")
13681 (delete-region (point) (1+ (match-beginning 2)))
13682 (setq ncol (max (current-column)
13683 (1+ col)
13684 (if (> to-col 0)
13685 to-col
13686 (- (abs to-col) tags-l))))
13687 (setq p (point))
13688 (insert (make-string (- ncol (current-column)) ?\ ))
13689 (setq ncol (current-column))
13690 (when indent-tabs-mode (tabify p (point-at-eol)))
13691 (org-move-to-column (min ncol col) t))
13692 (goto-char pos))))
13694 (defun org-set-tags-command (&optional arg just-align)
13695 "Call the set-tags command for the current entry."
13696 (interactive "P")
13697 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13698 (org-set-tags arg just-align)
13699 (save-excursion
13700 (org-back-to-heading t)
13701 (org-set-tags arg just-align))))
13703 (defun org-set-tags-to (data)
13704 "Set the tags of the current entry to DATA, replacing the current tags.
13705 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13706 If DATA is nil or the empty string, any tags will be removed."
13707 (interactive "sTags: ")
13708 (setq data
13709 (cond
13710 ((eq data nil) "")
13711 ((equal data "") "")
13712 ((stringp data)
13713 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13714 ":"))
13715 ((listp data)
13716 (concat ":" (mapconcat 'identity data ":") ":"))))
13717 (when data
13718 (save-excursion
13719 (org-back-to-heading t)
13720 (when (looking-at org-complex-heading-regexp)
13721 (if (match-end 5)
13722 (progn
13723 (goto-char (match-beginning 5))
13724 (insert data)
13725 (delete-region (point) (point-at-eol))
13726 (org-set-tags nil 'align))
13727 (goto-char (point-at-eol))
13728 (insert " " data)
13729 (org-set-tags nil 'align)))
13730 (beginning-of-line 1)
13731 (if (looking-at ".*?\\([ \t]+\\)$")
13732 (delete-region (match-beginning 1) (match-end 1))))))
13734 (defun org-align-all-tags ()
13735 "Align the tags i all headings."
13736 (interactive)
13737 (save-excursion
13738 (or (ignore-errors (org-back-to-heading t))
13739 (outline-next-heading))
13740 (if (org-at-heading-p)
13741 (org-set-tags t)
13742 (message "No headings"))))
13744 (defvar org-indent-indentation-per-level)
13745 (defun org-set-tags (&optional arg just-align)
13746 "Set the tags for the current headline.
13747 With prefix ARG, realign all tags in headings in the current buffer."
13748 (interactive "P")
13749 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13750 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13751 'region-start-level 'region))
13752 org-loop-over-headlines-in-active-region)
13753 (org-map-entries
13754 ;; We don't use ARG and JUST-ALIGN here these args are not
13755 ;; useful when looping over headlines
13756 `(org-set-tags)
13757 org-loop-over-headlines-in-active-region
13758 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13759 (let* ((re org-outline-regexp-bol)
13760 (current (unless arg (org-get-tags-string)))
13761 (col (current-column))
13762 (org-setting-tags t)
13763 table current-tags inherited-tags ; computed below when needed
13764 tags p0 c0 c1 rpl di tc level)
13765 (if arg
13766 (save-excursion
13767 (goto-char (point-min))
13768 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13769 (while (re-search-forward re nil t)
13770 (org-set-tags nil t)
13771 (end-of-line 1)))
13772 (message "All tags realigned to column %d" org-tags-column))
13773 (if just-align
13774 (setq tags current)
13775 ;; Get a new set of tags from the user
13776 (save-excursion
13777 (setq table (append org-tag-persistent-alist
13778 (or org-tag-alist (org-get-buffer-tags))
13779 (and
13780 org-complete-tags-always-offer-all-agenda-tags
13781 (org-global-tags-completion-table
13782 (org-agenda-files))))
13783 org-last-tags-completion-table table
13784 current-tags (org-split-string current ":")
13785 inherited-tags (nreverse
13786 (nthcdr (length current-tags)
13787 (nreverse (org-get-tags-at))))
13788 tags
13789 (if (or (eq t org-use-fast-tag-selection)
13790 (and org-use-fast-tag-selection
13791 (delq nil (mapcar 'cdr table))))
13792 (org-fast-tag-selection
13793 current-tags inherited-tags table
13794 (if org-fast-tag-selection-include-todo
13795 org-todo-key-alist))
13796 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13797 (org-trim
13798 (org-icompleting-read "Tags: "
13799 'org-tags-completion-function
13800 nil nil current 'org-tags-history))))))
13801 (while (string-match "[-+&]+" tags)
13802 ;; No boolean logic, just a list
13803 (setq tags (replace-match ":" t t tags))))
13805 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13807 (if org-tags-sort-function
13808 (setq tags (mapconcat 'identity
13809 (sort (org-split-string
13810 tags (org-re "[^[:alnum:]_@#%]+"))
13811 org-tags-sort-function) ":")))
13813 (if (string-match "\\`[\t ]*\\'" tags)
13814 (setq tags "")
13815 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13816 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13818 ;; Insert new tags at the correct column
13819 (beginning-of-line 1)
13820 (setq level (or (and (looking-at org-outline-regexp)
13821 (- (match-end 0) (point) 1))
13823 (cond
13824 ((and (equal current "") (equal tags "")))
13825 ((re-search-forward
13826 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13827 (point-at-eol) t)
13828 (if (equal tags "")
13829 (setq rpl "")
13830 (goto-char (match-beginning 0))
13831 (setq c0 (current-column)
13832 ;; compute offset for the case of org-indent-mode active
13833 di (if org-indent-mode
13834 (* (1- org-indent-indentation-per-level) (1- level))
13836 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13837 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13838 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13839 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13840 (replace-match rpl t t)
13841 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13842 tags)
13843 (t (error "Tags alignment failed")))
13844 (org-move-to-column col)
13845 (unless just-align
13846 (run-hooks 'org-after-tags-change-hook))))))
13848 (defun org-change-tag-in-region (beg end tag off)
13849 "Add or remove TAG for each entry in the region.
13850 This works in the agenda, and also in an org-mode buffer."
13851 (interactive
13852 (list (region-beginning) (region-end)
13853 (let ((org-last-tags-completion-table
13854 (if (derived-mode-p 'org-mode)
13855 (org-get-buffer-tags)
13856 (org-global-tags-completion-table))))
13857 (org-icompleting-read
13858 "Tag: " 'org-tags-completion-function nil nil nil
13859 'org-tags-history))
13860 (progn
13861 (message "[s]et or [r]emove? ")
13862 (equal (read-char-exclusive) ?r))))
13863 (if (fboundp 'deactivate-mark) (deactivate-mark))
13864 (let ((agendap (equal major-mode 'org-agenda-mode))
13865 l1 l2 m buf pos newhead (cnt 0))
13866 (goto-char end)
13867 (setq l2 (1- (org-current-line)))
13868 (goto-char beg)
13869 (setq l1 (org-current-line))
13870 (loop for l from l1 to l2 do
13871 (org-goto-line l)
13872 (setq m (get-text-property (point) 'org-hd-marker))
13873 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13874 (and agendap m))
13875 (setq buf (if agendap (marker-buffer m) (current-buffer))
13876 pos (if agendap m (point)))
13877 (with-current-buffer buf
13878 (save-excursion
13879 (save-restriction
13880 (goto-char pos)
13881 (setq cnt (1+ cnt))
13882 (org-toggle-tag tag (if off 'off 'on))
13883 (setq newhead (org-get-heading)))))
13884 (and agendap (org-agenda-change-all-lines newhead m))))
13885 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13887 (defun org-tags-completion-function (string predicate &optional flag)
13888 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13889 (confirm (lambda (x) (stringp (car x)))))
13890 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13891 (setq s1 (match-string 1 string)
13892 s2 (match-string 2 string))
13893 (setq s1 "" s2 string))
13894 (cond
13895 ((eq flag nil)
13896 ;; try completion
13897 (setq rtn (try-completion s2 ctable confirm))
13898 (if (stringp rtn)
13899 (setq rtn
13900 (concat s1 s2 (substring rtn (length s2))
13901 (if (and org-add-colon-after-tag-completion
13902 (assoc rtn ctable))
13903 ":" ""))))
13904 rtn)
13905 ((eq flag t)
13906 ;; all-completions
13907 (all-completions s2 ctable confirm)
13909 ((eq flag 'lambda)
13910 ;; exact match?
13911 (assoc s2 ctable)))
13914 (defun org-fast-tag-insert (kwd tags face &optional end)
13915 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13916 (insert (format "%-12s" (concat kwd ":"))
13917 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13918 (or end "")))
13920 (defun org-fast-tag-show-exit (flag)
13921 (save-excursion
13922 (org-goto-line 3)
13923 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13924 (replace-match ""))
13925 (when flag
13926 (end-of-line 1)
13927 (org-move-to-column (- (window-width) 19) t)
13928 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13930 (defun org-set-current-tags-overlay (current prefix)
13931 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13932 (if (featurep 'xemacs)
13933 (org-overlay-display org-tags-overlay (concat prefix s)
13934 'secondary-selection)
13935 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13936 (org-overlay-display org-tags-overlay (concat prefix s)))))
13938 (defvar org-last-tag-selection-key nil)
13939 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13940 "Fast tag selection with single keys.
13941 CURRENT is the current list of tags in the headline, INHERITED is the
13942 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13943 possibly with grouping information. TODO-TABLE is a similar table with
13944 TODO keywords, should these have keys assigned to them.
13945 If the keys are nil, a-z are automatically assigned.
13946 Returns the new tags string, or nil to not change the current settings."
13947 (let* ((fulltable (append table todo-table))
13948 (maxlen (apply 'max (mapcar
13949 (lambda (x)
13950 (if (stringp (car x)) (string-width (car x)) 0))
13951 fulltable)))
13952 (buf (current-buffer))
13953 (expert (eq org-fast-tag-selection-single-key 'expert))
13954 (buffer-tags nil)
13955 (fwidth (+ maxlen 3 1 3))
13956 (ncol (/ (- (window-width) 4) fwidth))
13957 (i-face 'org-done)
13958 (c-face 'org-todo)
13959 tg cnt e c char c1 c2 ntable tbl rtn
13960 ov-start ov-end ov-prefix
13961 (exit-after-next org-fast-tag-selection-single-key)
13962 (done-keywords org-done-keywords)
13963 groups ingroup)
13964 (save-excursion
13965 (beginning-of-line 1)
13966 (if (looking-at
13967 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13968 (setq ov-start (match-beginning 1)
13969 ov-end (match-end 1)
13970 ov-prefix "")
13971 (setq ov-start (1- (point-at-eol))
13972 ov-end (1+ ov-start))
13973 (skip-chars-forward "^\n\r")
13974 (setq ov-prefix
13975 (concat
13976 (buffer-substring (1- (point)) (point))
13977 (if (> (current-column) org-tags-column)
13979 (make-string (- org-tags-column (current-column)) ?\ ))))))
13980 (move-overlay org-tags-overlay ov-start ov-end)
13981 (save-window-excursion
13982 (if expert
13983 (set-buffer (get-buffer-create " *Org tags*"))
13984 (delete-other-windows)
13985 (split-window-vertically)
13986 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13987 (erase-buffer)
13988 (org-set-local 'org-done-keywords done-keywords)
13989 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13990 (org-fast-tag-insert "Current" current c-face "\n\n")
13991 (org-fast-tag-show-exit exit-after-next)
13992 (org-set-current-tags-overlay current ov-prefix)
13993 (setq tbl fulltable char ?a cnt 0)
13994 (while (setq e (pop tbl))
13995 (cond
13996 ((equal (car e) :startgroup)
13997 (push '() groups) (setq ingroup t)
13998 (when (not (= cnt 0))
13999 (setq cnt 0)
14000 (insert "\n"))
14001 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14002 ((equal (car e) :endgroup)
14003 (setq ingroup nil cnt 0)
14004 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14005 ((equal e '(:newline))
14006 (when (not (= cnt 0))
14007 (setq cnt 0)
14008 (insert "\n")
14009 (setq e (car tbl))
14010 (while (equal (car tbl) '(:newline))
14011 (insert "\n")
14012 (setq tbl (cdr tbl)))))
14014 (setq tg (copy-sequence (car e)) c2 nil)
14015 (if (cdr e)
14016 (setq c (cdr e))
14017 ;; automatically assign a character.
14018 (setq c1 (string-to-char
14019 (downcase (substring
14020 tg (if (= (string-to-char tg) ?@) 1 0)))))
14021 (if (or (rassoc c1 ntable) (rassoc c1 table))
14022 (while (or (rassoc char ntable) (rassoc char table))
14023 (setq char (1+ char)))
14024 (setq c2 c1))
14025 (setq c (or c2 char)))
14026 (if ingroup (push tg (car groups)))
14027 (setq tg (org-add-props tg nil 'face
14028 (cond
14029 ((not (assoc tg table))
14030 (org-get-todo-face tg))
14031 ((member tg current) c-face)
14032 ((member tg inherited) i-face))))
14033 (if (and (= cnt 0) (not ingroup)) (insert " "))
14034 (insert "[" c "] " tg (make-string
14035 (- fwidth 4 (length tg)) ?\ ))
14036 (push (cons tg c) ntable)
14037 (when (= (setq cnt (1+ cnt)) ncol)
14038 (insert "\n")
14039 (if ingroup (insert " "))
14040 (setq cnt 0)))))
14041 (setq ntable (nreverse ntable))
14042 (insert "\n")
14043 (goto-char (point-min))
14044 (if (not expert) (org-fit-window-to-buffer))
14045 (setq rtn
14046 (catch 'exit
14047 (while t
14048 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14049 (if (not groups) "no " "")
14050 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14051 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14052 (setq org-last-tag-selection-key c)
14053 (cond
14054 ((= c ?\r) (throw 'exit t))
14055 ((= c ?!)
14056 (setq groups (not groups))
14057 (goto-char (point-min))
14058 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14059 ((= c ?\C-c)
14060 (if (not expert)
14061 (org-fast-tag-show-exit
14062 (setq exit-after-next (not exit-after-next)))
14063 (setq expert nil)
14064 (delete-other-windows)
14065 (set-window-buffer (split-window-vertically) " *Org tags*")
14066 (org-switch-to-buffer-other-window " *Org tags*")
14067 (org-fit-window-to-buffer)))
14068 ((or (= c ?\C-g)
14069 (and (= c ?q) (not (rassoc c ntable))))
14070 (org-detach-overlay org-tags-overlay)
14071 (setq quit-flag t))
14072 ((= c ?\ )
14073 (setq current nil)
14074 (if exit-after-next (setq exit-after-next 'now)))
14075 ((= c ?\t)
14076 (condition-case nil
14077 (setq tg (org-icompleting-read
14078 "Tag: "
14079 (or buffer-tags
14080 (with-current-buffer buf
14081 (org-get-buffer-tags)))))
14082 (quit (setq tg "")))
14083 (when (string-match "\\S-" tg)
14084 (add-to-list 'buffer-tags (list tg))
14085 (if (member tg current)
14086 (setq current (delete tg current))
14087 (push tg current)))
14088 (if exit-after-next (setq exit-after-next 'now)))
14089 ((setq e (rassoc c todo-table) tg (car e))
14090 (with-current-buffer buf
14091 (save-excursion (org-todo tg)))
14092 (if exit-after-next (setq exit-after-next 'now)))
14093 ((setq e (rassoc c ntable) tg (car e))
14094 (if (member tg current)
14095 (setq current (delete tg current))
14096 (loop for g in groups do
14097 (if (member tg g)
14098 (mapc (lambda (x)
14099 (setq current (delete x current)))
14100 g)))
14101 (push tg current))
14102 (if exit-after-next (setq exit-after-next 'now))))
14104 ;; Create a sorted list
14105 (setq current
14106 (sort current
14107 (lambda (a b)
14108 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14109 (if (eq exit-after-next 'now) (throw 'exit t))
14110 (goto-char (point-min))
14111 (beginning-of-line 2)
14112 (delete-region (point) (point-at-eol))
14113 (org-fast-tag-insert "Current" current c-face)
14114 (org-set-current-tags-overlay current ov-prefix)
14115 (while (re-search-forward
14116 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14117 (setq tg (match-string 1))
14118 (add-text-properties
14119 (match-beginning 1) (match-end 1)
14120 (list 'face
14121 (cond
14122 ((member tg current) c-face)
14123 ((member tg inherited) i-face)
14124 (t (get-text-property (match-beginning 1) 'face))))))
14125 (goto-char (point-min)))))
14126 (org-detach-overlay org-tags-overlay)
14127 (if rtn
14128 (mapconcat 'identity current ":")
14129 nil))))
14131 (defun org-get-tags-string ()
14132 "Get the TAGS string in the current headline."
14133 (unless (org-at-heading-p t)
14134 (error "Not on a heading"))
14135 (save-excursion
14136 (beginning-of-line 1)
14137 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14138 (org-match-string-no-properties 1)
14139 "")))
14141 (defun org-get-tags ()
14142 "Get the list of tags specified in the current headline."
14143 (org-split-string (org-get-tags-string) ":"))
14145 (defun org-get-buffer-tags ()
14146 "Get a table of all tags used in the buffer, for completion."
14147 (let (tags)
14148 (save-excursion
14149 (goto-char (point-min))
14150 (while (re-search-forward
14151 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14152 (when (equal (char-after (point-at-bol 0)) ?*)
14153 (mapc (lambda (x) (add-to-list 'tags x))
14154 (org-split-string (org-match-string-no-properties 1) ":")))))
14155 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14156 (mapcar 'list tags)))
14158 ;;;; The mapping API
14160 ;;;###autoload
14161 (defun org-map-entries (func &optional match scope &rest skip)
14162 "Call FUNC at each headline selected by MATCH in SCOPE.
14164 FUNC is a function or a lisp form. The function will be called without
14165 arguments, with the cursor positioned at the beginning of the headline.
14166 The return values of all calls to the function will be collected and
14167 returned as a list.
14169 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14170 does not need to preserve point. After evaluation, the cursor will be
14171 moved to the end of the line (presumably of the headline of the
14172 processed entry) and search continues from there. Under some
14173 circumstances, this may not produce the wanted results. For example,
14174 if you have removed (e.g. archived) the current (sub)tree it could
14175 mean that the next entry will be skipped entirely. In such cases, you
14176 can specify the position from where search should continue by making
14177 FUNC set the variable `org-map-continue-from' to the desired buffer
14178 position.
14180 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14181 Only headlines that are matched by this query will be considered during
14182 the iteration. When MATCH is nil or t, all headlines will be
14183 visited by the iteration.
14185 SCOPE determines the scope of this command. It can be any of:
14187 nil The current buffer, respecting the restriction if any
14188 tree The subtree started with the entry at point
14189 region The entries within the active region, if any
14190 region-start-level
14191 The entries within the active region, but only those at
14192 the same level than the first one.
14193 file The current buffer, without restriction
14194 file-with-archives
14195 The current buffer, and any archives associated with it
14196 agenda All agenda files
14197 agenda-with-archives
14198 All agenda files with any archive files associated with them
14199 \(file1 file2 ...)
14200 If this is a list, all files in the list will be scanned
14202 The remaining args are treated as settings for the skipping facilities of
14203 the scanner. The following items can be given here:
14205 archive skip trees with the archive tag.
14206 comment skip trees with the COMMENT keyword
14207 function or Emacs Lisp form:
14208 will be used as value for `org-agenda-skip-function', so whenever
14209 the function returns t, FUNC will not be called for that
14210 entry and search will continue from the point where the
14211 function leaves it.
14213 If your function needs to retrieve the tags including inherited tags
14214 at the *current* entry, you can use the value of the variable
14215 `org-scanner-tags' which will be much faster than getting the value
14216 with `org-get-tags-at'. If your function gets properties with
14217 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14218 to t around the call to `org-entry-properties' to get the same speedup.
14219 Note that if your function moves around to retrieve tags and properties at
14220 a *different* entry, you cannot use these techniques."
14221 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14222 (not (org-region-active-p)))
14223 (let* ((org-agenda-archives-mode nil) ; just to make sure
14224 (org-agenda-skip-archived-trees (memq 'archive skip))
14225 (org-agenda-skip-comment-trees (memq 'comment skip))
14226 (org-agenda-skip-function
14227 (car (org-delete-all '(comment archive) skip)))
14228 (org-tags-match-list-sublevels t)
14229 (start-level (eq scope 'region-start-level))
14230 matcher file res
14231 org-todo-keywords-for-agenda
14232 org-done-keywords-for-agenda
14233 org-todo-keyword-alist-for-agenda
14234 org-drawers-for-agenda
14235 org-tag-alist-for-agenda
14236 todo-only)
14238 (cond
14239 ((eq match t) (setq matcher t))
14240 ((eq match nil) (setq matcher t))
14241 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14243 (save-excursion
14244 (save-restriction
14245 (cond ((eq scope 'tree)
14246 (org-back-to-heading t)
14247 (org-narrow-to-subtree)
14248 (setq scope nil))
14249 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14250 (org-region-active-p))
14251 ;; If needed, set start-level to a string like "2"
14252 (when start-level
14253 (save-excursion
14254 (goto-char (region-beginning))
14255 (unless (org-at-heading-p) (outline-next-heading))
14256 (setq start-level (org-current-level))))
14257 (narrow-to-region (region-beginning)
14258 (save-excursion
14259 (goto-char (region-end))
14260 (unless (and (bolp) (org-at-heading-p))
14261 (outline-next-heading))
14262 (point)))
14263 (setq scope nil)))
14265 (if (not scope)
14266 (progn
14267 (org-agenda-prepare-buffers
14268 (list (buffer-file-name (current-buffer))))
14269 (setq res (org-scan-tags func matcher todo-only start-level)))
14270 ;; Get the right scope
14271 (cond
14272 ((and scope (listp scope) (symbolp (car scope)))
14273 (setq scope (eval scope)))
14274 ((eq scope 'agenda)
14275 (setq scope (org-agenda-files t)))
14276 ((eq scope 'agenda-with-archives)
14277 (setq scope (org-agenda-files t))
14278 (setq scope (org-add-archive-files scope)))
14279 ((eq scope 'file)
14280 (setq scope (list (buffer-file-name))))
14281 ((eq scope 'file-with-archives)
14282 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14283 (org-agenda-prepare-buffers scope)
14284 (while (setq file (pop scope))
14285 (with-current-buffer (org-find-base-buffer-visiting file)
14286 (save-excursion
14287 (save-restriction
14288 (widen)
14289 (goto-char (point-min))
14290 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14291 res)))
14293 ;;;; Properties
14295 ;;; Setting and retrieving properties
14297 (defconst org-special-properties
14298 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14299 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14300 "The special properties valid in Org-mode.
14302 These are properties that are not defined in the property drawer,
14303 but in some other way.")
14305 (defconst org-default-properties
14306 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14307 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14308 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14309 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14310 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14311 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14312 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14313 "Some properties that are used by Org-mode for various purposes.
14314 Being in this list makes sure that they are offered for completion.")
14316 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14317 "Regular expression matching the first line of a property drawer.")
14319 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14320 "Regular expression matching the last line of a property drawer.")
14322 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14323 "Regular expression matching the first line of a property drawer.")
14325 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14326 "Regular expression matching the first line of a property drawer.")
14328 (defconst org-property-drawer-re
14329 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14330 org-property-end-re "\\)\n?")
14331 "Matches an entire property drawer.")
14333 (defconst org-clock-drawer-re
14334 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14335 org-property-end-re "\\)\n?")
14336 "Matches an entire clock drawer.")
14338 (defsubst org-re-property (property)
14339 "Return a regexp matching a PROPERTY line.
14340 Match group 1 will be set to the value."
14341 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14343 (defsubst org-re-property-keyword (property)
14344 "Return a regexp matching a PROPERTY line, possibly with no
14345 value for the property."
14346 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14348 (defun org-property-action ()
14349 "Do an action on properties."
14350 (interactive)
14351 (let (c)
14352 (org-at-property-p)
14353 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14354 (setq c (read-char-exclusive))
14355 (cond
14356 ((equal c ?s)
14357 (call-interactively 'org-set-property))
14358 ((equal c ?d)
14359 (call-interactively 'org-delete-property))
14360 ((equal c ?D)
14361 (call-interactively 'org-delete-property-globally))
14362 ((equal c ?c)
14363 (call-interactively 'org-compute-property-at-point))
14364 (t (error "No such property action %c" c)))))
14366 (defun org-inc-effort ()
14367 "Increment the value of the effort property in the current entry."
14368 (interactive)
14369 (org-set-effort nil t))
14371 (defun org-set-effort (&optional value increment)
14372 "Set the effort property of the current entry.
14373 With numerical prefix arg, use the nth allowed value, 0 stands for the
14374 10th allowed value.
14376 When INCREMENT is non-nil, set the property to the next allowed value."
14377 (interactive "P")
14378 (if (equal value 0) (setq value 10))
14379 (let* ((completion-ignore-case t)
14380 (prop org-effort-property)
14381 (cur (org-entry-get nil prop))
14382 (allowed (org-property-get-allowed-values nil prop 'table))
14383 (existing (mapcar 'list (org-property-values prop)))
14385 (val (cond
14386 ((stringp value) value)
14387 ((and allowed (integerp value))
14388 (or (car (nth (1- value) allowed))
14389 (car (org-last allowed))))
14390 ((and allowed increment)
14391 (or (caadr (member (list cur) allowed))
14392 (error "Allowed effort values are not set")))
14393 (allowed
14394 (message "Select 1-9,0, [RET%s]: %s"
14395 (if cur (concat "=" cur) "")
14396 (mapconcat 'car allowed " "))
14397 (setq rpl (read-char-exclusive))
14398 (if (equal rpl ?\r)
14400 (setq rpl (- rpl ?0))
14401 (if (equal rpl 0) (setq rpl 10))
14402 (if (and (> rpl 0) (<= rpl (length allowed)))
14403 (car (nth (1- rpl) allowed))
14404 (org-completing-read "Effort: " allowed nil))))
14406 (let (org-completion-use-ido org-completion-use-iswitchb)
14407 (org-completing-read
14408 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14409 (concat "[" cur "]") "")
14410 ": ")
14411 existing nil nil "" nil cur))))))
14412 (unless (equal (org-entry-get nil prop) val)
14413 (org-entry-put nil prop val))
14414 (message "%s is now %s" prop val)))
14416 (defun org-at-property-p ()
14417 "Is cursor inside a property drawer?"
14418 (save-excursion
14419 (beginning-of-line 1)
14420 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14421 (save-match-data ;; Used by calling procedures
14422 (let ((p (point))
14423 (range (unless (org-before-first-heading-p)
14424 (org-get-property-block))))
14425 (and range (<= (car range) p) (< p (cdr range))))))))
14427 (defun org-get-property-block (&optional beg end force)
14428 "Return the (beg . end) range of the body of the property drawer.
14429 BEG and END are the beginning and end of the current subtree, or of
14430 the part before the first headline. If they are not given, they will
14431 be found. If the drawer does not exist and FORCE is non-nil, create
14432 the drawer."
14433 (catch 'exit
14434 (save-excursion
14435 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14436 (progn (org-back-to-heading t) (point))))
14437 (end (or end (and (not (outline-next-heading)) (point-max))
14438 (point))))
14439 (goto-char beg)
14440 (if (re-search-forward org-property-start-re end t)
14441 (setq beg (1+ (match-end 0)))
14442 (if force
14443 (save-excursion
14444 (org-insert-property-drawer)
14445 (setq end (progn (outline-next-heading) (point))))
14446 (throw 'exit nil))
14447 (goto-char beg)
14448 (if (re-search-forward org-property-start-re end t)
14449 (setq beg (1+ (match-end 0)))))
14450 (if (re-search-forward org-property-end-re end t)
14451 (setq end (match-beginning 0))
14452 (or force (throw 'exit nil))
14453 (goto-char beg)
14454 (setq end beg)
14455 (org-indent-line)
14456 (insert ":END:\n"))
14457 (cons beg end)))))
14459 (defun org-entry-properties (&optional pom which specific)
14460 "Get all properties of the entry at point-or-marker POM.
14461 This includes the TODO keyword, the tags, time strings for deadline,
14462 scheduled, and clocking, and any additional properties defined in the
14463 entry. The return value is an alist, keys may occur multiple times
14464 if the property key was used several times.
14465 POM may also be nil, in which case the current entry is used.
14466 If WHICH is nil or `all', get all properties. If WHICH is
14467 `special' or `standard', only get that subclass. If WHICH
14468 is a string only get exactly this property. SPECIFIC can be a string, the
14469 specific property we are interested in. Specifying it can speed
14470 things up because then unnecessary parsing is avoided."
14471 (setq which (or which 'all))
14472 (org-with-point-at pom
14473 (let ((clockstr (substring org-clock-string 0 -1))
14474 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14475 (case-fold-search nil)
14476 beg end range props sum-props key key1 value string clocksum clocksumt)
14477 (save-excursion
14478 (when (condition-case nil
14479 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14480 (error nil))
14481 (setq beg (point))
14482 (setq sum-props (get-text-property (point) 'org-summaries))
14483 (setq clocksum (get-text-property (point) :org-clock-minutes)
14484 clocksumt (get-text-property (point) :org-clock-minutes-today))
14485 (outline-next-heading)
14486 (setq end (point))
14487 (when (memq which '(all special))
14488 ;; Get the special properties, like TODO and tags
14489 (goto-char beg)
14490 (when (and (or (not specific) (string= specific "TODO"))
14491 (looking-at org-todo-line-regexp) (match-end 2))
14492 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14493 (when (and (or (not specific) (string= specific "PRIORITY"))
14494 (looking-at org-priority-regexp))
14495 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14496 (when (or (not specific) (string= specific "FILE"))
14497 (push (cons "FILE" buffer-file-name) props))
14498 (when (and (or (not specific) (string= specific "TAGS"))
14499 (setq value (org-get-tags-string))
14500 (string-match "\\S-" value))
14501 (push (cons "TAGS" value) props))
14502 (when (and (or (not specific) (string= specific "ALLTAGS"))
14503 (setq value (org-get-tags-at)))
14504 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14505 ":"))
14506 props))
14507 (when (or (not specific) (string= specific "BLOCKED"))
14508 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14509 (when (or (not specific)
14510 (member specific
14511 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14512 "TIMESTAMP" "TIMESTAMP_IA")))
14513 (catch 'match
14514 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14515 (setq key (if (match-end 1)
14516 (substring (org-match-string-no-properties 1)
14517 0 -1))
14518 string (if (equal key clockstr)
14519 (org-trim
14520 (buffer-substring-no-properties
14521 (match-beginning 3) (goto-char
14522 (point-at-eol))))
14523 (substring (org-match-string-no-properties 3)
14524 1 -1)))
14525 ;; Get the correct property name from the key. This is
14526 ;; necessary if the user has configured time keywords.
14527 (setq key1 (concat key ":"))
14528 (cond
14529 ((not key)
14530 (setq key
14531 (if (= (char-after (match-beginning 3)) ?\[)
14532 "TIMESTAMP_IA" "TIMESTAMP")))
14533 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14534 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14535 ((equal key1 org-closed-string) (setq key "CLOSED"))
14536 ((equal key1 org-clock-string) (setq key "CLOCK")))
14537 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14538 (progn
14539 (push (cons key string) props)
14540 ;; no need to search further if match is found
14541 (throw 'match t))
14542 (when (or (equal key "CLOCK") (not (assoc key props)))
14543 (push (cons key string) props)))))))
14545 (when (memq which '(all standard))
14546 ;; Get the standard properties, like :PROP: ...
14547 (setq range (org-get-property-block beg end))
14548 (when range
14549 (goto-char (car range))
14550 (while (re-search-forward
14551 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14552 (cdr range) t)
14553 (setq key (org-match-string-no-properties 1)
14554 value (org-trim (or (org-match-string-no-properties 2) "")))
14555 (unless (member key excluded)
14556 (push (cons key (or value "")) props)))))
14557 (if clocksum
14558 (push (cons "CLOCKSUM"
14559 (org-columns-number-to-string (/ (float clocksum) 60.)
14560 'add_times))
14561 props))
14562 (if clocksumt
14563 (push (cons "CLOCKSUM_T"
14564 (org-columns-number-to-string (/ (float clocksumt) 60.)
14565 'add_times))
14566 props))
14567 (unless (assoc "CATEGORY" props)
14568 (push (cons "CATEGORY" (org-get-category)) props))
14569 (append sum-props (nreverse props)))))))
14571 (defun org-entry-get (pom property &optional inherit literal-nil)
14572 "Get value of PROPERTY for entry or content at point-or-marker POM.
14573 If INHERIT is non-nil and the entry does not have the property,
14574 then also check higher levels of the hierarchy.
14575 If INHERIT is the symbol `selective', use inheritance only if the setting
14576 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14577 If the property is present but empty, the return value is the empty string.
14578 If the property is not present at all, nil is returned.
14580 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14581 do not interpret it as the list atom nil. This is used for inheritance
14582 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14583 (org-with-point-at pom
14584 (if (and inherit (if (eq inherit 'selective)
14585 (org-property-inherit-p property)
14587 (org-entry-get-with-inheritance property literal-nil)
14588 (if (member property org-special-properties)
14589 ;; We need a special property. Use `org-entry-properties' to
14590 ;; retrieve it, but specify the wanted property
14591 (cdr (assoc property (org-entry-properties nil 'special property)))
14592 (let* ((range (org-get-property-block))
14593 (props (list (or (assoc property org-file-properties)
14594 (assoc property org-global-properties)
14595 (assoc property org-global-properties-fixed))))
14596 (ap (lambda (key)
14597 (when (re-search-forward
14598 (org-re-property key) (cdr range) t)
14599 (setq props
14600 (org-update-property-plist
14602 (if (match-end 1)
14603 (org-match-string-no-properties 1) "")
14604 props)))))
14605 val)
14606 (when (and range (goto-char (car range)))
14607 (funcall ap property)
14608 (goto-char (car range))
14609 (while (funcall ap (concat property "+")))
14610 (setq val (cdr (assoc property props)))
14611 (when val (if literal-nil val (org-not-nil val)))))))))
14613 (defun org-property-or-variable-value (var &optional inherit)
14614 "Check if there is a property fixing the value of VAR.
14615 If yes, return this value. If not, return the current value of the variable."
14616 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14617 (if (and prop (stringp prop) (string-match "\\S-" prop))
14618 (read prop)
14619 (symbol-value var))))
14621 (defun org-entry-delete (pom property)
14622 "Delete the property PROPERTY from entry at point-or-marker POM."
14623 (org-with-point-at pom
14624 (if (member property org-special-properties)
14625 nil ; cannot delete these properties.
14626 (let ((range (org-get-property-block)))
14627 (if (and range
14628 (goto-char (car range))
14629 (re-search-forward
14630 (org-re-property property)
14631 (cdr range) t))
14632 (progn
14633 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14635 nil)))))
14637 ;; Multi-values properties are properties that contain multiple values
14638 ;; These values are assumed to be single words, separated by whitespace.
14639 (defun org-entry-add-to-multivalued-property (pom property value)
14640 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14641 (let* ((old (org-entry-get pom property))
14642 (values (and old (org-split-string old "[ \t]"))))
14643 (setq value (org-entry-protect-space value))
14644 (unless (member value values)
14645 (setq values (cons value values))
14646 (org-entry-put pom property
14647 (mapconcat 'identity values " ")))))
14649 (defun org-entry-remove-from-multivalued-property (pom property value)
14650 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14651 (let* ((old (org-entry-get pom property))
14652 (values (and old (org-split-string old "[ \t]"))))
14653 (setq value (org-entry-protect-space value))
14654 (when (member value values)
14655 (setq values (delete value values))
14656 (org-entry-put pom property
14657 (mapconcat 'identity values " ")))))
14659 (defun org-entry-member-in-multivalued-property (pom property value)
14660 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14661 (let* ((old (org-entry-get pom property))
14662 (values (and old (org-split-string old "[ \t]"))))
14663 (setq value (org-entry-protect-space value))
14664 (member value values)))
14666 (defun org-entry-get-multivalued-property (pom property)
14667 "Return a list of values in a multivalued property."
14668 (let* ((value (org-entry-get pom property))
14669 (values (and value (org-split-string value "[ \t]"))))
14670 (mapcar 'org-entry-restore-space values)))
14672 (defun org-entry-put-multivalued-property (pom property &rest values)
14673 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14674 VALUES should be a list of strings. Spaces will be protected."
14675 (org-entry-put pom property
14676 (mapconcat 'org-entry-protect-space values " "))
14677 (let* ((value (org-entry-get pom property))
14678 (values (and value (org-split-string value "[ \t]"))))
14679 (mapcar 'org-entry-restore-space values)))
14681 (defun org-entry-protect-space (s)
14682 "Protect spaces and newline in string S."
14683 (while (string-match " " s)
14684 (setq s (replace-match "%20" t t s)))
14685 (while (string-match "\n" s)
14686 (setq s (replace-match "%0A" t t s)))
14689 (defun org-entry-restore-space (s)
14690 "Restore spaces and newline in string S."
14691 (while (string-match "%20" s)
14692 (setq s (replace-match " " t t s)))
14693 (while (string-match "%0A" s)
14694 (setq s (replace-match "\n" t t s)))
14697 (defvar org-entry-property-inherited-from (make-marker)
14698 "Marker pointing to the entry from where a property was inherited.
14699 Each call to `org-entry-get-with-inheritance' will set this marker to the
14700 location of the entry where the inheritance search matched. If there was
14701 no match, the marker will point nowhere.
14702 Note that also `org-entry-get' calls this function, if the INHERIT flag
14703 is set.")
14705 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14706 "Get PROPERTY of entry or content at point, search higher levels if needed.
14707 The search will stop at the first ancestor which has the property defined.
14708 If the value found is \"nil\", return nil to show that the property
14709 should be considered as undefined (this is the meaning of nil here).
14710 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14711 (move-marker org-entry-property-inherited-from nil)
14712 (let (tmp)
14713 (save-excursion
14714 (save-restriction
14715 (widen)
14716 (catch 'ex
14717 (while t
14718 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14719 (or (ignore-errors (org-back-to-heading t))
14720 (goto-char (point-min)))
14721 (move-marker org-entry-property-inherited-from (point))
14722 (throw 'ex tmp))
14723 (or (ignore-errors (org-up-heading-safe))
14724 (throw 'ex nil))))))
14725 (setq tmp (or tmp
14726 (cdr (assoc property org-file-properties))
14727 (cdr (assoc property org-global-properties))
14728 (cdr (assoc property org-global-properties-fixed))))
14729 (if literal-nil tmp (org-not-nil tmp))))
14731 (defvar org-property-changed-functions nil
14732 "Hook called when the value of a property has changed.
14733 Each hook function should accept two arguments, the name of the property
14734 and the new value.")
14736 (defun org-entry-put (pom property value)
14737 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14738 (org-with-point-at pom
14739 (org-back-to-heading t)
14740 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14741 range)
14742 (cond
14743 ((equal property "TODO")
14744 (when (and (stringp value) (string-match "\\S-" value)
14745 (not (member value org-todo-keywords-1)))
14746 (error "\"%s\" is not a valid TODO state" value))
14747 (if (or (not value)
14748 (not (string-match "\\S-" value)))
14749 (setq value 'none))
14750 (org-todo value)
14751 (org-set-tags nil 'align))
14752 ((equal property "PRIORITY")
14753 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14754 (string-to-char value) ?\ ))
14755 (org-set-tags nil 'align))
14756 ((equal property "CLOCKSUM")
14757 (if (not (re-search-forward
14758 (concat org-clock-string "\\]--\\(\\[[^]]+\\]\\)") nil t))
14759 (error "Cannot find a clock log")
14760 (goto-char (- (match-end 1) 2))
14761 (cond
14762 ((eq value 'earlier) (org-timestamp-down))
14763 ((eq value 'later) (org-timestamp-up)))
14764 (org-clock-sum-current-item)))
14765 ((equal property "SCHEDULED")
14766 (if (re-search-forward org-scheduled-time-regexp end t)
14767 (cond
14768 ((eq value 'earlier) (org-timestamp-change -1 'day))
14769 ((eq value 'later) (org-timestamp-change 1 'day))
14770 (t (call-interactively 'org-schedule)))
14771 (call-interactively 'org-schedule)))
14772 ((equal property "DEADLINE")
14773 (if (re-search-forward org-deadline-time-regexp end t)
14774 (cond
14775 ((eq value 'earlier) (org-timestamp-change -1 'day))
14776 ((eq value 'later) (org-timestamp-change 1 'day))
14777 (t (call-interactively 'org-deadline)))
14778 (call-interactively 'org-deadline)))
14779 ((member property org-special-properties)
14780 (error "The %s property can not yet be set with `org-entry-put'"
14781 property))
14782 (t ; a non-special property
14783 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14784 (setq range (org-get-property-block beg end 'force))
14785 (goto-char (car range))
14786 (if (re-search-forward
14787 (org-re-property-keyword property) (cdr range) t)
14788 (progn
14789 (delete-region (match-beginning 0) (match-end 0))
14790 (goto-char (match-beginning 0)))
14791 (goto-char (cdr range))
14792 (insert "\n")
14793 (backward-char 1)
14794 (org-indent-line))
14795 (insert ":" property ":")
14796 (and value (insert " " value))
14797 (org-indent-line)))))
14798 (run-hook-with-args 'org-property-changed-functions property value)))
14800 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14801 "Get all property keys in the current buffer.
14802 With INCLUDE-SPECIALS, also list the special properties that reflect things
14803 like tags and TODO state.
14804 With INCLUDE-DEFAULTS, also include properties that has special meaning
14805 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14806 and others.
14807 With INCLUDE-COLUMNS, also include property names given in COLUMN
14808 formats in the current buffer."
14809 (let (rtn range cfmt s p)
14810 (save-excursion
14811 (save-restriction
14812 (widen)
14813 (goto-char (point-min))
14814 (while (re-search-forward org-property-start-re nil t)
14815 (setq range (org-get-property-block))
14816 (goto-char (car range))
14817 (while (re-search-forward
14818 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14819 (cdr range) t)
14820 (add-to-list 'rtn (org-match-string-no-properties 1)))
14821 (outline-next-heading))))
14823 (when include-specials
14824 (setq rtn (append org-special-properties rtn)))
14826 (when include-defaults
14827 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14828 (add-to-list 'rtn org-effort-property))
14830 (when include-columns
14831 (save-excursion
14832 (save-restriction
14833 (widen)
14834 (goto-char (point-min))
14835 (while (re-search-forward
14836 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14837 nil t)
14838 (setq cfmt (match-string 2) s 0)
14839 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14840 cfmt s)
14841 (setq s (match-end 0)
14842 p (match-string 1 cfmt))
14843 (unless (or (equal p "ITEM")
14844 (member p org-special-properties))
14845 (add-to-list 'rtn (match-string 1 cfmt))))))))
14847 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14849 (defun org-property-values (key)
14850 "Return a list of all values of property KEY in the current buffer."
14851 (save-excursion
14852 (save-restriction
14853 (widen)
14854 (goto-char (point-min))
14855 (let ((re (org-re-property key))
14856 values)
14857 (while (re-search-forward re nil t)
14858 (add-to-list 'values (org-trim (match-string 1))))
14859 (delete "" values)))))
14861 (defun org-insert-property-drawer ()
14862 "Insert a property drawer into the current entry."
14863 (org-back-to-heading t)
14864 (looking-at org-outline-regexp)
14865 (let ((indent (if org-adapt-indentation
14866 (- (match-end 0) (match-beginning 0))
14868 (beg (point))
14869 (re (concat "^[ \t]*" org-keyword-time-regexp))
14870 end hiddenp)
14871 (outline-next-heading)
14872 (setq end (point))
14873 (goto-char beg)
14874 (while (re-search-forward re end t))
14875 (setq hiddenp (outline-invisible-p))
14876 (end-of-line 1)
14877 (and (equal (char-after) ?\n) (forward-char 1))
14878 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14879 (if (member (match-string 1) '("CLOCK:" ":END:"))
14880 ;; just skip this line
14881 (beginning-of-line 2)
14882 ;; Drawer start, find the end
14883 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14884 (beginning-of-line 1)))
14885 (org-skip-over-state-notes)
14886 (skip-chars-backward " \t\n\r")
14887 (if (eq (char-before) ?*) (forward-char 1))
14888 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14889 (beginning-of-line 0)
14890 (org-indent-to-column indent)
14891 (beginning-of-line 2)
14892 (org-indent-to-column indent)
14893 (beginning-of-line 0)
14894 (if hiddenp
14895 (save-excursion
14896 (org-back-to-heading t)
14897 (hide-entry))
14898 (org-flag-drawer t))))
14900 (defun org-insert-drawer (&optional arg drawer)
14901 "Insert a drawer at point.
14903 Optional argument DRAWER, when non-nil, is a string representing
14904 drawer's name. Otherwise, the user is prompted for a name.
14906 If a region is active, insert the drawer around that region
14907 instead.
14909 Point is left between drawer's boundaries."
14910 (interactive "P")
14911 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14912 "LOGBOOK"))
14913 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14914 ;; internally by Org. They are meant to be inserted
14915 ;; automatically.
14916 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14917 ;; Remove system drawers from list. Note: For some reason,
14918 ;; `org-completing-read' ignores the predicate while
14919 ;; `completing-read' handles it fine.
14920 (drawer (if arg "PROPERTIES"
14921 (or drawer
14922 (completing-read
14923 "Drawer: " org-drawers
14924 (lambda (d) (not (member d system-drawers))))))))
14925 (cond
14926 ;; With C-u, fall back on `org-insert-property-drawer'
14927 (arg (org-insert-property-drawer))
14928 ;; With an active region, insert a drawer at point.
14929 ((not (org-region-active-p))
14930 (progn
14931 (unless (bolp) (insert "\n"))
14932 (insert (format ":%s:\n\n:END:\n" drawer))
14933 (forward-line -2)))
14934 ;; Otherwise, insert the drawer at point
14936 (let ((rbeg (region-beginning))
14937 (rend (copy-marker (region-end))))
14938 (unwind-protect
14939 (progn
14940 (goto-char rbeg)
14941 (beginning-of-line)
14942 (when (save-excursion
14943 (re-search-forward org-outline-regexp-bol rend t))
14944 (error "Drawers cannot contain headlines"))
14945 ;; Position point at the beginning of the first
14946 ;; non-blank line in region. Insert drawer's opening
14947 ;; there, then indent it.
14948 (org-skip-whitespace)
14949 (beginning-of-line)
14950 (insert ":" drawer ":\n")
14951 (forward-line -1)
14952 (indent-for-tab-command)
14953 ;; Move point to the beginning of the first blank line
14954 ;; after the last non-blank line in region. Insert
14955 ;; drawer's closing, then indent it.
14956 (goto-char rend)
14957 (skip-chars-backward " \r\t\n")
14958 (insert "\n:END:")
14959 (indent-for-tab-command)
14960 (unless (eolp) (insert "\n")))
14961 ;; Clear marker, whatever the outcome of insertion is.
14962 (set-marker rend nil)))))))
14964 (defvar org-property-set-functions-alist nil
14965 "Property set function alist.
14966 Each entry should have the following format:
14968 (PROPERTY . READ-FUNCTION)
14970 The read function will be called with the same argument as
14971 `org-completing-read'.")
14973 (defun org-set-property-function (property)
14974 "Get the function that should be used to set PROPERTY.
14975 This is computed according to `org-property-set-functions-alist'."
14976 (or (cdr (assoc property org-property-set-functions-alist))
14977 'org-completing-read))
14979 (defun org-read-property-value (property)
14980 "Read PROPERTY value from user."
14981 (let* ((completion-ignore-case t)
14982 (allowed (org-property-get-allowed-values nil property 'table))
14983 (cur (org-entry-get nil property))
14984 (prompt (concat property " value"
14985 (if (and cur (string-match "\\S-" cur))
14986 (concat " [" cur "]") "") ": "))
14987 (set-function (org-set-property-function property))
14988 (val (if allowed
14989 (funcall set-function prompt allowed nil
14990 (not (get-text-property 0 'org-unrestricted
14991 (caar allowed))))
14992 (let (org-completion-use-ido org-completion-use-iswitchb)
14993 (funcall set-function prompt
14994 (mapcar 'list (org-property-values property))
14995 nil nil "" nil cur)))))
14996 (if (equal val "")
14998 val)))
15000 (defvar org-last-set-property nil)
15001 (defun org-read-property-name ()
15002 "Read a property name."
15003 (let* ((completion-ignore-case t)
15004 (keys (org-buffer-property-keys nil t t))
15005 (default-prop (or (save-excursion
15006 (save-match-data
15007 (beginning-of-line)
15008 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15009 (null (string= (match-string 1) "END"))
15010 (match-string 1))))
15011 org-last-set-property))
15012 (property (org-icompleting-read
15013 (concat "Property"
15014 (if default-prop (concat " [" default-prop "]") "")
15015 ": ")
15016 (mapcar 'list keys)
15017 nil nil nil nil
15018 default-prop
15020 (if (member property keys)
15021 property
15022 (or (cdr (assoc (downcase property)
15023 (mapcar (lambda (x) (cons (downcase x) x))
15024 keys)))
15025 property))))
15027 (defun org-set-property (property value)
15028 "In the current entry, set PROPERTY to VALUE.
15029 When called interactively, this will prompt for a property name, offering
15030 completion on existing and default properties. And then it will prompt
15031 for a value, offering completion either on allowed values (via an inherited
15032 xxx_ALL property) or on existing values in other instances of this property
15033 in the current file."
15034 (interactive (list nil nil))
15035 (let* ((property (or property (org-read-property-name)))
15036 (value (or value (org-read-property-value property)))
15037 (fn (cdr (assoc property org-properties-postprocess-alist))))
15038 (setq org-last-set-property property)
15039 ;; Possibly postprocess the inserted value:
15040 (when fn (setq value (funcall fn value)))
15041 (unless (equal (org-entry-get nil property) value)
15042 (org-entry-put nil property value))))
15044 (defun org-delete-property (property)
15045 "In the current entry, delete PROPERTY."
15046 (interactive
15047 (let* ((completion-ignore-case t)
15048 (prop (org-icompleting-read "Property: "
15049 (org-entry-properties nil 'standard))))
15050 (list prop)))
15051 (message "Property %s %s" property
15052 (if (org-entry-delete nil property)
15053 "deleted"
15054 "was not present in the entry")))
15056 (defun org-delete-property-globally (property)
15057 "Remove PROPERTY globally, from all entries."
15058 (interactive
15059 (let* ((completion-ignore-case t)
15060 (prop (org-icompleting-read
15061 "Globally remove property: "
15062 (mapcar 'list (org-buffer-property-keys)))))
15063 (list prop)))
15064 (save-excursion
15065 (save-restriction
15066 (widen)
15067 (goto-char (point-min))
15068 (let ((cnt 0))
15069 (while (re-search-forward
15070 (org-re-property property)
15071 nil t)
15072 (setq cnt (1+ cnt))
15073 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15074 (message "Property \"%s\" removed from %d entries" property cnt)))))
15076 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15078 (defun org-compute-property-at-point ()
15079 "Compute the property at point.
15080 This looks for an enclosing column format, extracts the operator and
15081 then applies it to the property in the column format's scope."
15082 (interactive)
15083 (unless (org-at-property-p)
15084 (error "Not at a property"))
15085 (let ((prop (org-match-string-no-properties 2)))
15086 (org-columns-get-format-and-top-level)
15087 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15088 (error "No operator defined for property %s" prop))
15089 (org-columns-compute prop)))
15091 (defvar org-property-allowed-value-functions nil
15092 "Hook for functions supplying allowed values for a specific property.
15093 The functions must take a single argument, the name of the property, and
15094 return a flat list of allowed values. If \":ETC\" is one of
15095 the values, this means that these values are intended as defaults for
15096 completion, but that other values should be allowed too.
15097 The functions must return nil if they are not responsible for this
15098 property.")
15100 (defun org-property-get-allowed-values (pom property &optional table)
15101 "Get allowed values for the property PROPERTY.
15102 When TABLE is non-nil, return an alist that can directly be used for
15103 completion."
15104 (let (vals)
15105 (cond
15106 ((equal property "TODO")
15107 (setq vals (org-with-point-at pom
15108 (append org-todo-keywords-1 '("")))))
15109 ((equal property "PRIORITY")
15110 (let ((n org-lowest-priority))
15111 (while (>= n org-highest-priority)
15112 (push (char-to-string n) vals)
15113 (setq n (1- n)))))
15114 ((member property org-special-properties))
15115 ((setq vals (run-hook-with-args-until-success
15116 'org-property-allowed-value-functions property)))
15118 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15119 (when (and vals (string-match "\\S-" vals))
15120 (setq vals (car (read-from-string (concat "(" vals ")"))))
15121 (setq vals (mapcar (lambda (x)
15122 (cond ((stringp x) x)
15123 ((numberp x) (number-to-string x))
15124 ((symbolp x) (symbol-name x))
15125 (t "???")))
15126 vals)))))
15127 (when (member ":ETC" vals)
15128 (setq vals (remove ":ETC" vals))
15129 (org-add-props (car vals) '(org-unrestricted t)))
15130 (if table (mapcar 'list vals) vals)))
15132 (defun org-property-previous-allowed-value (&optional previous)
15133 "Switch to the next allowed value for this property."
15134 (interactive)
15135 (org-property-next-allowed-value t))
15137 (defun org-property-next-allowed-value (&optional previous)
15138 "Switch to the next allowed value for this property."
15139 (interactive)
15140 (unless (org-at-property-p)
15141 (error "Not at a property"))
15142 (let* ((key (match-string 2))
15143 (value (match-string 3))
15144 (allowed (or (org-property-get-allowed-values (point) key)
15145 (and (member value '("[ ]" "[-]" "[X]"))
15146 '("[ ]" "[X]"))))
15147 nval)
15148 (unless allowed
15149 (error "Allowed values for this property have not been defined"))
15150 (if previous (setq allowed (reverse allowed)))
15151 (if (member value allowed)
15152 (setq nval (car (cdr (member value allowed)))))
15153 (setq nval (or nval (car allowed)))
15154 (if (equal nval value)
15155 (error "Only one allowed value for this property"))
15156 (org-at-property-p)
15157 (replace-match (concat " :" key ": " nval) t t)
15158 (org-indent-line)
15159 (beginning-of-line 1)
15160 (skip-chars-forward " \t")
15161 (run-hook-with-args 'org-property-changed-functions key nval)))
15163 (defun org-find-olp (path &optional this-buffer)
15164 "Return a marker pointing to the entry at outline path OLP.
15165 If anything goes wrong, throw an error.
15166 You can wrap this call to catch the error like this:
15168 (condition-case msg
15169 (org-mobile-locate-entry (match-string 4))
15170 (error (nth 1 msg)))
15172 The return value will then be either a string with the error message,
15173 or a marker if everything is OK.
15175 If THIS-BUFFER is set, the outline path does not contain a file,
15176 only headings."
15177 (let* ((file (if this-buffer buffer-file-name (pop path)))
15178 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15179 (level 1)
15180 (lmin 1)
15181 (lmax 1)
15182 limit re end found pos heading cnt flevel)
15183 (unless buffer (error "File not found :%s" file))
15184 (with-current-buffer buffer
15185 (save-excursion
15186 (save-restriction
15187 (widen)
15188 (setq limit (point-max))
15189 (goto-char (point-min))
15190 (while (setq heading (pop path))
15191 (setq re (format org-complex-heading-regexp-format
15192 (regexp-quote heading)))
15193 (setq cnt 0 pos (point))
15194 (while (re-search-forward re end t)
15195 (setq level (- (match-end 1) (match-beginning 1)))
15196 (if (and (>= level lmin) (<= level lmax))
15197 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15198 (when (= cnt 0) (error "Heading not found on level %d: %s"
15199 lmax heading))
15200 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15201 lmax heading))
15202 (goto-char found)
15203 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15204 (setq end (save-excursion (org-end-of-subtree t t))))
15205 (when (org-at-heading-p)
15206 (move-marker (make-marker) (point))))))))
15208 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15209 "Find node HEADING in BUFFER.
15210 Return a marker to the heading if it was found, or nil if not.
15211 If POS-ONLY is set, return just the position instead of a marker.
15213 The heading text must match exact, but it may have a TODO keyword,
15214 a priority cookie and tags in the standard locations."
15215 (with-current-buffer (or buffer (current-buffer))
15216 (save-excursion
15217 (save-restriction
15218 (widen)
15219 (goto-char (point-min))
15220 (let (case-fold-search)
15221 (if (re-search-forward
15222 (format org-complex-heading-regexp-format
15223 (regexp-quote heading)) nil t)
15224 (if pos-only
15225 (match-beginning 0)
15226 (move-marker (make-marker) (match-beginning 0)))))))))
15228 (defun org-find-exact-heading-in-directory (heading &optional dir)
15229 "Find Org node headline HEADING in all .org files in directory DIR.
15230 When the target headline is found, return a marker to this location."
15231 (let ((files (directory-files (or dir default-directory)
15232 nil "\\`[^.#].*\\.org\\'"))
15233 file visiting m buffer)
15234 (catch 'found
15235 (while (setq file (pop files))
15236 (message "trying %s" file)
15237 (setq visiting (org-find-base-buffer-visiting file))
15238 (setq buffer (or visiting (find-file-noselect file)))
15239 (setq m (org-find-exact-headline-in-buffer
15240 heading buffer))
15241 (when (and (not m) (not visiting)) (kill-buffer buffer))
15242 (and m (throw 'found m))))))
15244 (defun org-find-entry-with-id (ident)
15245 "Locate the entry that contains the ID property with exact value IDENT.
15246 IDENT can be a string, a symbol or a number, this function will search for
15247 the string representation of it.
15248 Return the position where this entry starts, or nil if there is no such entry."
15249 (interactive "sID: ")
15250 (let ((id (cond
15251 ((stringp ident) ident)
15252 ((symbol-name ident) (symbol-name ident))
15253 ((numberp ident) (number-to-string ident))
15254 (t (error "IDENT %s must be a string, symbol or number" ident))))
15255 (case-fold-search nil))
15256 (save-excursion
15257 (save-restriction
15258 (widen)
15259 (goto-char (point-min))
15260 (when (re-search-forward
15261 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15262 nil t)
15263 (org-back-to-heading t)
15264 (point))))))
15266 ;;;; Timestamps
15268 (defvar org-last-changed-timestamp nil)
15269 (defvar org-last-inserted-timestamp nil
15270 "The last time stamp inserted with `org-insert-time-stamp'.")
15271 (defvar org-time-was-given) ; dynamically scoped parameter
15272 (defvar org-end-time-was-given) ; dynamically scoped parameter
15273 (defvar org-ts-what) ; dynamically scoped parameter
15275 (defun org-time-stamp (arg &optional inactive)
15276 "Prompt for a date/time and insert a time stamp.
15277 If the user specifies a time like HH:MM or if this command is
15278 called with at least one prefix argument, the time stamp contains
15279 the date and the time. Otherwise, only the date is be included.
15281 All parts of a date not specified by the user is filled in from
15282 the current date/time. So if you just press return without
15283 typing anything, the time stamp will represent the current
15284 date/time.
15286 If there is already a timestamp at the cursor, it will be
15287 modified.
15289 With two universal prefix arguments, insert an active timestamp
15290 with the current time without prompting the user."
15291 (interactive "P")
15292 (let* ((ts nil)
15293 (default-time
15294 ;; Default time is either today, or, when entering a range,
15295 ;; the range start.
15296 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15297 (save-excursion
15298 (re-search-backward
15299 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15300 (- (point) 20) t)))
15301 (apply 'encode-time (org-parse-time-string (match-string 1)))
15302 (current-time)))
15303 (default-input (and ts (org-get-compact-tod ts)))
15304 (repeater (save-excursion
15305 (save-match-data
15306 (beginning-of-line)
15307 (when (re-search-forward
15308 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15309 (save-excursion (progn (end-of-line) (point))) t)
15310 (match-string 0)))))
15311 org-time-was-given org-end-time-was-given time)
15312 (cond
15313 ((and (org-at-timestamp-p t)
15314 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15315 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15316 (insert "--")
15317 (setq time (let ((this-command this-command))
15318 (org-read-date arg 'totime nil nil
15319 default-time default-input inactive)))
15320 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15321 ((org-at-timestamp-p t)
15322 (setq time (let ((this-command this-command))
15323 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15324 (when (org-at-timestamp-p t) ; just to get the match data
15325 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15326 (replace-match "")
15327 (setq org-last-changed-timestamp
15328 (org-insert-time-stamp
15329 time (or org-time-was-given arg)
15330 inactive nil nil (list org-end-time-was-given)))
15331 (when repeater (goto-char (1- (point))) (insert " " repeater)
15332 (setq org-last-changed-timestamp
15333 (concat (substring org-last-inserted-timestamp 0 -1)
15334 " " repeater ">"))))
15335 (message "Timestamp updated"))
15336 ((equal arg '(16))
15337 (org-insert-time-stamp (current-time) t))
15339 (setq time (let ((this-command this-command))
15340 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15341 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15342 nil nil (list org-end-time-was-given))))))
15344 ;; FIXME: can we use this for something else, like computing time differences?
15345 (defun org-get-compact-tod (s)
15346 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15347 (let* ((t1 (match-string 1 s))
15348 (h1 (string-to-number (match-string 2 s)))
15349 (m1 (string-to-number (match-string 3 s)))
15350 (t2 (and (match-end 4) (match-string 5 s)))
15351 (h2 (and t2 (string-to-number (match-string 6 s))))
15352 (m2 (and t2 (string-to-number (match-string 7 s))))
15353 dh dm)
15354 (if (not t2)
15356 (setq dh (- h2 h1) dm (- m2 m1))
15357 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15358 (concat t1 "+" (number-to-string dh)
15359 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15361 (defun org-time-stamp-inactive (&optional arg)
15362 "Insert an inactive time stamp.
15363 An inactive time stamp is enclosed in square brackets instead of angle
15364 brackets. It is inactive in the sense that it does not trigger agenda entries,
15365 does not link to the calendar and cannot be changed with the S-cursor keys.
15366 So these are more for recording a certain time/date."
15367 (interactive "P")
15368 (org-time-stamp arg 'inactive))
15370 (defvar org-date-ovl (make-overlay 1 1))
15371 (overlay-put org-date-ovl 'face 'org-date-selected)
15372 (org-detach-overlay org-date-ovl)
15374 (defvar org-ans1) ; dynamically scoped parameter
15375 (defvar org-ans2) ; dynamically scoped parameter
15377 (defvar org-plain-time-of-day-regexp) ; defined below
15379 (defvar org-overriding-default-time nil) ; dynamically scoped
15380 (defvar org-read-date-overlay nil)
15381 (defvar org-dcst nil) ; dynamically scoped
15382 (defvar org-read-date-history nil)
15383 (defvar org-read-date-final-answer nil)
15384 (defvar org-read-date-analyze-futurep nil)
15385 (defvar org-read-date-analyze-forced-year nil)
15386 (defvar org-read-date-inactive)
15388 (defun org-read-date (&optional org-with-time to-time from-string prompt
15389 default-time default-input inactive)
15390 "Read a date, possibly a time, and make things smooth for the user.
15391 The prompt will suggest to enter an ISO date, but you can also enter anything
15392 which will at least partially be understood by `parse-time-string'.
15393 Unrecognized parts of the date will default to the current day, month, year,
15394 hour and minute. If this command is called to replace a timestamp at point,
15395 or to enter the second timestamp of a range, the default time is taken
15396 from the existing stamp. Furthermore, the command prefers the future,
15397 so if you are giving a date where the year is not given, and the day-month
15398 combination is already past in the current year, it will assume you
15399 mean next year. For details, see the manual. A few examples:
15401 3-2-5 --> 2003-02-05
15402 feb 15 --> currentyear-02-15
15403 2/15 --> currentyear-02-15
15404 sep 12 9 --> 2009-09-12
15405 12:45 --> today 12:45
15406 22 sept 0:34 --> currentyear-09-22 0:34
15407 12 --> currentyear-currentmonth-12
15408 Fri --> nearest Friday (today or later)
15409 etc.
15411 Furthermore you can specify a relative date by giving, as the *first* thing
15412 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15413 change in days weeks, months, years.
15414 With a single plus or minus, the date is relative to today. With a double
15415 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15416 +4d --> four days from today
15417 +4 --> same as above
15418 +2w --> two weeks from today
15419 ++5 --> five days from default date
15421 The function understands only English month and weekday abbreviations.
15423 While prompting, a calendar is popped up - you can also select the
15424 date with the mouse (button 1). The calendar shows a period of three
15425 months. To scroll it to other months, use the keys `>' and `<'.
15426 If you don't like the calendar, turn it off with
15427 \(setq org-read-date-popup-calendar nil)
15429 With optional argument TO-TIME, the date will immediately be converted
15430 to an internal time.
15431 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15432 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15433 still enter a time, and this function will inform the calling routine
15434 about this change. The calling routine may then choose to change the
15435 format used to insert the time stamp into the buffer to include the time.
15436 With optional argument FROM-STRING, read from this string instead from
15437 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15438 the time/date that is used for everything that is not specified by the
15439 user."
15440 (require 'parse-time)
15441 (let* ((org-time-stamp-rounding-minutes
15442 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15443 (org-dcst org-display-custom-times)
15444 (ct (org-current-time))
15445 (org-def (or org-overriding-default-time default-time ct))
15446 (org-defdecode (decode-time org-def))
15447 (dummy (progn
15448 (when (< (nth 2 org-defdecode) org-extend-today-until)
15449 (setcar (nthcdr 2 org-defdecode) -1)
15450 (setcar (nthcdr 1 org-defdecode) 59)
15451 (setq org-def (apply 'encode-time org-defdecode)
15452 org-defdecode (decode-time org-def)))))
15453 (calendar-frame-setup nil)
15454 (calendar-setup nil)
15455 (calendar-move-hook nil)
15456 (calendar-view-diary-initially-flag nil)
15457 (calendar-view-holidays-initially-flag nil)
15458 (timestr (format-time-string
15459 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15460 (prompt (concat (if prompt (concat prompt " ") "")
15461 (format "Date+time [%s]: " timestr)))
15462 ans (org-ans0 "") org-ans1 org-ans2 final)
15464 (cond
15465 (from-string (setq ans from-string))
15466 (org-read-date-popup-calendar
15467 (save-excursion
15468 (save-window-excursion
15469 (calendar)
15470 (org-eval-in-calendar '(setq cursor-type nil) t)
15471 (unwind-protect
15472 (progn
15473 (calendar-forward-day (- (time-to-days org-def)
15474 (calendar-absolute-from-gregorian
15475 (calendar-current-date))))
15476 (org-eval-in-calendar nil t)
15477 (let* ((old-map (current-local-map))
15478 (map (copy-keymap calendar-mode-map))
15479 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15480 (org-defkey map (kbd "RET") 'org-calendar-select)
15481 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15482 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15483 (org-defkey minibuffer-local-map [(meta shift left)]
15484 (lambda () (interactive)
15485 (org-eval-in-calendar '(calendar-backward-month 1))))
15486 (org-defkey minibuffer-local-map [(meta shift right)]
15487 (lambda () (interactive)
15488 (org-eval-in-calendar '(calendar-forward-month 1))))
15489 (org-defkey minibuffer-local-map [(meta shift up)]
15490 (lambda () (interactive)
15491 (org-eval-in-calendar '(calendar-backward-year 1))))
15492 (org-defkey minibuffer-local-map [(meta shift down)]
15493 (lambda () (interactive)
15494 (org-eval-in-calendar '(calendar-forward-year 1))))
15495 (org-defkey minibuffer-local-map [?\e (shift left)]
15496 (lambda () (interactive)
15497 (org-eval-in-calendar '(calendar-backward-month 1))))
15498 (org-defkey minibuffer-local-map [?\e (shift right)]
15499 (lambda () (interactive)
15500 (org-eval-in-calendar '(calendar-forward-month 1))))
15501 (org-defkey minibuffer-local-map [?\e (shift up)]
15502 (lambda () (interactive)
15503 (org-eval-in-calendar '(calendar-backward-year 1))))
15504 (org-defkey minibuffer-local-map [?\e (shift down)]
15505 (lambda () (interactive)
15506 (org-eval-in-calendar '(calendar-forward-year 1))))
15507 (org-defkey minibuffer-local-map [(shift up)]
15508 (lambda () (interactive)
15509 (org-eval-in-calendar '(calendar-backward-week 1))))
15510 (org-defkey minibuffer-local-map [(shift down)]
15511 (lambda () (interactive)
15512 (org-eval-in-calendar '(calendar-forward-week 1))))
15513 (org-defkey minibuffer-local-map [(shift left)]
15514 (lambda () (interactive)
15515 (org-eval-in-calendar '(calendar-backward-day 1))))
15516 (org-defkey minibuffer-local-map [(shift right)]
15517 (lambda () (interactive)
15518 (org-eval-in-calendar '(calendar-forward-day 1))))
15519 (org-defkey minibuffer-local-map ">"
15520 (lambda () (interactive)
15521 (org-eval-in-calendar '(scroll-calendar-left 1))))
15522 (org-defkey minibuffer-local-map "<"
15523 (lambda () (interactive)
15524 (org-eval-in-calendar '(scroll-calendar-right 1))))
15525 (org-defkey minibuffer-local-map "\C-v"
15526 (lambda () (interactive)
15527 (org-eval-in-calendar
15528 '(calendar-scroll-left-three-months 1))))
15529 (org-defkey minibuffer-local-map "\M-v"
15530 (lambda () (interactive)
15531 (org-eval-in-calendar
15532 '(calendar-scroll-right-three-months 1))))
15533 (run-hooks 'org-read-date-minibuffer-setup-hook)
15534 (unwind-protect
15535 (progn
15536 (use-local-map map)
15537 (setq org-read-date-inactive inactive)
15538 (add-hook 'post-command-hook 'org-read-date-display)
15539 (setq org-ans0 (read-string prompt default-input
15540 'org-read-date-history nil))
15541 ;; org-ans0: from prompt
15542 ;; org-ans1: from mouse click
15543 ;; org-ans2: from calendar motion
15544 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15545 (remove-hook 'post-command-hook 'org-read-date-display)
15546 (use-local-map old-map)
15547 (when org-read-date-overlay
15548 (delete-overlay org-read-date-overlay)
15549 (setq org-read-date-overlay nil)))))
15550 (bury-buffer "*Calendar*")))))
15552 (t ; Naked prompt only
15553 (unwind-protect
15554 (setq ans (read-string prompt default-input
15555 'org-read-date-history timestr))
15556 (when org-read-date-overlay
15557 (delete-overlay org-read-date-overlay)
15558 (setq org-read-date-overlay nil)))))
15560 (setq final (org-read-date-analyze ans org-def org-defdecode))
15562 (when org-read-date-analyze-forced-year
15563 (message "Year was forced into %s"
15564 (if org-read-date-force-compatible-dates
15565 "compatible range (1970-2037)"
15566 "range representable on this machine"))
15567 (ding))
15569 ;; One round trip to get rid of 34th of August and stuff like that....
15570 (setq final (decode-time (apply 'encode-time final)))
15572 (setq org-read-date-final-answer ans)
15574 (if to-time
15575 (apply 'encode-time final)
15576 (if (and (boundp 'org-time-was-given) org-time-was-given)
15577 (format "%04d-%02d-%02d %02d:%02d"
15578 (nth 5 final) (nth 4 final) (nth 3 final)
15579 (nth 2 final) (nth 1 final))
15580 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15582 (defvar org-def)
15583 (defvar org-defdecode)
15584 (defvar org-with-time)
15585 (defun org-read-date-display ()
15586 "Display the current date prompt interpretation in the minibuffer."
15587 (when org-read-date-display-live
15588 (when org-read-date-overlay
15589 (delete-overlay org-read-date-overlay))
15590 (when (minibufferp (current-buffer))
15591 (save-excursion
15592 (end-of-line 1)
15593 (while (not (equal (buffer-substring
15594 (max (point-min) (- (point) 4)) (point))
15595 " "))
15596 (insert " ")))
15597 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15598 " " (or org-ans1 org-ans2)))
15599 (org-end-time-was-given nil)
15600 (f (org-read-date-analyze ans org-def org-defdecode))
15601 (fmts (if org-dcst
15602 org-time-stamp-custom-formats
15603 org-time-stamp-formats))
15604 (fmt (if (or org-with-time
15605 (and (boundp 'org-time-was-given) org-time-was-given))
15606 (cdr fmts)
15607 (car fmts)))
15608 (txt (format-time-string fmt (apply 'encode-time f)))
15609 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15610 (txt (concat "=> " txt)))
15611 (when (and org-end-time-was-given
15612 (string-match org-plain-time-of-day-regexp txt))
15613 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15614 org-end-time-was-given
15615 (substring txt (match-end 0)))))
15616 (when org-read-date-analyze-futurep
15617 (setq txt (concat txt " (=>F)")))
15618 (setq org-read-date-overlay
15619 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15620 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15622 (defun org-read-date-analyze (ans org-def org-defdecode)
15623 "Analyze the combined answer of the date prompt."
15624 ;; FIXME: cleanup and comment
15625 (let ((nowdecode (decode-time (current-time)))
15626 delta deltan deltaw deltadef year month day
15627 hour minute second wday pm h2 m2 tl wday1
15628 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15629 (setq org-read-date-analyze-futurep nil
15630 org-read-date-analyze-forced-year nil)
15631 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15632 (setq ans "+0"))
15634 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15635 (unless (save-match-data (string-match org-plain-time-of-day-regexp ans))
15636 (setq ans (replace-match "" t t ans)
15637 deltan (car delta)
15638 deltaw (nth 1 delta)
15639 deltadef (nth 2 delta))))
15641 ;; Check if there is an iso week date in there
15642 ;; If yes, store the info and postpone interpreting it until the rest
15643 ;; of the parsing is done
15644 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15645 (setq iso-year (if (match-end 1)
15646 (org-small-year-to-year
15647 (string-to-number (match-string 1 ans))))
15648 iso-weekday (if (match-end 3)
15649 (string-to-number (match-string 3 ans)))
15650 iso-week (string-to-number (match-string 2 ans)))
15651 (setq ans (replace-match "" t t ans)))
15653 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15654 (when (string-match
15655 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15656 (setq year (if (match-end 2)
15657 (string-to-number (match-string 2 ans))
15658 (progn (setq kill-year t)
15659 (string-to-number (format-time-string "%Y"))))
15660 month (string-to-number (match-string 3 ans))
15661 day (string-to-number (match-string 4 ans)))
15662 (if (< year 100) (setq year (+ 2000 year)))
15663 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15664 t nil ans)))
15666 ;; Help matching dotted european dates
15667 (when (string-match
15668 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15669 (setq year (if (match-end 3)
15670 (string-to-number (match-string 3 ans))
15671 (progn (setq kill-year t)
15672 (string-to-number (format-time-string "%Y"))))
15673 day (string-to-number (match-string 1 ans))
15674 month (string-to-number (match-string 2 ans))
15675 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15676 t nil ans)))
15678 ;; Help matching american dates, like 5/30 or 5/30/7
15679 (when (string-match
15680 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15681 (setq year (if (match-end 4)
15682 (string-to-number (match-string 4 ans))
15683 (progn (setq kill-year t)
15684 (string-to-number (format-time-string "%Y"))))
15685 month (string-to-number (match-string 1 ans))
15686 day (string-to-number (match-string 2 ans)))
15687 (if (< year 100) (setq year (+ 2000 year)))
15688 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15689 t nil ans)))
15690 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15691 ;; If there is a time with am/pm, and *no* time without it, we convert
15692 ;; so that matching will be successful.
15693 (loop for i from 1 to 2 do ; twice, for end time as well
15694 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15695 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15696 (setq hour (string-to-number (match-string 1 ans))
15697 minute (if (match-end 3)
15698 (string-to-number (match-string 3 ans))
15700 pm (equal ?p
15701 (string-to-char (downcase (match-string 4 ans)))))
15702 (if (and (= hour 12) (not pm))
15703 (setq hour 0)
15704 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15705 (setq ans (replace-match (format "%02d:%02d" hour minute)
15706 t t ans))))
15708 ;; Check if a time range is given as a duration
15709 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15710 (setq hour (string-to-number (match-string 1 ans))
15711 h2 (+ hour (string-to-number (match-string 3 ans)))
15712 minute (string-to-number (match-string 2 ans))
15713 m2 (+ minute (if (match-end 5) (string-to-number
15714 (match-string 5 ans))0)))
15715 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15716 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15717 t t ans)))
15719 ;; Check if there is a time range
15720 (when (boundp 'org-end-time-was-given)
15721 (setq org-time-was-given nil)
15722 (when (and (string-match org-plain-time-of-day-regexp ans)
15723 (match-end 8))
15724 (setq org-end-time-was-given (match-string 8 ans))
15725 (setq ans (concat (substring ans 0 (match-beginning 7))
15726 (substring ans (match-end 7))))))
15728 (setq tl (parse-time-string ans)
15729 day (or (nth 3 tl) (nth 3 org-defdecode))
15730 month (or (nth 4 tl)
15731 (if (and org-read-date-prefer-future
15732 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15733 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15734 (nth 4 org-defdecode)))
15735 year (or (and (not kill-year) (nth 5 tl))
15736 (if (and org-read-date-prefer-future
15737 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15738 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15739 (nth 5 org-defdecode)))
15740 hour (or (nth 2 tl) (nth 2 org-defdecode))
15741 minute (or (nth 1 tl) (nth 1 org-defdecode))
15742 second (or (nth 0 tl) 0)
15743 wday (nth 6 tl))
15745 (when (and (eq org-read-date-prefer-future 'time)
15746 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15747 (equal day (nth 3 nowdecode))
15748 (equal month (nth 4 nowdecode))
15749 (equal year (nth 5 nowdecode))
15750 (nth 2 tl)
15751 (or (< (nth 2 tl) (nth 2 nowdecode))
15752 (and (= (nth 2 tl) (nth 2 nowdecode))
15753 (nth 1 tl)
15754 (< (nth 1 tl) (nth 1 nowdecode)))))
15755 (setq day (1+ day)
15756 futurep t))
15758 ;; Special date definitions below
15759 (cond
15760 (iso-week
15761 ;; There was an iso week
15762 (require 'cal-iso)
15763 (setq futurep nil)
15764 (setq year (or iso-year year)
15765 day (or iso-weekday wday 1)
15766 wday nil ; to make sure that the trigger below does not match
15767 iso-date (calendar-gregorian-from-absolute
15768 (calendar-absolute-from-iso
15769 (list iso-week day year))))
15770 ; FIXME: Should we also push ISO weeks into the future?
15771 ; (when (and org-read-date-prefer-future
15772 ; (not iso-year)
15773 ; (< (calendar-absolute-from-gregorian iso-date)
15774 ; (time-to-days (current-time))))
15775 ; (setq year (1+ year)
15776 ; iso-date (calendar-gregorian-from-absolute
15777 ; (calendar-absolute-from-iso
15778 ; (list iso-week day year)))))
15779 (setq month (car iso-date)
15780 year (nth 2 iso-date)
15781 day (nth 1 iso-date)))
15782 (deltan
15783 (setq futurep nil)
15784 (unless deltadef
15785 (let ((now (decode-time (current-time))))
15786 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15787 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15788 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15789 ((equal deltaw "m") (setq month (+ month deltan)))
15790 ((equal deltaw "y") (setq year (+ year deltan)))))
15791 ((and wday (not (nth 3 tl)))
15792 ;; Weekday was given, but no day, so pick that day in the week
15793 ;; on or after the derived date.
15794 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15795 (unless (equal wday wday1)
15796 (setq day (+ day (% (- wday wday1 -7) 7))))))
15797 (if (and (boundp 'org-time-was-given)
15798 (nth 2 tl))
15799 (setq org-time-was-given t))
15800 (if (< year 100) (setq year (+ 2000 year)))
15801 ;; Check of the date is representable
15802 (if org-read-date-force-compatible-dates
15803 (progn
15804 (if (< year 1970)
15805 (setq year 1970 org-read-date-analyze-forced-year t))
15806 (if (> year 2037)
15807 (setq year 2037 org-read-date-analyze-forced-year t)))
15808 (condition-case nil
15809 (ignore (encode-time second minute hour day month year))
15810 (error
15811 (setq year (nth 5 org-defdecode))
15812 (setq org-read-date-analyze-forced-year t))))
15813 (setq org-read-date-analyze-futurep futurep)
15814 (list second minute hour day month year)))
15816 (defvar parse-time-weekdays)
15817 (defun org-read-date-get-relative (s today default)
15818 "Check string S for special relative date string.
15819 TODAY and DEFAULT are internal times, for today and for a default.
15820 Return shift list (N what def-flag)
15821 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15822 N is the number of WHATs to shift.
15823 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15824 the DEFAULT date rather than TODAY."
15825 (require 'parse-time)
15826 (when (and
15827 (string-match
15828 (concat
15829 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15830 "\\([0-9]+\\)?"
15831 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15832 "\\([ \t]\\|$\\)") s)
15833 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15834 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15835 (string-to-char (substring (match-string 1 s) -1))
15836 ?+))
15837 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15838 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15839 (what (if (match-end 3) (match-string 3 s) "d"))
15840 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15841 (date (if rel default today))
15842 (wday (nth 6 (decode-time date)))
15843 delta)
15844 (if wday1
15845 (progn
15846 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15847 (if (= dir ?-) (setq delta (- delta 7)))
15848 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15849 (list delta "d" rel))
15850 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15852 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15853 "Turn a user-specified date into the internal representation.
15854 The internal representation needed by the calendar is (month day year).
15855 This is a wrapper to handle the brain-dead convention in calendar that
15856 user function argument order change dependent on argument order."
15857 (if (boundp 'calendar-date-style)
15858 (cond
15859 ((eq calendar-date-style 'american)
15860 (list arg1 arg2 arg3))
15861 ((eq calendar-date-style 'european)
15862 (list arg2 arg1 arg3))
15863 ((eq calendar-date-style 'iso)
15864 (list arg2 arg3 arg1)))
15865 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15866 (if (org-bound-and-true-p european-calendar-style)
15867 (list arg2 arg1 arg3)
15868 (list arg1 arg2 arg3)))))
15870 (defun org-eval-in-calendar (form &optional keepdate)
15871 "Eval FORM in the calendar window and return to current window.
15872 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15873 otherwise stick to the current value of `org-ans2'."
15874 (let ((sf (selected-frame))
15875 (sw (selected-window)))
15876 (select-window (get-buffer-window "*Calendar*" t))
15877 (eval form)
15878 (when (and (not keepdate) (calendar-cursor-to-date))
15879 (let* ((date (calendar-cursor-to-date))
15880 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15881 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15882 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15883 (select-window sw)
15884 (org-select-frame-set-input-focus sf)))
15886 (defun org-calendar-select ()
15887 "Return to `org-read-date' with the date currently selected.
15888 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15889 (interactive)
15890 (when (calendar-cursor-to-date)
15891 (let* ((date (calendar-cursor-to-date))
15892 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15893 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15894 (if (active-minibuffer-window) (exit-minibuffer))))
15896 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15897 "Insert a date stamp for the date given by the internal TIME.
15898 WITH-HM means use the stamp format that includes the time of the day.
15899 INACTIVE means use square brackets instead of angular ones, so that the
15900 stamp will not contribute to the agenda.
15901 PRE and POST are optional strings to be inserted before and after the
15902 stamp.
15903 The command returns the inserted time stamp."
15904 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15905 stamp)
15906 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15907 (insert-before-markers (or pre ""))
15908 (when (listp extra)
15909 (setq extra (car extra))
15910 (if (and (stringp extra)
15911 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15912 (setq extra (format "-%02d:%02d"
15913 (string-to-number (match-string 1 extra))
15914 (string-to-number (match-string 2 extra))))
15915 (setq extra nil)))
15916 (when extra
15917 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15918 (insert-before-markers (setq stamp (format-time-string fmt time)))
15919 (insert-before-markers (or post ""))
15920 (setq org-last-inserted-timestamp stamp)))
15922 (defun org-toggle-time-stamp-overlays ()
15923 "Toggle the use of custom time stamp formats."
15924 (interactive)
15925 (setq org-display-custom-times (not org-display-custom-times))
15926 (unless org-display-custom-times
15927 (let ((p (point-min)) (bmp (buffer-modified-p)))
15928 (while (setq p (next-single-property-change p 'display))
15929 (if (and (get-text-property p 'display)
15930 (eq (get-text-property p 'face) 'org-date))
15931 (remove-text-properties
15932 p (setq p (next-single-property-change p 'display))
15933 '(display t))))
15934 (set-buffer-modified-p bmp)))
15935 (if (featurep 'xemacs)
15936 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15937 (org-restart-font-lock)
15938 (setq org-table-may-need-update t)
15939 (if org-display-custom-times
15940 (message "Time stamps are overlaid with custom format")
15941 (message "Time stamp overlays removed")))
15943 (defun org-display-custom-time (beg end)
15944 "Overlay modified time stamp format over timestamp between BEG and END."
15945 (let* ((ts (buffer-substring beg end))
15946 t1 w1 with-hm tf time str w2 (off 0))
15947 (save-match-data
15948 (setq t1 (org-parse-time-string ts t))
15949 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15950 (setq off (- (match-end 0) (match-beginning 0)))))
15951 (setq end (- end off))
15952 (setq w1 (- end beg)
15953 with-hm (and (nth 1 t1) (nth 2 t1))
15954 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15955 time (org-fix-decoded-time t1)
15956 str (org-add-props
15957 (format-time-string
15958 (substring tf 1 -1) (apply 'encode-time time))
15959 nil 'mouse-face 'highlight)
15960 w2 (length str))
15961 (if (not (= w2 w1))
15962 (add-text-properties (1+ beg) (+ 2 beg)
15963 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15964 (if (featurep 'xemacs)
15965 (progn
15966 (put-text-property beg end 'invisible t)
15967 (put-text-property beg end 'end-glyph (make-glyph str)))
15968 (put-text-property beg end 'display str))))
15970 (defun org-translate-time (string)
15971 "Translate all timestamps in STRING to custom format.
15972 But do this only if the variable `org-display-custom-times' is set."
15973 (when org-display-custom-times
15974 (save-match-data
15975 (let* ((start 0)
15976 (re org-ts-regexp-both)
15977 t1 with-hm inactive tf time str beg end)
15978 (while (setq start (string-match re string start))
15979 (setq beg (match-beginning 0)
15980 end (match-end 0)
15981 t1 (save-match-data
15982 (org-parse-time-string (substring string beg end) t))
15983 with-hm (and (nth 1 t1) (nth 2 t1))
15984 inactive (equal (substring string beg (1+ beg)) "[")
15985 tf (funcall (if with-hm 'cdr 'car)
15986 org-time-stamp-custom-formats)
15987 time (org-fix-decoded-time t1)
15988 str (format-time-string
15989 (concat
15990 (if inactive "[" "<") (substring tf 1 -1)
15991 (if inactive "]" ">"))
15992 (apply 'encode-time time))
15993 string (replace-match str t t string)
15994 start (+ start (length str)))))))
15995 string)
15997 (defun org-fix-decoded-time (time)
15998 "Set 0 instead of nil for the first 6 elements of time.
15999 Don't touch the rest."
16000 (let ((n 0))
16001 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16003 (defun org-days-to-time (timestamp-string)
16004 "Difference between TIMESTAMP-STRING and now in days."
16005 (- (time-to-days (org-time-string-to-time timestamp-string))
16006 (time-to-days (current-time))))
16008 (defun org-deadline-close (timestamp-string &optional ndays)
16009 "Is the time in TIMESTAMP-STRING close to the current date?"
16010 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16011 (and (< (org-days-to-time timestamp-string) ndays)
16012 (not (org-entry-is-done-p))))
16014 (defun org-get-wdays (ts)
16015 "Get the deadline lead time appropriate for timestring TS."
16016 (cond
16017 ((<= org-deadline-warning-days 0)
16018 ;; 0 or negative, enforce this value no matter what
16019 (- org-deadline-warning-days))
16020 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16021 ;; lead time is specified.
16022 (floor (* (string-to-number (match-string 1 ts))
16023 (cdr (assoc (match-string 2 ts)
16024 '(("d" . 1) ("w" . 7)
16025 ("m" . 30.4) ("y" . 365.25)))))))
16026 ;; go for the default.
16027 (t org-deadline-warning-days)))
16029 (defun org-calendar-select-mouse (ev)
16030 "Return to `org-read-date' with the date currently selected.
16031 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16032 (interactive "e")
16033 (mouse-set-point ev)
16034 (when (calendar-cursor-to-date)
16035 (let* ((date (calendar-cursor-to-date))
16036 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16037 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16038 (if (active-minibuffer-window) (exit-minibuffer))))
16040 (defun org-check-deadlines (ndays)
16041 "Check if there are any deadlines due or past due.
16042 A deadline is considered due if it happens within `org-deadline-warning-days'
16043 days from today's date. If the deadline appears in an entry marked DONE,
16044 it is not shown. The prefix arg NDAYS can be used to test that many
16045 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16046 (interactive "P")
16047 (let* ((org-warn-days
16048 (cond
16049 ((equal ndays '(4)) 100000)
16050 (ndays (prefix-numeric-value ndays))
16051 (t (abs org-deadline-warning-days))))
16052 (case-fold-search nil)
16053 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16054 (callback
16055 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16057 (message "%d deadlines past-due or due within %d days"
16058 (org-occur regexp nil callback)
16059 org-warn-days)))
16061 (defsubst org-re-timestamp (type)
16062 "Return a regexp for timestamp TYPE.
16063 Allowed values for TYPE are:
16065 all: all timestamps
16066 active: only active timestamps (<...>)
16067 inactive: only inactive timestamps ([...])
16068 scheduled: only scheduled timestamps
16069 deadline: only deadline timestamps
16071 When TYPE is nil, fall back on returning a regexp that matches
16072 both scheduled and deadline timestamps."
16073 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16074 ((eq type 'active) org-ts-regexp)
16075 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16076 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16077 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16078 ((eq type 'scheduled-or-deadline)
16079 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16081 (defun org-check-before-date (date)
16082 "Check if there are deadlines or scheduled entries before DATE."
16083 (interactive (list (org-read-date)))
16084 (let ((case-fold-search nil)
16085 (regexp (org-re-timestamp org-ts-type))
16086 (callback
16087 (lambda () (time-less-p
16088 (org-time-string-to-time (match-string 1))
16089 (org-time-string-to-time date)))))
16090 (message "%d entries before %s"
16091 (org-occur regexp nil callback) date)))
16093 (defun org-check-after-date (date)
16094 "Check if there are deadlines or scheduled entries after DATE."
16095 (interactive (list (org-read-date)))
16096 (let ((case-fold-search nil)
16097 (regexp (org-re-timestamp org-ts-type))
16098 (callback
16099 (lambda () (not
16100 (time-less-p
16101 (org-time-string-to-time (match-string 1))
16102 (org-time-string-to-time date))))))
16103 (message "%d entries after %s"
16104 (org-occur regexp nil callback) date)))
16106 (defun org-check-dates-range (start-date end-date)
16107 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16108 (interactive (list (org-read-date nil nil nil "Range starts")
16109 (org-read-date nil nil nil "Range end")))
16110 (let ((case-fold-search nil)
16111 (regexp (org-re-timestamp org-ts-type))
16112 (callback
16113 (lambda ()
16114 (let ((match (match-string 1)))
16115 (and
16116 (not (time-less-p
16117 (org-time-string-to-time match)
16118 (org-time-string-to-time start-date)))
16119 (time-less-p
16120 (org-time-string-to-time match)
16121 (org-time-string-to-time end-date)))))))
16122 (message "%d entries between %s and %s"
16123 (org-occur regexp nil callback) start-date end-date)))
16125 (defun org-evaluate-time-range (&optional to-buffer)
16126 "Evaluate a time range by computing the difference between start and end.
16127 Normally the result is just printed in the echo area, but with prefix arg
16128 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16129 If the time range is actually in a table, the result is inserted into the
16130 next column.
16131 For time difference computation, a year is assumed to be exactly 365
16132 days in order to avoid rounding problems."
16133 (interactive "P")
16135 (org-clock-update-time-maybe)
16136 (save-excursion
16137 (unless (org-at-date-range-p t)
16138 (goto-char (point-at-bol))
16139 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16140 (if (not (org-at-date-range-p t))
16141 (error "Not at a time-stamp range, and none found in current line")))
16142 (let* ((ts1 (match-string 1))
16143 (ts2 (match-string 2))
16144 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16145 (match-end (match-end 0))
16146 (time1 (org-time-string-to-time ts1))
16147 (time2 (org-time-string-to-time ts2))
16148 (t1 (org-float-time time1))
16149 (t2 (org-float-time time2))
16150 (diff (abs (- t2 t1)))
16151 (negative (< (- t2 t1) 0))
16152 ;; (ys (floor (* 365 24 60 60)))
16153 (ds (* 24 60 60))
16154 (hs (* 60 60))
16155 (fy "%dy %dd %02d:%02d")
16156 (fy1 "%dy %dd")
16157 (fd "%dd %02d:%02d")
16158 (fd1 "%dd")
16159 (fh "%02d:%02d")
16160 y d h m align)
16161 (if havetime
16162 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16164 d (floor (/ diff ds)) diff (mod diff ds)
16165 h (floor (/ diff hs)) diff (mod diff hs)
16166 m (floor (/ diff 60)))
16167 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16169 d (floor (+ (/ diff ds) 0.5))
16170 h 0 m 0))
16171 (if (not to-buffer)
16172 (message "%s" (org-make-tdiff-string y d h m))
16173 (if (org-at-table-p)
16174 (progn
16175 (goto-char match-end)
16176 (setq align t)
16177 (and (looking-at " *|") (goto-char (match-end 0))))
16178 (goto-char match-end))
16179 (if (looking-at
16180 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16181 (replace-match ""))
16182 (if negative (insert " -"))
16183 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16184 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16185 (insert " " (format fh h m))))
16186 (if align (org-table-align))
16187 (message "Time difference inserted")))))
16189 (defun org-make-tdiff-string (y d h m)
16190 (let ((fmt "")
16191 (l nil))
16192 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16193 l (push y l)))
16194 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16195 l (push d l)))
16196 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16197 l (push h l)))
16198 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16199 l (push m l)))
16200 (apply 'format fmt (nreverse l))))
16202 (defun org-time-string-to-time (s &optional buffer pos)
16203 (condition-case errdata
16204 (apply 'encode-time (org-parse-time-string s))
16205 (error (error "Bad timestamp `%s'%s\nError was: %s"
16206 s (if (not (and buffer pos))
16208 (format " at %d in buffer `%s'" pos buffer))
16209 (cdr errdata)))))
16211 (defun org-time-string-to-seconds (s)
16212 (org-float-time (org-time-string-to-time s)))
16214 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16215 "Convert a time stamp to an absolute day number.
16216 If there is a specifier for a cyclic time stamp, get the closest date to
16217 DAYNR.
16218 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16219 The variable date is bound by the calendar when this is called."
16220 (cond
16221 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16222 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16223 daynr
16224 (+ daynr 1000)))
16225 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16226 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16227 (time-to-days (current-time))) (match-string 0 s)
16228 prefer show-all))
16229 (t (time-to-days
16230 (condition-case errdata
16231 (apply 'encode-time (org-parse-time-string s))
16232 (error (error "Bad timestamp `%s'%s\nError was: %s"
16233 s (if (not (and buffer pos))
16235 (format " at %d in buffer `%s'" pos buffer))
16236 (cdr errdata))))))))
16238 (defun org-days-to-iso-week (days)
16239 "Return the iso week number."
16240 (require 'cal-iso)
16241 (car (calendar-iso-from-absolute days)))
16243 (defun org-small-year-to-year (year)
16244 "Convert 2-digit years into 4-digit years.
16245 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16246 The year 2000 cannot be abbreviated. Any year larger than 99
16247 is returned unchanged."
16248 (if (< year 38)
16249 (setq year (+ 2000 year))
16250 (if (< year 100)
16251 (setq year (+ 1900 year))))
16252 year)
16254 (defun org-time-from-absolute (d)
16255 "Return the time corresponding to date D.
16256 D may be an absolute day number, or a calendar-type list (month day year)."
16257 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16258 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16260 (defun org-calendar-holiday ()
16261 "List of holidays, for Diary display in Org-mode."
16262 (require 'holidays)
16263 (let ((hl (funcall
16264 (if (fboundp 'calendar-check-holidays)
16265 'calendar-check-holidays 'check-calendar-holidays) date)))
16266 (if hl (mapconcat 'identity hl "; "))))
16268 (defun org-diary-sexp-entry (sexp entry date)
16269 "Process a SEXP diary ENTRY for DATE."
16270 (require 'diary-lib)
16271 (let ((result (if calendar-debug-sexp
16272 (let ((stack-trace-on-error t))
16273 (eval (car (read-from-string sexp))))
16274 (condition-case nil
16275 (eval (car (read-from-string sexp)))
16276 (error
16277 (beep)
16278 (message "Bad sexp at line %d in %s: %s"
16279 (org-current-line)
16280 (buffer-file-name) sexp)
16281 (sleep-for 2))))))
16282 (cond ((stringp result) (split-string result "; "))
16283 ((and (consp result)
16284 (not (consp (cdr result)))
16285 (stringp (cdr result))) (cdr result))
16286 ((and (consp result)
16287 (stringp (car result))) result)
16288 (result entry))))
16290 (defun org-diary-to-ical-string (frombuf)
16291 "Get iCalendar entries from diary entries in buffer FROMBUF.
16292 This uses the icalendar.el library."
16293 (let* ((tmpdir (if (featurep 'xemacs)
16294 (temp-directory)
16295 temporary-file-directory))
16296 (tmpfile (make-temp-name
16297 (expand-file-name "orgics" tmpdir)))
16298 buf rtn b e)
16299 (with-current-buffer frombuf
16300 (icalendar-export-region (point-min) (point-max) tmpfile)
16301 (setq buf (find-buffer-visiting tmpfile))
16302 (set-buffer buf)
16303 (goto-char (point-min))
16304 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16305 (setq b (match-beginning 0)))
16306 (goto-char (point-max))
16307 (if (re-search-backward "^END:VEVENT" nil t)
16308 (setq e (match-end 0)))
16309 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16310 (kill-buffer buf)
16311 (delete-file tmpfile)
16312 rtn))
16314 (defun org-closest-date (start current change prefer show-all)
16315 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16316 When PREFER is `past', return a date that is either CURRENT or past.
16317 When PREFER is `future', return a date that is either CURRENT or future.
16318 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16319 ;; Make the proper lists from the dates
16320 (catch 'exit
16321 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16322 dn dw sday cday n1 n2 n0
16323 d m y y1 y2 date1 date2 nmonths nm ny m2)
16325 (setq start (org-date-to-gregorian start)
16326 current (org-date-to-gregorian
16327 (if show-all
16328 current
16329 (time-to-days (current-time))))
16330 sday (calendar-absolute-from-gregorian start)
16331 cday (calendar-absolute-from-gregorian current))
16333 (if (<= cday sday) (throw 'exit sday))
16335 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16336 (setq dn (string-to-number (match-string 1 change))
16337 dw (cdr (assoc (match-string 2 change) a1)))
16338 (error "Invalid change specifier: %s" change))
16339 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16340 (cond
16341 ((eq dw 'day)
16342 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16343 n2 (+ n1 dn)))
16344 ((eq dw 'year)
16345 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16346 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16347 (setq date1 (list m d y1)
16348 n1 (calendar-absolute-from-gregorian date1)
16349 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16350 n2 (calendar-absolute-from-gregorian date2)))
16351 ((eq dw 'month)
16352 ;; approx number of month between the two dates
16353 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16354 ;; How often does dn fit in there?
16355 (setq d (nth 1 start) m (car start) y (nth 2 start)
16356 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16357 m (+ m nm)
16358 ny (floor (/ m 12))
16359 y (+ y ny)
16360 m (- m (* ny 12)))
16361 (while (> m 12) (setq m (- m 12) y (1+ y)))
16362 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16363 (setq m2 (+ m dn) y2 y)
16364 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16365 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16366 (while (<= n2 cday)
16367 (setq n1 n2 m m2 y y2)
16368 (setq m2 (+ m dn) y2 y)
16369 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16370 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16371 ;; Make sure n1 is the earlier date
16372 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16373 (if show-all
16374 (cond
16375 ((eq prefer 'past) (if (= cday n2) n2 n1))
16376 ((eq prefer 'future) (if (= cday n1) n1 n2))
16377 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16378 (cond
16379 ((eq prefer 'past) (if (= cday n2) n2 n1))
16380 ((eq prefer 'future) (if (= cday n1) n1 n2))
16381 (t (if (= cday n1) n1 n2)))))))
16383 (defun org-date-to-gregorian (date)
16384 "Turn any specification of DATE into a Gregorian date for the calendar."
16385 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16386 ((and (listp date) (= (length date) 3)) date)
16387 ((stringp date)
16388 (setq date (org-parse-time-string date))
16389 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16390 ((listp date)
16391 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16393 (defun org-parse-time-string (s &optional nodefault)
16394 "Parse the standard Org-mode time string.
16395 This should be a lot faster than the normal `parse-time-string'.
16396 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16397 hour and minute fields will be nil if not given."
16398 (if (string-match org-ts-regexp0 s)
16399 (list 0
16400 (if (or (match-beginning 8) (not nodefault))
16401 (string-to-number (or (match-string 8 s) "0")))
16402 (if (or (match-beginning 7) (not nodefault))
16403 (string-to-number (or (match-string 7 s) "0")))
16404 (string-to-number (match-string 4 s))
16405 (string-to-number (match-string 3 s))
16406 (string-to-number (match-string 2 s))
16407 nil nil nil)
16408 (error "Not a standard Org-mode time string: %s" s)))
16410 (defun org-timestamp-up (&optional arg)
16411 "Increase the date item at the cursor by one.
16412 If the cursor is on the year, change the year. If it is on the month,
16413 the day or the time, change that.
16414 With prefix ARG, change by that many units."
16415 (interactive "p")
16416 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16418 (defun org-timestamp-down (&optional arg)
16419 "Decrease the date item at the cursor by one.
16420 If the cursor is on the year, change the year. If it is on the month,
16421 the day or the time, change that.
16422 With prefix ARG, change by that many units."
16423 (interactive "p")
16424 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16426 (defun org-timestamp-up-day (&optional arg)
16427 "Increase the date in the time stamp by one day.
16428 With prefix ARG, change that many days."
16429 (interactive "p")
16430 (if (and (not (org-at-timestamp-p t))
16431 (org-at-heading-p))
16432 (org-todo 'up)
16433 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16435 (defun org-timestamp-down-day (&optional arg)
16436 "Decrease the date in the time stamp by one day.
16437 With prefix ARG, change that many days."
16438 (interactive "p")
16439 (if (and (not (org-at-timestamp-p t))
16440 (org-at-heading-p))
16441 (org-todo 'down)
16442 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16444 (defun org-at-timestamp-p (&optional inactive-ok)
16445 "Determine if the cursor is in or at a timestamp."
16446 (interactive)
16447 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16448 (pos (point))
16449 (ans (or (looking-at tsr)
16450 (save-excursion
16451 (skip-chars-backward "^[<\n\r\t")
16452 (if (> (point) (point-min)) (backward-char 1))
16453 (and (looking-at tsr)
16454 (> (- (match-end 0) pos) -1))))))
16455 (and ans
16456 (boundp 'org-ts-what)
16457 (setq org-ts-what
16458 (cond
16459 ((= pos (match-beginning 0)) 'bracket)
16460 ;; Point is considered to be "on the bracket" whether
16461 ;; it's really on it or right after it.
16462 ((= pos (1- (match-end 0))) 'bracket)
16463 ((= pos (match-end 0)) 'after)
16464 ((org-pos-in-match-range pos 2) 'year)
16465 ((org-pos-in-match-range pos 3) 'month)
16466 ((org-pos-in-match-range pos 7) 'hour)
16467 ((org-pos-in-match-range pos 8) 'minute)
16468 ((or (org-pos-in-match-range pos 4)
16469 (org-pos-in-match-range pos 5)) 'day)
16470 ((and (> pos (or (match-end 8) (match-end 5)))
16471 (< pos (match-end 0)))
16472 (- pos (or (match-end 8) (match-end 5))))
16473 (t 'day))))
16474 ans))
16476 (defun org-toggle-timestamp-type ()
16477 "Toggle the type (<active> or [inactive]) of a time stamp."
16478 (interactive)
16479 (when (org-at-timestamp-p t)
16480 (let ((beg (match-beginning 0)) (end (match-end 0))
16481 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16482 (save-excursion
16483 (goto-char beg)
16484 (while (re-search-forward "[][<>]" end t)
16485 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16486 t t)))
16487 (message "Timestamp is now %sactive"
16488 (if (equal (char-after beg) ?<) "" "in")))))
16490 (defvar org-clock-history) ; defined in org-clock.el
16491 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16492 (defun org-timestamp-change (n &optional what updown)
16493 "Change the date in the time stamp at point.
16494 The date will be changed by N times WHAT. WHAT can be `day', `month',
16495 `year', `minute', `second'. If WHAT is not given, the cursor position
16496 in the timestamp determines what will be changed."
16497 (let ((origin (point)) origin-cat
16498 with-hm inactive
16499 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16500 org-ts-what
16501 extra rem
16502 ts time time0 fixnext clrgx)
16503 (if (not (org-at-timestamp-p t))
16504 (error "Not at a timestamp"))
16505 (if (and (not what) (eq org-ts-what 'bracket))
16506 (org-toggle-timestamp-type)
16507 ;; Point isn't on brackets. Remember the part of the time-stamp
16508 ;; the point was in. Indeed, size of time-stamps may change,
16509 ;; but point must be kept in the same category nonetheless.
16510 (setq origin-cat org-ts-what)
16511 (if (and (not what) (not (eq org-ts-what 'day))
16512 org-display-custom-times
16513 (get-text-property (point) 'display)
16514 (not (get-text-property (1- (point)) 'display)))
16515 (setq org-ts-what 'day))
16516 (setq org-ts-what (or what org-ts-what)
16517 inactive (= (char-after (match-beginning 0)) ?\[)
16518 ts (match-string 0))
16519 (replace-match "")
16520 (if (string-match
16521 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16523 (setq extra (match-string 1 ts)))
16524 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16525 (setq with-hm t))
16526 (setq time0 (org-parse-time-string ts))
16527 (when (and updown
16528 (eq org-ts-what 'minute)
16529 (not current-prefix-arg))
16530 ;; This looks like s-up and s-down. Change by one rounding step.
16531 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16532 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16533 (setcar (cdr time0) (+ (nth 1 time0)
16534 (if (> n 0) (- rem) (- dm rem))))))
16535 (setq time
16536 (encode-time (or (car time0) 0)
16537 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16538 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16539 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16540 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16541 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16542 (nthcdr 6 time0)))
16543 (when (and (member org-ts-what '(hour minute))
16544 extra
16545 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16546 (setq extra (org-modify-ts-extra
16547 extra
16548 (if (eq org-ts-what 'hour) 2 5)
16549 n dm)))
16550 (when (integerp org-ts-what)
16551 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16552 (if (eq what 'calendar)
16553 (let ((cal-date (org-get-date-from-calendar)))
16554 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16555 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16556 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16557 (setcar time0 (or (car time0) 0))
16558 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16559 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16560 (setq time (apply 'encode-time time0))))
16561 ;; Insert the new time-stamp, and ensure point stays in the same
16562 ;; category as before (i.e. not after the last position in that
16563 ;; category).
16564 (let ((pos (point)))
16565 ;; Stay before inserted string. `save-excursion' is of no use.
16566 (setq org-last-changed-timestamp
16567 (org-insert-time-stamp time with-hm inactive nil nil extra))
16568 (goto-char pos))
16569 (save-match-data
16570 (looking-at org-ts-regexp3)
16571 (goto-char (cond
16572 ;; `day' category ends before `hour' if any, or at
16573 ;; the end of the day name.
16574 ((eq origin-cat 'day)
16575 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16576 ((eq origin-cat 'hour) (min (match-end 7) origin))
16577 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16578 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16579 ;; `year' and `month' have both fixed size: point
16580 ;; couldn't have moved into another part.
16581 (t origin))))
16582 ;; Update clock if on a CLOCK line.
16583 (org-clock-update-time-maybe)
16584 ;; Maybe adjust the closest clock in `org-clock-history'
16585 (when org-clock-adjust-closest
16586 (if (not (and (org-at-clock-log-p)
16587 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16588 org-clock-history))))))
16589 (message "No clock to adjust")
16590 (cond ((save-excursion ; fix previous clock?
16591 (re-search-backward org-ts-regexp0 nil t)
16592 (org-looking-back (concat org-clock-string " \\[")))
16593 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16594 ((save-excursion ; fix next clock?
16595 (re-search-backward org-ts-regexp0 nil t)
16596 (looking-at (concat org-ts-regexp0 "\\] =>")))
16597 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16598 (save-window-excursion
16599 ;; Find closest clock to point, adjust the previous/next one in history
16600 (let* ((p (save-excursion (org-back-to-heading t)))
16601 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16602 (clfixnth
16603 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16604 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16605 (if (not clfixpos)
16606 (message "No clock to adjust")
16607 (save-excursion
16608 (org-goto-marker-or-bmk clfixpos)
16609 (org-show-subtree)
16610 (when (re-search-forward clrgx nil t)
16611 (goto-char (match-beginning 1))
16612 (let (org-clock-adjust-closest)
16613 (org-timestamp-change n org-ts-what updown))
16614 (message "Clock adjusted in %s for heading: %s"
16615 (file-name-nondirectory (buffer-file-name))
16616 (org-get-heading t t)))))))))
16617 ;; Try to recenter the calendar window, if any.
16618 (if (and org-calendar-follow-timestamp-change
16619 (get-buffer-window "*Calendar*" t)
16620 (memq org-ts-what '(day month year)))
16621 (org-recenter-calendar (time-to-days time))))))
16623 (defun org-modify-ts-extra (s pos n dm)
16624 "Change the different parts of the lead-time and repeat fields in timestamp."
16625 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16626 ng h m new rem)
16627 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16628 (cond
16629 ((or (org-pos-in-match-range pos 2)
16630 (org-pos-in-match-range pos 3))
16631 (setq m (string-to-number (match-string 3 s))
16632 h (string-to-number (match-string 2 s)))
16633 (if (org-pos-in-match-range pos 2)
16634 (setq h (+ h n))
16635 (setq n (* dm (org-no-warnings (signum n))))
16636 (when (not (= 0 (setq rem (% m dm))))
16637 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16638 (setq m (+ m n)))
16639 (if (< m 0) (setq m (+ m 60) h (1- h)))
16640 (if (> m 59) (setq m (- m 60) h (1+ h)))
16641 (setq h (min 24 (max 0 h)))
16642 (setq ng 1 new (format "-%02d:%02d" h m)))
16643 ((org-pos-in-match-range pos 6)
16644 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16645 ((org-pos-in-match-range pos 5)
16646 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16648 ((org-pos-in-match-range pos 9)
16649 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16650 ((org-pos-in-match-range pos 8)
16651 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16653 (when ng
16654 (setq s (concat
16655 (substring s 0 (match-beginning ng))
16657 (substring s (match-end ng))))))
16660 (defun org-recenter-calendar (date)
16661 "If the calendar is visible, recenter it to DATE."
16662 (let ((cwin (get-buffer-window "*Calendar*" t)))
16663 (when cwin
16664 (let ((calendar-move-hook nil))
16665 (with-selected-window cwin
16666 (calendar-goto-date (if (listp date) date
16667 (calendar-gregorian-from-absolute date))))))))
16669 (defun org-goto-calendar (&optional arg)
16670 "Go to the Emacs calendar at the current date.
16671 If there is a time stamp in the current line, go to that date.
16672 A prefix ARG can be used to force the current date."
16673 (interactive "P")
16674 (let ((tsr org-ts-regexp) diff
16675 (calendar-move-hook nil)
16676 (calendar-view-holidays-initially-flag nil)
16677 (calendar-view-diary-initially-flag nil))
16678 (if (or (org-at-timestamp-p)
16679 (save-excursion
16680 (beginning-of-line 1)
16681 (looking-at (concat ".*" tsr))))
16682 (let ((d1 (time-to-days (current-time)))
16683 (d2 (time-to-days
16684 (org-time-string-to-time (match-string 1)))))
16685 (setq diff (- d2 d1))))
16686 (calendar)
16687 (calendar-goto-today)
16688 (if (and diff (not arg)) (calendar-forward-day diff))))
16690 (defun org-get-date-from-calendar ()
16691 "Return a list (month day year) of date at point in calendar."
16692 (with-current-buffer "*Calendar*"
16693 (save-match-data
16694 (calendar-cursor-to-date))))
16696 (defun org-date-from-calendar ()
16697 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16698 If there is already a time stamp at the cursor position, update it."
16699 (interactive)
16700 (if (org-at-timestamp-p t)
16701 (org-timestamp-change 0 'calendar)
16702 (let ((cal-date (org-get-date-from-calendar)))
16703 (org-insert-time-stamp
16704 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16706 (defun org-minutes-to-hh:mm-string (m)
16707 "Compute H:MM from a number of minutes."
16708 (let ((h (/ m 60)))
16709 (setq m (- m (* 60 h)))
16710 (format org-time-clocksum-format h m)))
16712 (defun org-hh:mm-string-to-minutes (s)
16713 "Convert a string H:MM to a number of minutes.
16714 If the string is just a number, interpret it as minutes.
16715 In fact, the first hh:mm or number in the string will be taken,
16716 there can be extra stuff in the string.
16717 If no number is found, the return value is 0."
16718 (cond
16719 ((integerp s) s)
16720 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16721 (+ (* (string-to-number (match-string 1 s)) 60)
16722 (string-to-number (match-string 2 s))))
16723 ((string-match "\\([0-9]+\\)" s)
16724 (string-to-number (match-string 1 s)))
16725 (t 0)))
16727 (defcustom org-effort-durations
16728 `(("h" . 60)
16729 ("d" . ,(* 60 8))
16730 ("w" . ,(* 60 8 5))
16731 ("m" . ,(* 60 8 5 4))
16732 ("y" . ,(* 60 8 5 40)))
16733 "Conversion factor to minutes for an effort modifier.
16735 Each entry has the form (MODIFIER . MINUTES).
16737 In an effort string, a number followed by MODIFIER is multiplied
16738 by the specified number of MINUTES to obtain an effort in
16739 minutes.
16741 For example, if the value of this variable is ((\"hours\" . 60)), then an
16742 effort string \"2hours\" is equivalent to 120 minutes."
16743 :group 'org-agenda
16744 :version "24.1"
16745 :type '(alist :key-type (string :tag "Modifier")
16746 :value-type (number :tag "Minutes")))
16748 (defcustom org-image-actual-width t
16749 "Should we use the actual width of images when inlining them?
16751 When set to `t', always use the image width.
16753 When set to a number, use imagemagick (when available) to set
16754 the image's width to this value.
16756 When set to a number in a list, try to get the width from the
16757 #+ATTR.* keyword if it matches a width specification like
16758 width=\"[0-9]+\", and fall back on that number if none is found.
16760 When set to nil, try to get the width from an #+ATTR.* keyword
16761 and fall back on the original width if none is found.
16763 This requires Emacs >= 24.1, build with imagemagick support."
16764 :group 'org-appearance
16765 :version "24.3"
16766 :type '(choice
16767 (const :tag "Use the image width" t)
16768 (integer :tag "Use a number of pixels")
16769 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16770 (const :tag "Use #+ATTR* or don't resize" nil)))
16772 (defun org-duration-string-to-minutes (s &optional output-to-string)
16773 "Convert a duration string S to minutes.
16775 A bare number is interpreted as minutes, modifiers can be set by
16776 customizing `org-effort-durations' (which see).
16778 Entries containing a colon are interpreted as H:MM by
16779 `org-hh:mm-string-to-minutes'."
16780 (let ((result 0)
16781 (re (concat "\\([0-9.]+\\) *\\("
16782 (regexp-opt (mapcar 'car org-effort-durations))
16783 "\\)")))
16784 (while (string-match re s)
16785 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16786 (string-to-number (match-string 1 s))))
16787 (setq s (replace-match "" nil t s)))
16788 (setq result (floor result))
16789 (incf result (org-hh:mm-string-to-minutes s))
16790 (if output-to-string (number-to-string result) result)))
16792 ;;;; Files
16794 (defun org-save-all-org-buffers ()
16795 "Save all Org-mode buffers without user confirmation."
16796 (interactive)
16797 (message "Saving all Org-mode buffers...")
16798 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16799 (when (featurep 'org-id) (org-id-locations-save))
16800 (message "Saving all Org-mode buffers... done"))
16802 (defun org-revert-all-org-buffers ()
16803 "Revert all Org-mode buffers.
16804 Prompt for confirmation when there are unsaved changes.
16805 Be sure you know what you are doing before letting this function
16806 overwrite your changes.
16808 This function is useful in a setup where one tracks org files
16809 with a version control system, to revert on one machine after pulling
16810 changes from another. I believe the procedure must be like this:
16812 1. M-x org-save-all-org-buffers
16813 2. Pull changes from the other machine, resolve conflicts
16814 3. M-x org-revert-all-org-buffers"
16815 (interactive)
16816 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16817 (error "Abort"))
16818 (save-excursion
16819 (save-window-excursion
16820 (mapc
16821 (lambda (b)
16822 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16823 (with-current-buffer b buffer-file-name))
16824 (org-pop-to-buffer-same-window b)
16825 (revert-buffer t 'no-confirm)))
16826 (buffer-list))
16827 (when (and (featurep 'org-id) org-id-track-globally)
16828 (org-id-locations-load)))))
16830 ;;;; Agenda files
16832 ;;;###autoload
16833 (defun org-switchb (&optional arg)
16834 "Switch between Org buffers.
16835 With one prefix argument, restrict available buffers to files.
16836 With two prefix arguments, restrict available buffers to agenda files.
16838 Defaults to `iswitchb' for buffer name completion.
16839 Set `org-completion-use-ido' to make it use ido instead."
16840 (interactive "P")
16841 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16842 ((equal arg '(16)) (org-buffer-list 'agenda))
16843 (t (org-buffer-list))))
16844 (org-completion-use-iswitchb org-completion-use-iswitchb)
16845 (org-completion-use-ido org-completion-use-ido))
16846 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16847 (setq org-completion-use-iswitchb t))
16848 (org-pop-to-buffer-same-window
16849 (org-icompleting-read "Org buffer: "
16850 (mapcar 'list (mapcar 'buffer-name blist))
16851 nil t))))
16853 ;;; Define some older names previously used for this functionality
16854 ;;;###autoload
16855 (defalias 'org-ido-switchb 'org-switchb)
16856 ;;;###autoload
16857 (defalias 'org-iswitchb 'org-switchb)
16859 (defun org-buffer-list (&optional predicate exclude-tmp)
16860 "Return a list of Org buffers.
16861 PREDICATE can be `export', `files' or `agenda'.
16863 export restrict the list to Export buffers.
16864 files restrict the list to buffers visiting Org files.
16865 agenda restrict the list to buffers visiting agenda files.
16867 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16868 (let* ((bfn nil)
16869 (agenda-files (and (eq predicate 'agenda)
16870 (mapcar 'file-truename (org-agenda-files t))))
16871 (filter
16872 (cond
16873 ((eq predicate 'files)
16874 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16875 ((eq predicate 'export)
16876 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16877 ((eq predicate 'agenda)
16878 (lambda (b)
16879 (with-current-buffer b
16880 (and (derived-mode-p 'org-mode)
16881 (setq bfn (buffer-file-name b))
16882 (member (file-truename bfn) agenda-files)))))
16883 (t (lambda (b) (with-current-buffer b
16884 (or (derived-mode-p 'org-mode)
16885 (string-match "\*Org .*Export"
16886 (buffer-name b)))))))))
16887 (delq nil
16888 (mapcar
16889 (lambda(b)
16890 (if (and (funcall filter b)
16891 (or (not exclude-tmp)
16892 (not (string-match "tmp" (buffer-name b)))))
16894 nil))
16895 (buffer-list)))))
16897 (defun org-agenda-files (&optional unrestricted archives)
16898 "Get the list of agenda files.
16899 Optional UNRESTRICTED means return the full list even if a restriction
16900 is currently in place.
16901 When ARCHIVES is t, include all archive files that are really being
16902 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16903 `org-agenda-archives-mode' is t."
16904 (let ((files
16905 (cond
16906 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16907 ((stringp org-agenda-files) (org-read-agenda-file-list))
16908 ((listp org-agenda-files) org-agenda-files)
16909 (t (error "Invalid value of `org-agenda-files'")))))
16910 (setq files (apply 'append
16911 (mapcar (lambda (f)
16912 (if (file-directory-p f)
16913 (directory-files
16914 f t org-agenda-file-regexp)
16915 (list f)))
16916 files)))
16917 (when org-agenda-skip-unavailable-files
16918 (setq files (delq nil
16919 (mapcar (function
16920 (lambda (file)
16921 (and (file-readable-p file) file)))
16922 files))))
16923 (when (or (eq archives t)
16924 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16925 (setq files (org-add-archive-files files)))
16926 files))
16928 (defun org-agenda-file-p (&optional file)
16929 "Return non-nil, if FILE is an agenda file.
16930 If FILE is omitted, use the file associated with the current
16931 buffer."
16932 (member (or file (buffer-file-name))
16933 (org-agenda-files t)))
16935 (defun org-edit-agenda-file-list ()
16936 "Edit the list of agenda files.
16937 Depending on setup, this either uses customize to edit the variable
16938 `org-agenda-files', or it visits the file that is holding the list. In the
16939 latter case, the buffer is set up in a way that saving it automatically kills
16940 the buffer and restores the previous window configuration."
16941 (interactive)
16942 (if (stringp org-agenda-files)
16943 (let ((cw (current-window-configuration)))
16944 (find-file org-agenda-files)
16945 (org-set-local 'org-window-configuration cw)
16946 (org-add-hook 'after-save-hook
16947 (lambda ()
16948 (set-window-configuration
16949 (prog1 org-window-configuration
16950 (kill-buffer (current-buffer))))
16951 (org-install-agenda-files-menu)
16952 (message "New agenda file list installed"))
16953 nil 'local)
16954 (message "%s" (substitute-command-keys
16955 "Edit list and finish with \\[save-buffer]")))
16956 (customize-variable 'org-agenda-files)))
16958 (defun org-store-new-agenda-file-list (list)
16959 "Set new value for the agenda file list and save it correctly."
16960 (if (stringp org-agenda-files)
16961 (let ((fe (org-read-agenda-file-list t)) b u)
16962 (while (setq b (find-buffer-visiting org-agenda-files))
16963 (kill-buffer b))
16964 (with-temp-file org-agenda-files
16965 (insert
16966 (mapconcat
16967 (lambda (f) ;; Keep un-expanded entries.
16968 (if (setq u (assoc f fe))
16969 (cdr u)
16971 list "\n")
16972 "\n")))
16973 (let ((org-mode-hook nil) (org-inhibit-startup t)
16974 (org-insert-mode-line-in-empty-file nil))
16975 (setq org-agenda-files list)
16976 (customize-save-variable 'org-agenda-files org-agenda-files))))
16978 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16979 "Read the list of agenda files from a file.
16980 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16981 filenames, used by `org-store-new-agenda-file-list' to write back
16982 un-expanded file names."
16983 (when (file-directory-p org-agenda-files)
16984 (error "`org-agenda-files' cannot be a single directory"))
16985 (when (stringp org-agenda-files)
16986 (with-temp-buffer
16987 (insert-file-contents org-agenda-files)
16988 (mapcar
16989 (lambda (f)
16990 (let ((e (expand-file-name (substitute-in-file-name f)
16991 org-directory)))
16992 (if pair-with-expansion
16993 (cons e f)
16994 e)))
16995 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16997 ;;;###autoload
16998 (defun org-cycle-agenda-files ()
16999 "Cycle through the files in `org-agenda-files'.
17000 If the current buffer visits an agenda file, find the next one in the list.
17001 If the current buffer does not, find the first agenda file."
17002 (interactive)
17003 (let* ((fs (org-agenda-files t))
17004 (files (append fs (list (car fs))))
17005 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17006 file)
17007 (unless files (error "No agenda files"))
17008 (catch 'exit
17009 (while (setq file (pop files))
17010 (if (equal (file-truename file) tcf)
17011 (when (car files)
17012 (find-file (car files))
17013 (throw 'exit t))))
17014 (find-file (car fs)))
17015 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17017 (defun org-agenda-file-to-front (&optional to-end)
17018 "Move/add the current file to the top of the agenda file list.
17019 If the file is not present in the list, it is added to the front. If it is
17020 present, it is moved there. With optional argument TO-END, add/move to the
17021 end of the list."
17022 (interactive "P")
17023 (let ((org-agenda-skip-unavailable-files nil)
17024 (file-alist (mapcar (lambda (x)
17025 (cons (file-truename x) x))
17026 (org-agenda-files t)))
17027 (ctf (file-truename buffer-file-name))
17028 x had)
17029 (setq x (assoc ctf file-alist) had x)
17031 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17032 (if to-end
17033 (setq file-alist (append (delq x file-alist) (list x)))
17034 (setq file-alist (cons x (delq x file-alist))))
17035 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17036 (org-install-agenda-files-menu)
17037 (message "File %s to %s of agenda file list"
17038 (if had "moved" "added") (if to-end "end" "front"))))
17040 (defun org-remove-file (&optional file)
17041 "Remove current file from the list of files in variable `org-agenda-files'.
17042 These are the files which are being checked for agenda entries.
17043 Optional argument FILE means use this file instead of the current."
17044 (interactive)
17045 (let* ((org-agenda-skip-unavailable-files nil)
17046 (file (or file buffer-file-name))
17047 (true-file (file-truename file))
17048 (afile (abbreviate-file-name file))
17049 (files (delq nil (mapcar
17050 (lambda (x)
17051 (if (equal true-file
17052 (file-truename x))
17053 nil x))
17054 (org-agenda-files t)))))
17055 (if (not (= (length files) (length (org-agenda-files t))))
17056 (progn
17057 (org-store-new-agenda-file-list files)
17058 (org-install-agenda-files-menu)
17059 (message "Removed file: %s" afile))
17060 (message "File was not in list: %s (not removed)" afile))))
17062 (defun org-file-menu-entry (file)
17063 (vector file (list 'find-file file) t))
17065 (defun org-check-agenda-file (file)
17066 "Make sure FILE exists. If not, ask user what to do."
17067 (when (not (file-exists-p file))
17068 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17069 (abbreviate-file-name file))
17070 (let ((r (downcase (read-char-exclusive))))
17071 (cond
17072 ((equal r ?r)
17073 (org-remove-file file)
17074 (throw 'nextfile t))
17075 (t (error "Abort"))))))
17077 (defun org-get-agenda-file-buffer (file)
17078 "Get a buffer visiting FILE. If the buffer needs to be created, add
17079 it to the list of buffers which might be released later."
17080 (let ((buf (org-find-base-buffer-visiting file)))
17081 (if buf
17082 buf ; just return it
17083 ;; Make a new buffer and remember it
17084 (setq buf (find-file-noselect file))
17085 (if buf (push buf org-agenda-new-buffers))
17086 buf)))
17088 (defun org-release-buffers (blist)
17089 "Release all buffers in list, asking the user for confirmation when needed.
17090 When a buffer is unmodified, it is just killed. When modified, it is saved
17091 \(if the user agrees) and then killed."
17092 (let (buf file)
17093 (while (setq buf (pop blist))
17094 (setq file (buffer-file-name buf))
17095 (when (and (buffer-modified-p buf)
17096 file
17097 (y-or-n-p (format "Save file %s? " file)))
17098 (with-current-buffer buf (save-buffer)))
17099 (kill-buffer buf))))
17101 (defun org-agenda-prepare-buffers (files)
17102 "Create buffers for all agenda files, protect archived trees and comments."
17103 (interactive)
17104 (let ((pa '(:org-archived t))
17105 (pc '(:org-comment t))
17106 (pall '(:org-archived t :org-comment t))
17107 (inhibit-read-only t)
17108 (rea (concat ":" org-archive-tag ":"))
17109 bmp file re)
17110 (save-excursion
17111 (save-restriction
17112 (while (setq file (pop files))
17113 (catch 'nextfile
17114 (if (bufferp file)
17115 (set-buffer file)
17116 (org-check-agenda-file file)
17117 (set-buffer (org-get-agenda-file-buffer file)))
17118 (widen)
17119 (setq bmp (buffer-modified-p))
17120 (org-refresh-category-properties)
17121 (setq org-todo-keywords-for-agenda
17122 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17123 (setq org-done-keywords-for-agenda
17124 (append org-done-keywords-for-agenda org-done-keywords))
17125 (setq org-todo-keyword-alist-for-agenda
17126 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17127 (setq org-drawers-for-agenda
17128 (append org-drawers-for-agenda org-drawers))
17129 (setq org-tag-alist-for-agenda
17130 (append org-tag-alist-for-agenda org-tag-alist))
17132 (save-excursion
17133 (remove-text-properties (point-min) (point-max) pall)
17134 (when org-agenda-skip-archived-trees
17135 (goto-char (point-min))
17136 (while (re-search-forward rea nil t)
17137 (if (org-at-heading-p t)
17138 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17139 (goto-char (point-min))
17140 (setq re (format org-heading-keyword-regexp-format
17141 org-comment-string))
17142 (while (re-search-forward re nil t)
17143 (add-text-properties
17144 (match-beginning 0) (org-end-of-subtree t) pc)))
17145 (set-buffer-modified-p bmp)))))
17146 (setq org-todo-keywords-for-agenda
17147 (org-uniquify org-todo-keywords-for-agenda))
17148 (setq org-todo-keyword-alist-for-agenda
17149 (org-uniquify org-todo-keyword-alist-for-agenda)
17150 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17152 ;;;; Embedded LaTeX
17154 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17155 "Keymap for the minor `org-cdlatex-mode'.")
17157 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17158 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17159 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17160 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17161 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17163 (defvar org-cdlatex-texmathp-advice-is-done nil
17164 "Flag remembering if we have applied the advice to texmathp already.")
17166 (define-minor-mode org-cdlatex-mode
17167 "Toggle the minor `org-cdlatex-mode'.
17168 This mode supports entering LaTeX environment and math in LaTeX fragments
17169 in Org-mode.
17170 \\{org-cdlatex-mode-map}"
17171 nil " OCDL" nil
17172 (when org-cdlatex-mode
17173 (require 'cdlatex)
17174 (run-hooks 'cdlatex-mode-hook)
17175 (cdlatex-compute-tables))
17176 (unless org-cdlatex-texmathp-advice-is-done
17177 (setq org-cdlatex-texmathp-advice-is-done t)
17178 (defadvice texmathp (around org-math-always-on activate)
17179 "Always return t in org-mode buffers.
17180 This is because we want to insert math symbols without dollars even outside
17181 the LaTeX math segments. If Orgmode thinks that point is actually inside
17182 an embedded LaTeX fragment, let texmathp do its job.
17183 \\[org-cdlatex-mode-map]"
17184 (interactive)
17185 (let (p)
17186 (cond
17187 ((not (derived-mode-p 'org-mode)) ad-do-it)
17188 ((eq this-command 'cdlatex-math-symbol)
17189 (setq ad-return-value t
17190 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17192 (let ((p (org-inside-LaTeX-fragment-p)))
17193 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17194 (setq ad-return-value t
17195 texmathp-why '("Org-mode embedded math" . 0))
17196 (if p ad-do-it)))))))))
17198 (defun turn-on-org-cdlatex ()
17199 "Unconditionally turn on `org-cdlatex-mode'."
17200 (org-cdlatex-mode 1))
17202 (defun org-inside-LaTeX-fragment-p ()
17203 "Test if point is inside a LaTeX fragment.
17204 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17205 sequence appearing also before point.
17206 Even though the matchers for math are configurable, this function assumes
17207 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17208 delimiters are skipped when they have been removed by customization.
17209 The return value is nil, or a cons cell with the delimiter and the
17210 position of this delimiter.
17212 This function does a reasonably good job, but can locally be fooled by
17213 for example currency specifications. For example it will assume being in
17214 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17215 fragments that are properly closed, but during editing, we have to live
17216 with the uncertainty caused by missing closing delimiters. This function
17217 looks only before point, not after."
17218 (catch 'exit
17219 (let ((pos (point))
17220 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17221 (lim (progn
17222 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17223 (point)))
17224 dd-on str (start 0) m re)
17225 (goto-char pos)
17226 (when dodollar
17227 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17228 re (nth 1 (assoc "$" org-latex-regexps)))
17229 (while (string-match re str start)
17230 (cond
17231 ((= (match-end 0) (length str))
17232 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17233 ((= (match-end 0) (- (length str) 5))
17234 (throw 'exit nil))
17235 (t (setq start (match-end 0))))))
17236 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17237 (goto-char pos)
17238 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17239 (and (match-beginning 2) (throw 'exit nil))
17240 ;; count $$
17241 (while (re-search-backward "\\$\\$" lim t)
17242 (setq dd-on (not dd-on)))
17243 (goto-char pos)
17244 (if dd-on (cons "$$" m))))))
17246 (defun org-inside-latex-macro-p ()
17247 "Is point inside a LaTeX macro or its arguments?"
17248 (save-match-data
17249 (org-in-regexp
17250 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17252 (defun org-try-cdlatex-tab ()
17253 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17254 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17255 - inside a LaTeX fragment, or
17256 - after the first word in a line, where an abbreviation expansion could
17257 insert a LaTeX environment."
17258 (when org-cdlatex-mode
17259 (cond
17260 ;; Before any word on the line: No expansion possible.
17261 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17262 ;; Just after first word on the line: Expand it. Make sure it
17263 ;; cannot happen on headlines, though.
17264 ((save-excursion
17265 (skip-chars-backward "a-zA-Z0-9*")
17266 (skip-chars-backward " \t")
17267 (and (bolp) (not (org-at-heading-p))))
17268 (cdlatex-tab) t)
17269 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17271 (defun org-cdlatex-underscore-caret (&optional arg)
17272 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17273 Revert to the normal definition outside of these fragments."
17274 (interactive "P")
17275 (if (org-inside-LaTeX-fragment-p)
17276 (call-interactively 'cdlatex-sub-superscript)
17277 (let (org-cdlatex-mode)
17278 (call-interactively (key-binding (vector last-input-event))))))
17280 (defun org-cdlatex-math-modify (&optional arg)
17281 "Execute `cdlatex-math-modify' in LaTeX fragments.
17282 Revert to the normal definition outside of these fragments."
17283 (interactive "P")
17284 (if (org-inside-LaTeX-fragment-p)
17285 (call-interactively 'cdlatex-math-modify)
17286 (let (org-cdlatex-mode)
17287 (call-interactively (key-binding (vector last-input-event))))))
17289 (defvar org-latex-fragment-image-overlays nil
17290 "List of overlays carrying the images of latex fragments.")
17291 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17293 (defun org-remove-latex-fragment-image-overlays ()
17294 "Remove all overlays with LaTeX fragment images in current buffer."
17295 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17296 (setq org-latex-fragment-image-overlays nil))
17298 (defun org-preview-latex-fragment (&optional subtree)
17299 "Preview the LaTeX fragment at point, or all locally or globally.
17300 If the cursor is in a LaTeX fragment, create the image and overlay
17301 it over the source code. If there is no fragment at point, display
17302 all fragments in the current text, from one headline to the next. With
17303 prefix SUBTREE, display all fragments in the current subtree. With a
17304 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17305 the cursor is before the first headline,
17306 display all fragments in the buffer.
17307 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17308 (interactive "P")
17309 (unless buffer-file-name
17310 (error "Can't preview LaTeX fragment in a non-file buffer"))
17311 (org-remove-latex-fragment-image-overlays)
17312 (save-excursion
17313 (save-restriction
17314 (let (beg end at msg)
17315 (cond
17316 ((or (equal subtree '(16))
17317 (not (save-excursion
17318 (re-search-backward org-outline-regexp-bol nil t))))
17319 (setq beg (point-min) end (point-max)
17320 msg "Creating images for buffer...%s"))
17321 ((equal subtree '(4))
17322 (org-back-to-heading)
17323 (setq beg (point) end (org-end-of-subtree t)
17324 msg "Creating images for subtree...%s"))
17326 (if (setq at (org-inside-LaTeX-fragment-p))
17327 (goto-char (max (point-min) (- (cdr at) 2)))
17328 (org-back-to-heading))
17329 (setq beg (point) end (progn (outline-next-heading) (point))
17330 msg (if at "Creating image...%s"
17331 "Creating images for entry...%s"))))
17332 (message msg "")
17333 (narrow-to-region beg end)
17334 (goto-char beg)
17335 (org-format-latex
17336 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17337 (file-name-nondirectory
17338 buffer-file-name)))
17339 default-directory 'overlays msg at 'forbuffer
17340 org-latex-create-formula-image-program)
17341 (message msg "done. Use `C-c C-c' to remove images.")))))
17343 (defvar org-latex-regexps
17344 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17345 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17346 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17347 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17348 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17349 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17350 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17351 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17352 "Regular expressions for matching embedded LaTeX.")
17354 (defvar org-export-have-math nil) ;; dynamic scoping
17355 (defun org-format-latex (prefix &optional dir overlays msg at
17356 forbuffer processing-type)
17357 "Replace LaTeX fragments with links to an image, and produce images.
17358 Some of the options can be changed using the variable
17359 `org-format-latex-options'."
17360 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17361 (let* ((prefixnodir (file-name-nondirectory prefix))
17362 (absprefix (expand-file-name prefix dir))
17363 (todir (file-name-directory absprefix))
17364 (opt org-format-latex-options)
17365 (optnew org-format-latex-options)
17366 (matchers (plist-get opt :matchers))
17367 (re-list org-latex-regexps)
17368 (org-format-latex-header-extra
17369 (plist-get (org-infile-export-plist) :latex-header-extra))
17370 (cnt 0) txt hash link beg end re e checkdir
17371 string
17372 m n block-type block linkfile movefile ov)
17373 ;; Check the different regular expressions
17374 (while (setq e (pop re-list))
17375 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17376 block (if block-type "\n\n" ""))
17377 (when (member m matchers)
17378 (goto-char (point-min))
17379 (while (re-search-forward re nil t)
17380 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17381 (not (get-text-property (match-beginning n)
17382 'org-protected))
17383 (or (not overlays)
17384 (not (eq (get-char-property (match-beginning n)
17385 'org-overlay-type)
17386 'org-latex-overlay))))
17387 (setq org-export-have-math t)
17388 (cond
17389 ((eq processing-type 'verbatim)
17390 ;; Leave the text verbatim, just protect it
17391 (add-text-properties (match-beginning n) (match-end n)
17392 '(org-protected t)))
17393 ((eq processing-type 'mathjax)
17394 ;; Prepare for MathJax processing
17395 (setq string (match-string n))
17396 (if (member m '("$" "$1"))
17397 (save-excursion
17398 (delete-region (match-beginning n) (match-end n))
17399 (goto-char (match-beginning n))
17400 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17401 "\\)")
17402 '(org-protected t))))
17403 (add-text-properties (match-beginning n) (match-end n)
17404 '(org-protected t))))
17405 ((or (eq processing-type 'dvipng)
17406 (eq processing-type 'imagemagick))
17407 ;; Process to an image
17408 (setq txt (match-string n)
17409 beg (match-beginning n) end (match-end n)
17410 cnt (1+ cnt))
17411 (let ((face (face-at-point))
17412 (fg (plist-get opt :foreground))
17413 (bg (plist-get opt :background))
17414 print-length print-level) ; make sure full list is printed
17415 (when forbuffer
17416 ; Get the colors from the face at point
17417 (goto-char beg)
17418 (when (eq fg 'auto)
17419 (setq fg (face-attribute face :foreground nil 'default)))
17420 (when (eq bg 'auto)
17421 (setq bg (face-attribute face :background nil 'default)))
17422 (setq optnew (copy-sequence opt))
17423 (plist-put optnew :foreground fg)
17424 (plist-put optnew :background bg))
17425 (setq hash (sha1 (prin1-to-string
17426 (list org-format-latex-header
17427 org-format-latex-header-extra
17428 org-export-latex-default-packages-alist
17429 org-export-latex-packages-alist
17430 org-format-latex-options
17431 forbuffer txt fg bg)))
17432 linkfile (format "%s_%s.png" prefix hash)
17433 movefile (format "%s_%s.png" absprefix hash)))
17434 (setq link (concat block "[[file:" linkfile "]]" block))
17435 (if msg (message msg cnt))
17436 (goto-char beg)
17437 (unless checkdir ; make sure the directory exists
17438 (setq checkdir t)
17439 (or (file-directory-p todir) (make-directory todir t)))
17440 (org-create-formula-image
17441 txt movefile optnew forbuffer processing-type)
17442 (if overlays
17443 (progn
17444 (mapc (lambda (o)
17445 (if (eq (overlay-get o 'org-overlay-type)
17446 'org-latex-overlay)
17447 (delete-overlay o)))
17448 (overlays-in beg end))
17449 (setq ov (make-overlay beg end))
17450 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17451 (if (featurep 'xemacs)
17452 (progn
17453 (overlay-put ov 'invisible t)
17454 (overlay-put
17455 ov 'end-glyph
17456 (make-glyph (vector 'png :file movefile))))
17457 (overlay-put
17458 ov 'display
17459 (list 'image :type 'png :file movefile :ascent 'center)))
17460 (push ov org-latex-fragment-image-overlays)
17461 (goto-char end))
17462 (delete-region beg end)
17463 (insert (org-add-props link
17464 (list 'org-latex-src
17465 (replace-regexp-in-string
17466 "\"" "" txt)
17467 'org-latex-src-embed-type
17468 (if block-type 'paragraph 'character))))))
17469 ((eq processing-type 'mathml)
17470 ;; Process to MathML
17471 (unless (save-match-data (org-format-latex-mathml-available-p))
17472 (error "LaTeX to MathML converter not configured"))
17473 (setq txt (match-string n)
17474 beg (match-beginning n) end (match-end n)
17475 cnt (1+ cnt))
17476 (if msg (message msg cnt))
17477 (goto-char beg)
17478 (delete-region beg end)
17479 (insert (org-format-latex-as-mathml
17480 txt block-type prefix dir)))
17482 (error "Unknown conversion type %s for latex fragments"
17483 processing-type)))))))))
17485 (defun org-create-math-formula (latex-frag &optional mathml-file)
17486 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17487 Use `org-latex-to-mathml-convert-command'. If the conversion is
17488 sucessful, return the portion between \"<math...> </math>\"
17489 elements otherwise return nil. When MATHML-FILE is specified,
17490 write the results in to that file. When invoked as an
17491 interactive command, prompt for LATEX-FRAG, with initial value
17492 set to the current active region and echo the results for user
17493 inspection."
17494 (interactive (list (let ((frag (when (org-region-active-p)
17495 (buffer-substring-no-properties
17496 (region-beginning) (region-end)))))
17497 (read-string "LaTeX Fragment: " frag nil frag))))
17498 (unless latex-frag (error "Invalid latex-frag"))
17499 (let* ((tmp-in-file (file-relative-name
17500 (make-temp-name (expand-file-name "ltxmathml-in"))))
17501 (ignore (write-region latex-frag nil tmp-in-file))
17502 (tmp-out-file (file-relative-name
17503 (make-temp-name (expand-file-name "ltxmathml-out"))))
17504 (cmd (format-spec
17505 org-latex-to-mathml-convert-command
17506 `((?j . ,(shell-quote-argument
17507 (expand-file-name org-latex-to-mathml-jar-file)))
17508 (?I . ,(shell-quote-argument tmp-in-file))
17509 (?o . ,(shell-quote-argument tmp-out-file)))))
17510 mathml shell-command-output)
17511 (when (org-called-interactively-p 'any)
17512 (unless (org-format-latex-mathml-available-p)
17513 (error "LaTeX to MathML converter not configured")))
17514 (message "Running %s" cmd)
17515 (setq shell-command-output (shell-command-to-string cmd))
17516 (setq mathml
17517 (when (file-readable-p tmp-out-file)
17518 (with-current-buffer (find-file-noselect tmp-out-file t)
17519 (goto-char (point-min))
17520 (when (re-search-forward
17521 (concat
17522 (regexp-quote
17523 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17524 "\\(.\\|\n\\)*"
17525 (regexp-quote "</math>")) nil t)
17526 (prog1 (match-string 0) (kill-buffer))))))
17527 (cond
17528 (mathml
17529 (setq mathml
17530 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17531 (when mathml-file
17532 (write-region mathml nil mathml-file))
17533 (when (org-called-interactively-p 'any)
17534 (message mathml)))
17535 ((message "LaTeX to MathML conversion failed")
17536 (message shell-command-output)))
17537 (delete-file tmp-in-file)
17538 (when (file-exists-p tmp-out-file)
17539 (delete-file tmp-out-file))
17540 mathml))
17542 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17543 prefix &optional dir)
17544 "Use `org-create-math-formula' but check local cache first."
17545 (let* ((absprefix (expand-file-name prefix dir))
17546 (print-length nil) (print-level nil)
17547 (formula-id (concat
17548 "formula-"
17549 (sha1
17550 (prin1-to-string
17551 (list latex-frag
17552 org-latex-to-mathml-convert-command)))))
17553 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17554 (formula-cache-dir (file-name-directory formula-cache)))
17556 (unless (file-directory-p formula-cache-dir)
17557 (make-directory formula-cache-dir t))
17559 (unless (file-exists-p formula-cache)
17560 (org-create-math-formula latex-frag formula-cache))
17562 (if (file-exists-p formula-cache)
17563 ;; Successful conversion. Return the link to MathML file.
17564 (org-add-props
17565 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17566 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17567 'org-latex-src-embed-type (if latex-frag-type
17568 'paragraph 'character)))
17569 ;; Failed conversion. Return the LaTeX fragment verbatim
17570 (add-text-properties
17571 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17572 latex-frag)))
17574 (defun org-create-formula-image (string tofile options buffer &optional type)
17575 "Create an image from LaTeX source using dvipng or convert.
17576 This function calls either `org-create-formula-image-with-dvipng'
17577 or `org-create-formula-image-with-imagemagick' depending on the
17578 value of `org-latex-create-formula-image-program' or on the value
17579 of the optional TYPE variable.
17581 Note: ultimately these two function should be combined as they
17582 share a good deal of logic."
17583 (org-check-external-command
17584 "latex" "needed to convert LaTeX fragments to images")
17585 (funcall
17586 (case (or type org-latex-create-formula-image-program)
17587 ('dvipng
17588 (org-check-external-command
17589 "dvipng" "needed to convert LaTeX fragments to images")
17590 #'org-create-formula-image-with-dvipng)
17591 ('imagemagick
17592 (org-check-external-command
17593 "convert" "you need to install imagemagick")
17594 #'org-create-formula-image-with-imagemagick)
17595 (t (error
17596 "invalid value of `org-latex-create-formula-image-program'")))
17597 string tofile options buffer))
17599 ;; This function borrows from Ganesh Swami's latex2png.el
17600 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17601 "This calls dvipng."
17602 (require 'org-latex)
17603 (let* ((tmpdir (if (featurep 'xemacs)
17604 (temp-directory)
17605 temporary-file-directory))
17606 (texfilebase (make-temp-name
17607 (expand-file-name "orgtex" tmpdir)))
17608 (texfile (concat texfilebase ".tex"))
17609 (dvifile (concat texfilebase ".dvi"))
17610 (pngfile (concat texfilebase ".png"))
17611 (fnh (if (featurep 'xemacs)
17612 (font-height (face-font 'default))
17613 (face-attribute 'default :height nil)))
17614 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17615 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17616 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17617 "Black"))
17618 (bg (or (plist-get options (if buffer :background :html-background))
17619 "Transparent")))
17620 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17621 (setq fg (org-dvipng-color-format fg)))
17622 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17623 (setq bg (org-dvipng-color-format bg)))
17624 (with-temp-file texfile
17625 (insert (org-splice-latex-header
17626 org-format-latex-header
17627 org-export-latex-default-packages-alist
17628 org-export-latex-packages-alist t
17629 org-format-latex-header-extra))
17630 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17631 (require 'org-latex)
17632 (org-export-latex-fix-inputenc))
17633 (let ((dir default-directory))
17634 (condition-case nil
17635 (progn
17636 (cd tmpdir)
17637 (call-process "latex" nil nil nil texfile))
17638 (error nil))
17639 (cd dir))
17640 (if (not (file-exists-p dvifile))
17641 (progn (message "Failed to create dvi file from %s" texfile) nil)
17642 (condition-case nil
17643 (if (featurep 'xemacs)
17644 (call-process "dvipng" nil nil nil
17645 "-fg" fg "-bg" bg
17646 "-T" "tight"
17647 "-o" pngfile
17648 dvifile)
17649 (call-process "dvipng" nil nil nil
17650 "-fg" fg "-bg" bg
17651 "-D" dpi
17652 ;;"-x" scale "-y" scale
17653 "-T" "tight"
17654 "-o" pngfile
17655 dvifile))
17656 (error nil))
17657 (if (not (file-exists-p pngfile))
17658 (if org-format-latex-signal-error
17659 (error "Failed to create png file from %s" texfile)
17660 (message "Failed to create png file from %s" texfile)
17661 nil)
17662 ;; Use the requested file name and clean up
17663 (copy-file pngfile tofile 'replace)
17664 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17665 (if (file-exists-p (concat texfilebase e))
17666 (delete-file (concat texfilebase e))))
17667 pngfile))))
17669 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17670 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17671 "This calls convert, which is included into imagemagick."
17672 (require 'org-latex)
17673 (let* ((tmpdir (if (featurep 'xemacs)
17674 (temp-directory)
17675 temporary-file-directory))
17676 (texfilebase (make-temp-name
17677 (expand-file-name "orgtex" tmpdir)))
17678 (texfile (concat texfilebase ".tex"))
17679 (pdffile (concat texfilebase ".pdf"))
17680 (pngfile (concat texfilebase ".png"))
17681 (fnh (if (featurep 'xemacs)
17682 (font-height (face-font 'default))
17683 (face-attribute 'default :height nil)))
17684 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17685 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17686 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17687 "black"))
17688 (bg (or (plist-get options (if buffer :background :html-background))
17689 "white")))
17690 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17691 (setq fg (org-latex-color-format fg)))
17692 (if (eq bg 'default) (setq bg (org-latex-color :background))
17693 (setq bg (org-latex-color-format
17694 (if (string= bg "Transparent") "white" bg))))
17695 (with-temp-file texfile
17696 (insert (org-splice-latex-header
17697 org-format-latex-header
17698 org-export-latex-default-packages-alist
17699 org-export-latex-packages-alist t
17700 org-format-latex-header-extra))
17701 (insert "\n\\begin{document}\n"
17702 "\\definecolor{fg}{rgb}{" fg "}\n"
17703 "\\definecolor{bg}{rgb}{" bg "}\n"
17704 "\n\\pagecolor{bg}\n"
17705 "\n{\\color{fg}\n"
17706 string
17707 "\n}\n"
17708 "\n\\end{document}\n" )
17709 (require 'org-latex)
17710 (org-export-latex-fix-inputenc))
17711 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17712 (condition-case nil
17713 (progn
17714 (cd tmpdir)
17715 (setq cmds org-latex-to-pdf-process)
17716 (while cmds
17717 (setq latex-frags-cmds (pop cmds))
17718 (if (listp latex-frags-cmds)
17719 (setq cmds nil)
17720 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17721 (while latex-frags-cmds
17722 (setq cmd (pop latex-frags-cmds))
17723 (while (string-match "%b" cmd)
17724 (setq cmd (replace-match
17725 (save-match-data
17726 (shell-quote-argument texfile))
17727 t t cmd)))
17728 (while (string-match "%f" cmd)
17729 (setq cmd (replace-match
17730 (save-match-data
17731 (shell-quote-argument (file-name-nondirectory texfile)))
17732 t t cmd)))
17733 (while (string-match "%o" cmd)
17734 (setq cmd (replace-match
17735 (save-match-data
17736 (shell-quote-argument (file-name-directory texfile)))
17737 t t cmd)))
17738 (setq cmd (split-string cmd))
17739 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17740 (error nil))
17741 (cd dir))
17742 (if (not (file-exists-p pdffile))
17743 (progn (message "Failed to create pdf file from %s" texfile) nil)
17744 (condition-case nil
17745 (if (featurep 'xemacs)
17746 (call-process "convert" nil nil nil
17747 "-density" "96"
17748 "-trim"
17749 "-antialias"
17750 pdffile
17751 "-quality" "100"
17752 ;; "-sharpen" "0x1.0"
17753 pngfile)
17754 (call-process "convert" nil nil nil
17755 "-density" dpi
17756 "-trim"
17757 "-antialias"
17758 pdffile
17759 "-quality" "100"
17760 ; "-sharpen" "0x1.0"
17761 pngfile))
17762 (error nil))
17763 (if (not (file-exists-p pngfile))
17764 (if org-format-latex-signal-error
17765 (error "Failed to create png file from %s" texfile)
17766 (message "Failed to create png file from %s" texfile)
17767 nil)
17768 ;; Use the requested file name and clean up
17769 (copy-file pngfile tofile 'replace)
17770 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17771 (if (file-exists-p (concat texfilebase e))
17772 (delete-file (concat texfilebase e))))
17773 pngfile))))
17775 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17776 "Fill a LaTeX header template TPL.
17777 In the template, the following place holders will be recognized:
17779 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17780 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17781 [PACKAGES] \\usepackage statements for PKG
17782 [NO-PACKAGES] do not include PKG
17783 [EXTRA] the string EXTRA
17784 [NO-EXTRA] do not include EXTRA
17786 For backward compatibility, if both the positive and the negative place
17787 holder is missing, the positive one (without the \"NO-\") will be
17788 assumed to be present at the end of the template.
17789 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17790 EXTRA is a string.
17791 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17792 (let (rpl (end ""))
17793 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17794 (setq rpl (if (or (match-end 1) (not def-pkg))
17795 "" (org-latex-packages-to-string def-pkg snippets-p t))
17796 tpl (replace-match rpl t t tpl))
17797 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17799 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17800 (setq rpl (if (or (match-end 1) (not pkg))
17801 "" (org-latex-packages-to-string pkg snippets-p t))
17802 tpl (replace-match rpl t t tpl))
17803 (if pkg (setq end
17804 (concat end "\n"
17805 (org-latex-packages-to-string pkg snippets-p)))))
17807 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17808 (setq rpl (if (or (match-end 1) (not extra))
17809 "" (concat extra "\n"))
17810 tpl (replace-match rpl t t tpl))
17811 (if (and extra (string-match "\\S-" extra))
17812 (setq end (concat end "\n" extra))))
17814 (if (string-match "\\S-" end)
17815 (concat tpl "\n" end)
17816 tpl)))
17818 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17819 "Turn an alist of packages into a string with the \\usepackage macros."
17820 (setq pkg (mapconcat (lambda(p)
17821 (cond
17822 ((stringp p) p)
17823 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17824 (format "%% Package %s omitted" (cadr p)))
17825 ((equal "" (car p))
17826 (format "\\usepackage{%s}" (cadr p)))
17828 (format "\\usepackage[%s]{%s}"
17829 (car p) (cadr p)))))
17831 "\n"))
17832 (if newline (concat pkg "\n") pkg))
17834 (defun org-dvipng-color (attr)
17835 "Return a RGB color specification for dvipng."
17836 (apply 'format "rgb %s %s %s"
17837 (mapcar 'org-normalize-color
17838 (if (featurep 'xemacs)
17839 (color-rgb-components
17840 (face-property 'default
17841 (cond ((eq attr :foreground) 'foreground)
17842 ((eq attr :background) 'background))))
17843 (color-values (face-attribute 'default attr nil))))))
17845 (defun org-dvipng-color-format (color-name)
17846 "Convert COLOR-NAME to a RGB color value for dvipng."
17847 (apply 'format "rgb %s %s %s"
17848 (mapcar 'org-normalize-color
17849 (color-values color-name))))
17851 (defun org-latex-color (attr)
17852 "Return a RGB color for the LaTeX color package."
17853 (apply 'format "%s,%s,%s"
17854 (mapcar 'org-normalize-color
17855 (if (featurep 'xemacs)
17856 (color-rgb-components
17857 (face-property 'default
17858 (cond ((eq attr :foreground) 'foreground)
17859 ((eq attr :background) 'background))))
17860 (color-values (face-attribute 'default attr nil))))))
17862 (defun org-latex-color-format (color-name)
17863 "Convert COLOR-NAME to a RGB color value."
17864 (apply 'format "%s,%s,%s"
17865 (mapcar 'org-normalize-color
17866 (color-values color-name))))
17868 (defun org-normalize-color (value)
17869 "Return string to be used as color value for an RGB component."
17870 (format "%g" (/ value 65535.0)))
17872 ;; Image display
17875 (defvar org-inline-image-overlays nil)
17876 (make-variable-buffer-local 'org-inline-image-overlays)
17878 (defun org-toggle-inline-images (&optional include-linked)
17879 "Toggle the display of inline images.
17880 INCLUDE-LINKED is passed to `org-display-inline-images'."
17881 (interactive "P")
17882 (if org-inline-image-overlays
17883 (progn
17884 (org-remove-inline-images)
17885 (message "Inline image display turned off"))
17886 (org-display-inline-images include-linked)
17887 (if org-inline-image-overlays
17888 (message "%d images displayed inline"
17889 (length org-inline-image-overlays))
17890 (message "No images to display inline"))))
17892 (defun org-redisplay-inline-images ()
17893 "Refresh the display of inline images."
17894 (interactive)
17895 (if (not org-inline-image-overlays)
17896 (org-toggle-inline-images)
17897 (org-toggle-inline-images)
17898 (org-toggle-inline-images)))
17900 (defun org-display-inline-images (&optional include-linked refresh beg end)
17901 "Display inline images.
17902 Normally only links without a description part are inlined, because this
17903 is how it will work for export. When INCLUDE-LINKED is set, also links
17904 with a description part will be inlined. This can be nice for a quick
17905 look at those images, but it does not reflect what exported files will look
17906 like.
17907 When REFRESH is set, refresh existing images between BEG and END.
17908 This will create new image displays only if necessary.
17909 BEG and END default to the buffer boundaries."
17910 (interactive "P")
17911 (unless refresh
17912 (org-remove-inline-images)
17913 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17914 (save-excursion
17915 (save-restriction
17916 (widen)
17917 (setq beg (or beg (point-min)) end (or end (point-max)))
17918 (goto-char beg)
17919 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17920 (substring (org-image-file-name-regexp) 0 -2)
17921 "\\)\\]" (if include-linked "" "\\]")))
17922 old file ov img type attrwidth width)
17923 (while (re-search-forward re end t)
17924 (setq old (get-char-property-and-overlay (match-beginning 1)
17925 'org-image-overlay)
17926 file (expand-file-name
17927 (concat (or (match-string 3) "") (match-string 4))))
17928 (when (image-type-available-p 'imagemagick)
17929 (setq attrwidth (if (or (listp org-image-actual-width)
17930 (null org-image-actual-width))
17931 (save-excursion
17932 (save-match-data
17933 (move-beginning-of-line 0)
17934 (if (looking-at "#\\+ATTR.*width=\"\\([^\"]+\\)\"")
17935 (string-to-number (match-string 1))))))
17936 width (cond ((eq org-image-actual-width t) nil)
17937 ((null org-image-actual-width) attrwidth)
17938 ((numberp org-image-actual-width)
17939 org-image-actual-width)
17940 ((listp org-image-actual-width)
17941 (or attrwidth (car org-image-actual-width))))
17942 type (if width 'imagemagick)))
17943 (when (file-exists-p file)
17944 (if (and (car-safe old) refresh)
17945 (image-refresh (overlay-get (cdr old) 'display))
17946 (setq img (save-match-data (create-image file type nil :width width)))
17947 (when img
17948 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17949 (overlay-put ov 'display img)
17950 (overlay-put ov 'face 'default)
17951 (overlay-put ov 'org-image-overlay t)
17952 (overlay-put ov 'modification-hooks
17953 (list 'org-display-inline-modification-hook))
17954 (push ov org-inline-image-overlays)))))))))
17956 (defun org-display-inline-modification-hook (ov after beg end &optional len)
17957 "Remove inline-display overlay if a corresponding region is modified."
17958 (let ((inhibit-modification-hooks t))
17959 (when (and ov after)
17960 (delete ov org-inline-image-overlays)
17961 (delete-overlay ov))))
17963 (defun org-remove-inline-images ()
17964 "Remove inline display of images."
17965 (interactive)
17966 (mapc 'delete-overlay org-inline-image-overlays)
17967 (setq org-inline-image-overlays nil))
17969 ;;;; Key bindings
17971 ;; Outline functions from `outline-mode-prefix-map'
17972 ;; that can be remapped in Org:
17973 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17974 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17975 (define-key org-mode-map [remap outline-forward-same-level]
17976 'org-forward-heading-same-level)
17977 (define-key org-mode-map [remap outline-backward-same-level]
17978 'org-backward-heading-same-level)
17979 (define-key org-mode-map [remap show-branches]
17980 'org-kill-note-or-show-branches)
17981 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17982 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17983 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17985 ;; Outline functions from `outline-mode-prefix-map' that can not
17986 ;; be remapped in Org:
17988 ;; - the column "key binding" shows whether the Outline function is still
17989 ;; available in Org mode on the same key that it has been bound to in
17990 ;; Outline mode:
17991 ;; - "overridden": key used for a different functionality in Org mode
17992 ;; - else: key still bound to the same Outline function in Org mode
17994 ;; | Outline function | key binding | Org replacement |
17995 ;; |------------------------------------+-------------+-----------------------|
17996 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17997 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17998 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17999 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18000 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18001 ;; | `show-entry' | overridden | no replacement |
18002 ;; | `show-children' | `C-c C-i' | visibility cycling |
18003 ;; | `show-branches' | `C-c C-k' | still same function |
18004 ;; | `show-subtree' | overridden | visibility cycling |
18005 ;; | `show-all' | overridden | no replacement |
18006 ;; | `hide-subtree' | overridden | visibility cycling |
18007 ;; | `hide-body' | overridden | no replacement |
18008 ;; | `hide-entry' | overridden | visibility cycling |
18009 ;; | `hide-leaves' | overridden | no replacement |
18010 ;; | `hide-sublevels' | overridden | no replacement |
18011 ;; | `hide-other' | overridden | no replacement |
18013 ;; Make `C-c C-x' a prefix key
18014 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18016 ;; TAB key with modifiers
18017 (org-defkey org-mode-map "\C-i" 'org-cycle)
18018 (org-defkey org-mode-map [(tab)] 'org-cycle)
18019 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18020 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18021 ;; The following line is necessary under Suse GNU/Linux
18022 (unless (featurep 'xemacs)
18023 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18024 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18025 (define-key org-mode-map [backtab] 'org-shifttab)
18027 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18028 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18029 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18031 ;; Cursor keys with modifiers
18032 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18033 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18034 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18035 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18037 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18038 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18039 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18040 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18042 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18043 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18044 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18045 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18047 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18048 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18049 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18050 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18052 ;; Babel keys
18053 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18054 (mapc (lambda (pair)
18055 (define-key org-babel-map (car pair) (cdr pair)))
18056 org-babel-key-bindings)
18058 ;;; Extra keys for tty access.
18059 ;; We only set them when really needed because otherwise the
18060 ;; menus don't show the simple keys
18062 (when (or org-use-extra-keys
18063 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18064 (not window-system))
18065 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18066 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18067 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18068 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18069 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18070 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18071 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18072 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18073 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18074 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18075 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18076 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18077 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18078 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18079 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18080 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18081 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18082 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18083 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18084 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18085 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18086 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18087 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18088 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18089 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18090 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18091 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18092 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18094 ;; All the other keys
18096 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18097 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18098 (if (boundp 'narrow-map)
18099 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18100 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18101 (if (boundp 'narrow-map)
18102 (org-defkey narrow-map "b" 'org-narrow-to-block)
18103 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18104 (if (boundp 'narrow-map)
18105 (org-defkey narrow-map "e" 'org-narrow-to-element)
18106 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18107 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18108 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18109 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18110 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18111 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18112 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18113 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18114 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18115 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18116 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18117 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18118 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18119 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18120 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18121 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18122 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18123 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18124 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18125 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18126 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18127 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18128 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18129 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18130 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18131 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18132 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18133 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18134 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18135 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18136 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18137 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18138 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18139 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18140 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18141 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18142 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18143 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18144 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18145 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18146 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18147 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18148 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18149 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18150 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18151 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18152 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18153 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18154 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18155 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18156 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18157 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18158 (org-defkey org-mode-map "\C-c^" 'org-sort)
18159 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18160 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18161 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18162 (org-defkey org-mode-map "\C-m" 'org-return)
18163 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18164 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18165 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18166 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18167 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18168 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18169 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18170 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18171 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18172 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18173 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18174 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18175 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18176 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18177 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18178 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18179 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18180 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18181 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18182 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18183 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18184 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18185 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18187 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18188 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18189 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18190 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18192 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18193 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18194 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18195 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18196 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18197 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18198 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18199 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18200 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18201 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18202 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18203 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18204 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18205 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18206 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18207 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18208 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18209 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18210 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18211 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18212 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18213 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18215 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18216 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18217 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18218 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18219 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18221 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18223 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18225 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18226 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18228 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18231 (when (featurep 'xemacs)
18232 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18235 (defconst org-speed-commands-default
18237 ("Outline Navigation")
18238 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18239 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18240 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18241 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18242 ("u" . (org-speed-move-safe 'outline-up-heading))
18243 ("j" . org-goto)
18244 ("g" . (org-refile t))
18245 ("Outline Visibility")
18246 ("c" . org-cycle)
18247 ("C" . org-shifttab)
18248 (" " . org-display-outline-path)
18249 (":" . org-columns)
18250 ("Outline Structure Editing")
18251 ("U" . org-shiftmetaup)
18252 ("D" . org-shiftmetadown)
18253 ("r" . org-metaright)
18254 ("l" . org-metaleft)
18255 ("R" . org-shiftmetaright)
18256 ("L" . org-shiftmetaleft)
18257 ("i" . (progn (forward-char 1) (call-interactively
18258 'org-insert-heading-respect-content)))
18259 ("^" . org-sort)
18260 ("w" . org-refile)
18261 ("a" . org-archive-subtree-default-with-confirmation)
18262 ("." . org-mark-subtree)
18263 ("#" . org-toggle-comment)
18264 ("Clock Commands")
18265 ("I" . org-clock-in)
18266 ("O" . org-clock-out)
18267 ("Meta Data Editing")
18268 ("t" . org-todo)
18269 ("0" . (org-priority ?\ ))
18270 ("1" . (org-priority ?A))
18271 ("2" . (org-priority ?B))
18272 ("3" . (org-priority ?C))
18273 (";" . org-set-tags-command)
18274 ("e" . org-set-effort)
18275 ("E" . org-inc-effort)
18276 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18277 (org-entry-put (point) "APPT_WARNTIME" m)))
18278 ("Agenda Views etc")
18279 ("v" . org-agenda)
18280 ("/" . org-sparse-tree)
18281 ("Misc")
18282 ("o" . org-open-at-point)
18283 ("?" . org-speed-command-help)
18284 ("<" . (org-agenda-set-restriction-lock 'subtree))
18285 (">" . (org-agenda-remove-restriction-lock))
18287 "The default speed commands.")
18289 (defun org-print-speed-command (e)
18290 (if (> (length (car e)) 1)
18291 (progn
18292 (princ "\n")
18293 (princ (car e))
18294 (princ "\n")
18295 (princ (make-string (length (car e)) ?-))
18296 (princ "\n"))
18297 (princ (car e))
18298 (princ " ")
18299 (if (symbolp (cdr e))
18300 (princ (symbol-name (cdr e)))
18301 (prin1 (cdr e)))
18302 (princ "\n")))
18304 (defun org-speed-command-help ()
18305 "Show the available speed commands."
18306 (interactive)
18307 (if (not org-use-speed-commands)
18308 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18309 (with-output-to-temp-buffer "*Help*"
18310 (princ "User-defined Speed commands\n===========================\n")
18311 (mapc 'org-print-speed-command org-speed-commands-user)
18312 (princ "\n")
18313 (princ "Built-in Speed commands\n=======================\n")
18314 (mapc 'org-print-speed-command org-speed-commands-default))
18315 (with-current-buffer "*Help*"
18316 (setq truncate-lines t))))
18318 (defun org-speed-move-safe (cmd)
18319 "Execute CMD, but make sure that the cursor always ends up in a headline.
18320 If not, return to the original position and throw an error."
18321 (interactive)
18322 (let ((pos (point)))
18323 (call-interactively cmd)
18324 (unless (and (bolp) (org-at-heading-p))
18325 (goto-char pos)
18326 (error "Boundary reached while executing %s" cmd))))
18328 (defvar org-self-insert-command-undo-counter 0)
18330 (defvar org-table-auto-blank-field) ; defined in org-table.el
18331 (defvar org-speed-command nil)
18333 (defun org-speed-command-default-hook (keys)
18334 "Hook for activating single-letter speed commands.
18335 `org-speed-commands-default' specifies a minimal command set.
18336 Use `org-speed-commands-user' for further customization."
18337 (when (or (and (bolp) (looking-at org-outline-regexp))
18338 (and (functionp org-use-speed-commands)
18339 (funcall org-use-speed-commands)))
18340 (cdr (assoc keys (append org-speed-commands-user
18341 org-speed-commands-default)))))
18343 (defun org-babel-speed-command-hook (keys)
18344 "Hook for activating single-letter code block commands."
18345 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18346 (cdr (assoc keys org-babel-key-bindings))))
18348 (defcustom org-speed-command-hook
18349 '(org-speed-command-default-hook org-babel-speed-command-hook)
18350 "Hook for activating speed commands at strategic locations.
18351 Hook functions are called in sequence until a valid handler is
18352 found.
18354 Each hook takes a single argument, a user-pressed command key
18355 which is also a `self-insert-command' from the global map.
18357 Within the hook, examine the cursor position and the command key
18358 and return nil or a valid handler as appropriate. Handler could
18359 be one of an interactive command, a function, or a form.
18361 Set `org-use-speed-commands' to non-nil value to enable this
18362 hook. The default setting is `org-speed-command-default-hook'."
18363 :group 'org-structure
18364 :version "24.1"
18365 :type 'hook)
18367 (defun org-self-insert-command (N)
18368 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18369 If the cursor is in a table looking at whitespace, the whitespace is
18370 overwritten, and the table is not marked as requiring realignment."
18371 (interactive "p")
18372 (org-check-before-invisible-edit 'insert)
18373 (cond
18374 ((and org-use-speed-commands
18375 (setq org-speed-command
18376 (run-hook-with-args-until-success
18377 'org-speed-command-hook (this-command-keys))))
18378 (cond
18379 ((commandp org-speed-command)
18380 (setq this-command org-speed-command)
18381 (call-interactively org-speed-command))
18382 ((functionp org-speed-command)
18383 (funcall org-speed-command))
18384 ((and org-speed-command (listp org-speed-command))
18385 (eval org-speed-command))
18386 (t (let (org-use-speed-commands)
18387 (call-interactively 'org-self-insert-command)))))
18388 ((and
18389 (org-table-p)
18390 (progn
18391 ;; check if we blank the field, and if that triggers align
18392 (and (featurep 'org-table) org-table-auto-blank-field
18393 (member last-command
18394 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18395 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18396 ;; got extra space, this field does not determine column width
18397 (let (org-table-may-need-update) (org-table-blank-field))
18398 ;; no extra space, this field may determine column width
18399 (org-table-blank-field)))
18401 (eq N 1)
18402 (looking-at "[^|\n]* |"))
18403 (let (org-table-may-need-update)
18404 (goto-char (1- (match-end 0)))
18405 (backward-delete-char 1)
18406 (goto-char (match-beginning 0))
18407 (self-insert-command N)))
18409 (setq org-table-may-need-update t)
18410 (self-insert-command N)
18411 (org-fix-tags-on-the-fly)
18412 (if org-self-insert-cluster-for-undo
18413 (if (not (eq last-command 'org-self-insert-command))
18414 (setq org-self-insert-command-undo-counter 1)
18415 (if (>= org-self-insert-command-undo-counter 20)
18416 (setq org-self-insert-command-undo-counter 1)
18417 (and (> org-self-insert-command-undo-counter 0)
18418 buffer-undo-list (listp buffer-undo-list)
18419 (not (cadr buffer-undo-list)) ; remove nil entry
18420 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18421 (setq org-self-insert-command-undo-counter
18422 (1+ org-self-insert-command-undo-counter))))))))
18424 (defun org-check-before-invisible-edit (kind)
18425 "Check is editing if kind KIND would be dangerous with invisible text around.
18426 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18427 ;; First, try to get out of here as quickly as possible, to reduce overhead
18428 (if (and org-catch-invisible-edits
18429 (or (not (boundp 'visible-mode)) (not visible-mode))
18430 (or (get-char-property (point) 'invisible)
18431 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18432 ;; OK, we need to take a closer look
18433 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18434 (invisible-before-point (if (bobp) nil (get-char-property
18435 (1- (point)) 'invisible)))
18436 (border-and-ok-direction
18438 ;; Check if we are acting predictably before invisible text
18439 (and invisible-at-point (not invisible-before-point)
18440 (memq kind '(insert delete-backward)))
18441 ;; Check if we are acting predictably after invisible text
18442 ;; This works not well, and I have turned it off. It seems
18443 ;; better to always show and stop after invisible text.
18444 ;; (and (not invisible-at-point) invisible-before-point
18445 ;; (memq kind '(insert delete)))
18447 (when (or (memq invisible-at-point '(outline org-hide-block t))
18448 (memq invisible-before-point '(outline org-hide-block t)))
18449 (if (eq org-catch-invisible-edits 'error)
18450 (error "Editing in invisible areas is prohibited - make visible first"))
18451 (if (and org-custom-properties-overlays
18452 (y-or-n-p "Display invisible properties in this buffer? "))
18453 (org-toggle-custom-properties-visibility)
18454 ;; Make the area visible
18455 (save-excursion
18456 (if invisible-before-point
18457 (goto-char (previous-single-char-property-change
18458 (point) 'invisible)))
18459 (org-cycle))
18460 (cond
18461 ((eq org-catch-invisible-edits 'show)
18462 ;; That's it, we do the edit after showing
18463 (message
18464 "Unfolding invisible region around point before editing")
18465 (sit-for 1))
18466 ((and (eq org-catch-invisible-edits 'smart)
18467 border-and-ok-direction)
18468 (message "Unfolding invisible region around point before editing"))
18470 ;; Don't do the edit, make the user repeat it in full visibility
18471 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18473 (defun org-fix-tags-on-the-fly ()
18474 (when (and (equal (char-after (point-at-bol)) ?*)
18475 (org-at-heading-p))
18476 (org-align-tags-here org-tags-column)))
18478 (defun org-delete-backward-char (N)
18479 "Like `delete-backward-char', insert whitespace at field end in tables.
18480 When deleting backwards, in tables this function will insert whitespace in
18481 front of the next \"|\" separator, to keep the table aligned. The table will
18482 still be marked for re-alignment if the field did fill the entire column,
18483 because, in this case the deletion might narrow the column."
18484 (interactive "p")
18485 (org-check-before-invisible-edit 'delete-backward)
18486 (if (and (org-table-p)
18487 (eq N 1)
18488 (string-match "|" (buffer-substring (point-at-bol) (point)))
18489 (looking-at ".*?|"))
18490 (let ((pos (point))
18491 (noalign (looking-at "[^|\n\r]* |"))
18492 (c org-table-may-need-update))
18493 (backward-delete-char N)
18494 (if (not overwrite-mode)
18495 (progn
18496 (skip-chars-forward "^|")
18497 (insert " ")
18498 (goto-char (1- pos))))
18499 ;; noalign: if there were two spaces at the end, this field
18500 ;; does not determine the width of the column.
18501 (if noalign (setq org-table-may-need-update c)))
18502 (backward-delete-char N)
18503 (org-fix-tags-on-the-fly)))
18505 (defun org-delete-char (N)
18506 "Like `delete-char', but insert whitespace at field end in tables.
18507 When deleting characters, in tables this function will insert whitespace in
18508 front of the next \"|\" separator, to keep the table aligned. The table will
18509 still be marked for re-alignment if the field did fill the entire column,
18510 because, in this case the deletion might narrow the column."
18511 (interactive "p")
18512 (org-check-before-invisible-edit 'delete)
18513 (if (and (org-table-p)
18514 (not (bolp))
18515 (not (= (char-after) ?|))
18516 (eq N 1))
18517 (if (looking-at ".*?|")
18518 (let ((pos (point))
18519 (noalign (looking-at "[^|\n\r]* |"))
18520 (c org-table-may-need-update))
18521 (replace-match (concat
18522 (substring (match-string 0) 1 -1)
18523 " |"))
18524 (goto-char pos)
18525 ;; noalign: if there were two spaces at the end, this field
18526 ;; does not determine the width of the column.
18527 (if noalign (setq org-table-may-need-update c)))
18528 (delete-char N))
18529 (delete-char N)
18530 (org-fix-tags-on-the-fly)))
18532 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18533 (put 'org-self-insert-command 'delete-selection t)
18534 (put 'orgtbl-self-insert-command 'delete-selection t)
18535 (put 'org-delete-char 'delete-selection 'supersede)
18536 (put 'org-delete-backward-char 'delete-selection 'supersede)
18537 (put 'org-yank 'delete-selection 'yank)
18539 ;; Make `flyspell-mode' delay after some commands
18540 (put 'org-self-insert-command 'flyspell-delayed t)
18541 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18542 (put 'org-delete-char 'flyspell-delayed t)
18543 (put 'org-delete-backward-char 'flyspell-delayed t)
18545 ;; Make pabbrev-mode expand after org-mode commands
18546 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18547 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18549 ;; How to do this: Measure non-white length of current string
18550 ;; If equal to column width, we should realign.
18552 (defun org-remap (map &rest commands)
18553 "In MAP, remap the functions given in COMMANDS.
18554 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18555 (let (new old)
18556 (while commands
18557 (setq old (pop commands) new (pop commands))
18558 (if (fboundp 'command-remapping)
18559 (org-defkey map (vector 'remap old) new)
18560 (substitute-key-definition old new map global-map)))))
18562 (when (eq org-enable-table-editor 'optimized)
18563 ;; If the user wants maximum table support, we need to hijack
18564 ;; some standard editing functions
18565 (org-remap org-mode-map
18566 'self-insert-command 'org-self-insert-command
18567 'delete-char 'org-delete-char
18568 'delete-backward-char 'org-delete-backward-char)
18569 (org-defkey org-mode-map "|" 'org-force-self-insert))
18571 (defvar org-ctrl-c-ctrl-c-hook nil
18572 "Hook for functions attaching themselves to `C-c C-c'.
18574 This can be used to add additional functionality to the C-c C-c
18575 key which executes context-dependent commands. This hook is run
18576 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18577 run after the last test.
18579 Each function will be called with no arguments. The function
18580 must check if the context is appropriate for it to act. If yes,
18581 it should do its thing and then return a non-nil value. If the
18582 context is wrong, just do nothing and return nil.")
18584 (defvar org-ctrl-c-ctrl-c-final-hook nil
18585 "Hook for functions attaching themselves to `C-c C-c'.
18587 This can be used to add additional functionality to the C-c C-c
18588 key which executes context-dependent commands. This hook is run
18589 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18590 before the first test.
18592 Each function will be called with no arguments. The function
18593 must check if the context is appropriate for it to act. If yes,
18594 it should do its thing and then return a non-nil value. If the
18595 context is wrong, just do nothing and return nil.")
18597 (defvar org-tab-first-hook nil
18598 "Hook for functions to attach themselves to TAB.
18599 See `org-ctrl-c-ctrl-c-hook' for more information.
18600 This hook runs as the first action when TAB is pressed, even before
18601 `org-cycle' messes around with the `outline-regexp' to cater for
18602 inline tasks and plain list item folding.
18603 If any function in this hook returns t, any other actions that
18604 would have been caused by TAB (such as table field motion or visibility
18605 cycling) will not occur.")
18607 (defvar org-tab-after-check-for-table-hook nil
18608 "Hook for functions to attach themselves to TAB.
18609 See `org-ctrl-c-ctrl-c-hook' for more information.
18610 This hook runs after it has been established that the cursor is not in a
18611 table, but before checking if the cursor is in a headline or if global cycling
18612 should be done.
18613 If any function in this hook returns t, not other actions like visibility
18614 cycling will be done.")
18616 (defvar org-tab-after-check-for-cycling-hook nil
18617 "Hook for functions to attach themselves to TAB.
18618 See `org-ctrl-c-ctrl-c-hook' for more information.
18619 This hook runs after it has been established that not table field motion and
18620 not visibility should be done because of current context. This is probably
18621 the place where a package like yasnippets can hook in.")
18623 (defvar org-tab-before-tab-emulation-hook nil
18624 "Hook for functions to attach themselves to TAB.
18625 See `org-ctrl-c-ctrl-c-hook' for more information.
18626 This hook runs after every other options for TAB have been exhausted, but
18627 before indentation and \t insertion takes place.")
18629 (defvar org-metaleft-hook nil
18630 "Hook for functions attaching themselves to `M-left'.
18631 See `org-ctrl-c-ctrl-c-hook' for more information.")
18632 (defvar org-metaright-hook nil
18633 "Hook for functions attaching themselves to `M-right'.
18634 See `org-ctrl-c-ctrl-c-hook' for more information.")
18635 (defvar org-metaup-hook nil
18636 "Hook for functions attaching themselves to `M-up'.
18637 See `org-ctrl-c-ctrl-c-hook' for more information.")
18638 (defvar org-metadown-hook nil
18639 "Hook for functions attaching themselves to `M-down'.
18640 See `org-ctrl-c-ctrl-c-hook' for more information.")
18641 (defvar org-shiftmetaleft-hook nil
18642 "Hook for functions attaching themselves to `M-S-left'.
18643 See `org-ctrl-c-ctrl-c-hook' for more information.")
18644 (defvar org-shiftmetaright-hook nil
18645 "Hook for functions attaching themselves to `M-S-right'.
18646 See `org-ctrl-c-ctrl-c-hook' for more information.")
18647 (defvar org-shiftmetaup-hook nil
18648 "Hook for functions attaching themselves to `M-S-up'.
18649 See `org-ctrl-c-ctrl-c-hook' for more information.")
18650 (defvar org-shiftmetadown-hook nil
18651 "Hook for functions attaching themselves to `M-S-down'.
18652 See `org-ctrl-c-ctrl-c-hook' for more information.")
18653 (defvar org-metareturn-hook nil
18654 "Hook for functions attaching themselves to `M-RET'.
18655 See `org-ctrl-c-ctrl-c-hook' for more information.")
18656 (defvar org-shiftup-hook nil
18657 "Hook for functions attaching themselves to `S-up'.
18658 See `org-ctrl-c-ctrl-c-hook' for more information.")
18659 (defvar org-shiftup-final-hook nil
18660 "Hook for functions attaching themselves to `S-up'.
18661 This one runs after all other options except shift-select have been excluded.
18662 See `org-ctrl-c-ctrl-c-hook' for more information.")
18663 (defvar org-shiftdown-hook nil
18664 "Hook for functions attaching themselves to `S-down'.
18665 See `org-ctrl-c-ctrl-c-hook' for more information.")
18666 (defvar org-shiftdown-final-hook nil
18667 "Hook for functions attaching themselves to `S-down'.
18668 This one runs after all other options except shift-select have been excluded.
18669 See `org-ctrl-c-ctrl-c-hook' for more information.")
18670 (defvar org-shiftleft-hook nil
18671 "Hook for functions attaching themselves to `S-left'.
18672 See `org-ctrl-c-ctrl-c-hook' for more information.")
18673 (defvar org-shiftleft-final-hook nil
18674 "Hook for functions attaching themselves to `S-left'.
18675 This one runs after all other options except shift-select have been excluded.
18676 See `org-ctrl-c-ctrl-c-hook' for more information.")
18677 (defvar org-shiftright-hook nil
18678 "Hook for functions attaching themselves to `S-right'.
18679 See `org-ctrl-c-ctrl-c-hook' for more information.")
18680 (defvar org-shiftright-final-hook nil
18681 "Hook for functions attaching themselves to `S-right'.
18682 This one runs after all other options except shift-select have been excluded.
18683 See `org-ctrl-c-ctrl-c-hook' for more information.")
18685 (defun org-modifier-cursor-error ()
18686 "Throw an error, a modified cursor command was applied in wrong context."
18687 (error "This command is active in special context like tables, headlines or items"))
18689 (defun org-shiftselect-error ()
18690 "Throw an error because Shift-Cursor command was applied in wrong context."
18691 (if (and (boundp 'shift-select-mode) shift-select-mode)
18692 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18693 (error "This command works only in special context like headlines or timestamps")))
18695 (defun org-call-for-shift-select (cmd)
18696 (let ((this-command-keys-shift-translated t))
18697 (call-interactively cmd)))
18699 (defun org-shifttab (&optional arg)
18700 "Global visibility cycling or move to previous table field.
18701 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18702 on context.
18703 See the individual commands for more information."
18704 (interactive "P")
18705 (cond
18706 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18707 ((integerp arg)
18708 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18709 (message "Content view to level: %d" arg)
18710 (org-content (prefix-numeric-value arg2))
18711 (setq org-cycle-global-status 'overview)))
18712 (t (call-interactively 'org-global-cycle))))
18714 (defun org-shiftmetaleft ()
18715 "Promote subtree or delete table column.
18716 Calls `org-promote-subtree', `org-outdent-item-tree', or
18717 `org-table-delete-column', depending on context. See the
18718 individual commands for more information."
18719 (interactive)
18720 (cond
18721 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18722 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18723 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18724 ((if (not (org-region-active-p)) (org-at-item-p)
18725 (save-excursion (goto-char (region-beginning))
18726 (org-at-item-p)))
18727 (call-interactively 'org-outdent-item-tree))
18728 (t (org-modifier-cursor-error))))
18730 (defun org-shiftmetaright ()
18731 "Demote subtree or insert table column.
18732 Calls `org-demote-subtree', `org-indent-item-tree', or
18733 `org-table-insert-column', depending on context. See the
18734 individual commands for more information."
18735 (interactive)
18736 (cond
18737 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18738 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18739 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18740 ((if (not (org-region-active-p)) (org-at-item-p)
18741 (save-excursion (goto-char (region-beginning))
18742 (org-at-item-p)))
18743 (call-interactively 'org-indent-item-tree))
18744 (t (org-modifier-cursor-error))))
18746 (defun org-shiftmetaup (&optional arg)
18747 "Move subtree up or kill table row.
18748 Calls `org-move-subtree-up' or `org-table-kill-row' or
18749 `org-move-item-up' or `org-timestamp-up', depending on context.
18750 See the individual commands for more information."
18751 (interactive "P")
18752 (cond
18753 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18754 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18755 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18756 ((org-at-item-p) (call-interactively 'org-move-item-up))
18757 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18758 (call-interactively 'org-timestamp-up)))
18759 (t (org-modifier-cursor-error))))
18761 (defun org-shiftmetadown (&optional arg)
18762 "Move subtree down or insert table row.
18763 Calls `org-move-subtree-down' or `org-table-insert-row' or
18764 `org-move-item-down' or `org-timestamp-up', depending on context.
18765 See the individual commands for more information."
18766 (interactive "P")
18767 (cond
18768 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18769 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18770 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18771 ((org-at-item-p) (call-interactively 'org-move-item-down))
18772 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18773 (call-interactively 'org-timestamp-down)))
18774 (t (org-modifier-cursor-error))))
18776 (defsubst org-hidden-tree-error ()
18777 (error
18778 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18780 (defun org-metaleft (&optional arg)
18781 "Promote heading or move table column to left.
18782 Calls `org-do-promote' or `org-table-move-column', depending on context.
18783 With no specific context, calls the Emacs default `backward-word'.
18784 See the individual commands for more information."
18785 (interactive "P")
18786 (cond
18787 ((run-hook-with-args-until-success 'org-metaleft-hook))
18788 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18789 ((org-with-limited-levels
18790 (or (org-at-heading-p)
18791 (and (org-region-active-p)
18792 (save-excursion
18793 (goto-char (region-beginning))
18794 (org-at-heading-p)))))
18795 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18796 (call-interactively 'org-do-promote))
18797 ;; At an inline task.
18798 ((org-at-heading-p)
18799 (call-interactively 'org-inlinetask-promote))
18800 ((or (org-at-item-p)
18801 (and (org-region-active-p)
18802 (save-excursion
18803 (goto-char (region-beginning))
18804 (org-at-item-p))))
18805 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18806 (call-interactively 'org-outdent-item))
18807 (t (call-interactively 'backward-word))))
18809 (defun org-metaright (&optional arg)
18810 "Demote a subtree, a list item or move table column to right.
18811 In front of a drawer or a block keyword, indent it correctly.
18812 With no specific context, calls the Emacs default `forward-word'.
18813 See the individual commands for more information."
18814 (interactive "P")
18815 (cond
18816 ((run-hook-with-args-until-success 'org-metaright-hook))
18817 ((org-at-table-p) (call-interactively 'org-table-move-column))
18818 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18819 ((org-at-block-p) (call-interactively 'org-indent-block))
18820 ((org-with-limited-levels
18821 (or (org-at-heading-p)
18822 (and (org-region-active-p)
18823 (save-excursion
18824 (goto-char (region-beginning))
18825 (org-at-heading-p)))))
18826 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18827 (call-interactively 'org-do-demote))
18828 ;; At an inline task.
18829 ((org-at-heading-p)
18830 (call-interactively 'org-inlinetask-demote))
18831 ((or (org-at-item-p)
18832 (and (org-region-active-p)
18833 (save-excursion
18834 (goto-char (region-beginning))
18835 (org-at-item-p))))
18836 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18837 (call-interactively 'org-indent-item))
18838 (t (call-interactively 'forward-word))))
18840 (defun org-check-for-hidden (what)
18841 "Check if there are hidden headlines/items in the current visual line.
18842 WHAT can be either `headlines' or `items'. If the current line is
18843 an outline or item heading and it has a folded subtree below it,
18844 this function returns t, nil otherwise."
18845 (let ((re (cond
18846 ((eq what 'headlines) org-outline-regexp-bol)
18847 ((eq what 'items) (org-item-beginning-re))
18848 (t (error "This should not happen"))))
18849 beg end)
18850 (save-excursion
18851 (catch 'exit
18852 (unless (org-region-active-p)
18853 (setq beg (point-at-bol))
18854 (beginning-of-line 2)
18855 (while (and (not (eobp)) ;; this is like `next-line'
18856 (get-char-property (1- (point)) 'invisible))
18857 (beginning-of-line 2))
18858 (setq end (point))
18859 (goto-char beg)
18860 (goto-char (point-at-eol))
18861 (setq end (max end (point)))
18862 (while (re-search-forward re end t)
18863 (if (get-char-property (match-beginning 0) 'invisible)
18864 (throw 'exit t))))
18865 nil))))
18867 (autoload 'org-element-at-point "org-element")
18869 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18870 (declare-function org-element-type "org-element" (element))
18871 (declare-function org-element-contents "org-element" (element))
18872 (declare-function org-element-property "org-element" (property element))
18873 (declare-function org-element-paragraph-parser "org-element" (limit))
18874 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18875 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18876 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18877 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18878 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18880 (defun org-metaup (&optional arg)
18881 "Move subtree up or move table row up.
18882 Calls `org-move-subtree-up' or `org-table-move-row' or
18883 `org-move-item-up', depending on context. See the individual commands
18884 for more information."
18885 (interactive "P")
18886 (cond
18887 ((run-hook-with-args-until-success 'org-metaup-hook))
18888 ((org-region-active-p)
18889 (let* ((a (min (region-beginning) (region-end)))
18890 (b (1- (max (region-beginning) (region-end))))
18891 (c (save-excursion (goto-char a)
18892 (move-beginning-of-line 0)))
18893 (d (save-excursion (goto-char a)
18894 (move-end-of-line 0) (point))))
18895 (transpose-regions a b c d)
18896 (goto-char c)))
18897 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18898 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18899 ((org-at-item-p) (call-interactively 'org-move-item-up))
18900 (t (org-drag-element-backward))))
18902 (defun org-metadown (&optional arg)
18903 "Move subtree down or move table row down.
18904 Calls `org-move-subtree-down' or `org-table-move-row' or
18905 `org-move-item-down', depending on context. See the individual
18906 commands for more information."
18907 (interactive "P")
18908 (cond
18909 ((run-hook-with-args-until-success 'org-metadown-hook))
18910 ((org-region-active-p)
18911 (let* ((a (min (region-beginning) (region-end)))
18912 (b (max (region-beginning) (region-end)))
18913 (c (save-excursion (goto-char b)
18914 (move-beginning-of-line 1)))
18915 (d (save-excursion (goto-char b)
18916 (move-end-of-line 1) (1+ (point)))))
18917 (transpose-regions a b c d)
18918 (goto-char d)))
18919 ((org-at-table-p) (call-interactively 'org-table-move-row))
18920 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18921 ((org-at-item-p) (call-interactively 'org-move-item-down))
18922 (t (org-drag-element-forward))))
18924 (defun org-shiftup (&optional arg)
18925 "Increase item in timestamp or increase priority of current headline.
18926 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18927 depending on context. See the individual commands for more information."
18928 (interactive "P")
18929 (cond
18930 ((run-hook-with-args-until-success 'org-shiftup-hook))
18931 ((and org-support-shift-select (org-region-active-p))
18932 (org-call-for-shift-select 'previous-line))
18933 ((org-at-timestamp-p t)
18934 (call-interactively (if org-edit-timestamp-down-means-later
18935 'org-timestamp-down 'org-timestamp-up)))
18936 ((and (not (eq org-support-shift-select 'always))
18937 org-enable-priority-commands
18938 (org-at-heading-p))
18939 (call-interactively 'org-priority-up))
18940 ((and (not org-support-shift-select) (org-at-item-p))
18941 (call-interactively 'org-previous-item))
18942 ((org-clocktable-try-shift 'up arg))
18943 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18944 (org-support-shift-select
18945 (org-call-for-shift-select 'previous-line))
18946 (t (org-shiftselect-error))))
18948 (defun org-shiftdown (&optional arg)
18949 "Decrease item in timestamp or decrease priority of current headline.
18950 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18951 depending on context. See the individual commands for more information."
18952 (interactive "P")
18953 (cond
18954 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18955 ((and org-support-shift-select (org-region-active-p))
18956 (org-call-for-shift-select 'next-line))
18957 ((org-at-timestamp-p t)
18958 (call-interactively (if org-edit-timestamp-down-means-later
18959 'org-timestamp-up 'org-timestamp-down)))
18960 ((and (not (eq org-support-shift-select 'always))
18961 org-enable-priority-commands
18962 (org-at-heading-p))
18963 (call-interactively 'org-priority-down))
18964 ((and (not org-support-shift-select) (org-at-item-p))
18965 (call-interactively 'org-next-item))
18966 ((org-clocktable-try-shift 'down arg))
18967 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18968 (org-support-shift-select
18969 (org-call-for-shift-select 'next-line))
18970 (t (org-shiftselect-error))))
18972 (defun org-shiftright (&optional arg)
18973 "Cycle the thing at point or in the current line, depending on context.
18974 Depending on context, this does one of the following:
18976 - switch a timestamp at point one day into the future
18977 - on a headline, switch to the next TODO keyword.
18978 - on an item, switch entire list to the next bullet type
18979 - on a property line, switch to the next allowed value
18980 - on a clocktable definition line, move time block into the future"
18981 (interactive "P")
18982 (cond
18983 ((run-hook-with-args-until-success 'org-shiftright-hook))
18984 ((and org-support-shift-select (org-region-active-p))
18985 (org-call-for-shift-select 'forward-char))
18986 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18987 ((and (not (eq org-support-shift-select 'always))
18988 (org-at-heading-p))
18989 (let ((org-inhibit-logging
18990 (not org-treat-S-cursor-todo-selection-as-state-change))
18991 (org-inhibit-blocking
18992 (not org-treat-S-cursor-todo-selection-as-state-change)))
18993 (org-call-with-arg 'org-todo 'right)))
18994 ((or (and org-support-shift-select
18995 (not (eq org-support-shift-select 'always))
18996 (org-at-item-bullet-p))
18997 (and (not org-support-shift-select) (org-at-item-p)))
18998 (org-call-with-arg 'org-cycle-list-bullet nil))
18999 ((and (not (eq org-support-shift-select 'always))
19000 (org-at-property-p))
19001 (call-interactively 'org-property-next-allowed-value))
19002 ((org-clocktable-try-shift 'right arg))
19003 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19004 (org-support-shift-select
19005 (org-call-for-shift-select 'forward-char))
19006 (t (org-shiftselect-error))))
19008 (defun org-shiftleft (&optional arg)
19009 "Cycle the thing at point or in the current line, depending on context.
19010 Depending on context, this does one of the following:
19012 - switch a timestamp at point one day into the past
19013 - on a headline, switch to the previous TODO keyword.
19014 - on an item, switch entire list to the previous bullet type
19015 - on a property line, switch to the previous allowed value
19016 - on a clocktable definition line, move time block into the past"
19017 (interactive "P")
19018 (cond
19019 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19020 ((and org-support-shift-select (org-region-active-p))
19021 (org-call-for-shift-select 'backward-char))
19022 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19023 ((and (not (eq org-support-shift-select 'always))
19024 (org-at-heading-p))
19025 (let ((org-inhibit-logging
19026 (not org-treat-S-cursor-todo-selection-as-state-change))
19027 (org-inhibit-blocking
19028 (not org-treat-S-cursor-todo-selection-as-state-change)))
19029 (org-call-with-arg 'org-todo 'left)))
19030 ((or (and org-support-shift-select
19031 (not (eq org-support-shift-select 'always))
19032 (org-at-item-bullet-p))
19033 (and (not org-support-shift-select) (org-at-item-p)))
19034 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19035 ((and (not (eq org-support-shift-select 'always))
19036 (org-at-property-p))
19037 (call-interactively 'org-property-previous-allowed-value))
19038 ((org-clocktable-try-shift 'left arg))
19039 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19040 (org-support-shift-select
19041 (org-call-for-shift-select 'backward-char))
19042 (t (org-shiftselect-error))))
19044 (defun org-shiftcontrolright ()
19045 "Switch to next TODO set."
19046 (interactive)
19047 (cond
19048 ((and org-support-shift-select (org-region-active-p))
19049 (org-call-for-shift-select 'forward-word))
19050 ((and (not (eq org-support-shift-select 'always))
19051 (org-at-heading-p))
19052 (org-call-with-arg 'org-todo 'nextset))
19053 (org-support-shift-select
19054 (org-call-for-shift-select 'forward-word))
19055 (t (org-shiftselect-error))))
19057 (defun org-shiftcontrolleft ()
19058 "Switch to previous TODO set."
19059 (interactive)
19060 (cond
19061 ((and org-support-shift-select (org-region-active-p))
19062 (org-call-for-shift-select 'backward-word))
19063 ((and (not (eq org-support-shift-select 'always))
19064 (org-at-heading-p))
19065 (org-call-with-arg 'org-todo 'previousset))
19066 (org-support-shift-select
19067 (org-call-for-shift-select 'backward-word))
19068 (t (org-shiftselect-error))))
19070 (defun org-shiftcontrolup ()
19071 "Change timestamps synchronously up in CLOCK log lines."
19072 (interactive)
19073 (cond ((and (not org-support-shift-select)
19074 (org-at-clock-log-p)
19075 (org-at-timestamp-p t))
19076 (org-clock-timestamps-up))
19077 (t (org-shiftselect-error))))
19079 (defun org-shiftcontroldown ()
19080 "Change timestamps synchronously down in CLOCK log lines."
19081 (interactive)
19082 (cond ((and (not org-support-shift-select)
19083 (org-at-clock-log-p)
19084 (org-at-timestamp-p t))
19085 (org-clock-timestamps-down))
19086 (t (org-shiftselect-error))))
19088 (defun org-ctrl-c-ret ()
19089 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19090 (interactive)
19091 (cond
19092 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19093 (t (call-interactively 'org-insert-heading))))
19095 (defun org-find-visible ()
19096 (let ((s (point)))
19097 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19098 (get-char-property s 'invisible)))
19100 (defun org-find-invisible ()
19101 (let ((s (point)))
19102 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19103 (not (get-char-property s 'invisible))))
19106 (defun org-copy-visible (beg end)
19107 "Copy the visible parts of the region."
19108 (interactive "r")
19109 (let (snippets s)
19110 (save-excursion
19111 (save-restriction
19112 (narrow-to-region beg end)
19113 (setq s (goto-char (point-min)))
19114 (while (not (= (point) (point-max)))
19115 (goto-char (org-find-invisible))
19116 (push (buffer-substring s (point)) snippets)
19117 (setq s (goto-char (org-find-visible))))))
19118 (kill-new (apply 'concat (nreverse snippets)))))
19120 (defun org-copy-special ()
19121 "Copy region in table or copy current subtree.
19122 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19123 See the individual commands for more information."
19124 (interactive)
19125 (call-interactively
19126 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19128 (defun org-cut-special ()
19129 "Cut region in table or cut current subtree.
19130 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19131 See the individual commands for more information."
19132 (interactive)
19133 (call-interactively
19134 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19136 (defun org-paste-special (arg)
19137 "Paste rectangular region into table, or past subtree relative to level.
19138 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19139 See the individual commands for more information."
19140 (interactive "P")
19141 (if (org-at-table-p)
19142 (org-table-paste-rectangle)
19143 (org-paste-subtree arg)))
19145 (defun org-edit-special (&optional arg)
19146 "Call a special editor for the stuff at point.
19147 When at a table, call the formula editor with `org-table-edit-formulas'.
19148 When at the first line of an src example, call `org-edit-src-code'.
19149 When in an #+include line, visit the include file. Otherwise call
19150 `ffap' to visit the file at point."
19151 (interactive)
19152 ;; possibly prep session before editing source
19153 (when arg
19154 (let* ((info (org-babel-get-src-block-info))
19155 (lang (nth 0 info))
19156 (params (nth 2 info))
19157 (session (cdr (assoc :session params))))
19158 (when (and info session) ;; we are in a source-code block with a session
19159 (funcall
19160 (intern (concat "org-babel-prep-session:" lang)) session params))))
19161 (cond ;; proceed with `org-edit-special'
19162 ((save-excursion
19163 (beginning-of-line 1)
19164 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19165 (find-file (org-trim (match-string 1))))
19166 ((org-edit-src-code))
19167 ((org-edit-fixed-width-region))
19168 ((org-at-table.el-p)
19169 (org-edit-src-code))
19170 ((or (org-at-table-p)
19171 (save-excursion
19172 (beginning-of-line 1)
19173 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19174 (call-interactively 'org-table-edit-formulas))
19175 (t (call-interactively 'ffap))))
19177 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19178 (defun org-ctrl-c-ctrl-c (&optional arg)
19179 "Set tags in headline, or update according to changed information at point.
19181 This command does many different things, depending on context:
19183 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19184 this is what we do.
19186 - If the cursor is on a statistics cookie, update it.
19188 - If the cursor is in a headline, prompt for tags and insert them
19189 into the current line, aligned to `org-tags-column'. When called
19190 with prefix arg, realign all tags in the current buffer.
19192 - If the cursor is in one of the special #+KEYWORD lines, this
19193 triggers scanning the buffer for these lines and updating the
19194 information.
19196 - If the cursor is inside a table, realign the table. This command
19197 works even if the automatic table editor has been turned off.
19199 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19200 the entire table.
19202 - If the cursor is at a footnote reference or definition, jump to
19203 the corresponding definition or references, respectively.
19205 - If the cursor is a the beginning of a dynamic block, update it.
19207 - If the current buffer is a capture buffer, close note and file it.
19209 - If the cursor is on a <<<target>>>, update radio targets and
19210 corresponding links in this buffer.
19212 - If the cursor is on a numbered item in a plain list, renumber the
19213 ordered list.
19215 - If the cursor is on a checkbox, toggle it.
19217 - If the cursor is on a code block, evaluate it. The variable
19218 `org-confirm-babel-evaluate' can be used to control prompting
19219 before code block evaluation, by default every code block
19220 evaluation requires confirmation. Code block evaluation can be
19221 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19222 (interactive "P")
19223 (let ((org-enable-table-editor t))
19224 (cond
19225 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19226 org-occur-highlights
19227 org-latex-fragment-image-overlays)
19228 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19229 (org-remove-occur-highlights)
19230 (org-remove-latex-fragment-image-overlays)
19231 (message "Temporary highlights/overlays removed from current buffer"))
19232 ((and (local-variable-p 'org-finish-function (current-buffer))
19233 (fboundp org-finish-function))
19234 (funcall org-finish-function))
19235 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19236 ((org-in-regexp org-ts-regexp-both)
19237 (org-timestamp-change 0 'day))
19238 ((or (looking-at org-property-start-re)
19239 (org-at-property-p))
19240 (call-interactively 'org-property-action))
19241 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19242 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19243 (or (org-at-heading-p) (org-at-item-p)))
19244 (call-interactively 'org-update-statistics-cookies))
19245 ((org-at-heading-p) (call-interactively 'org-set-tags))
19246 ((org-at-table.el-p)
19247 (message "Use C-c ' to edit table.el tables"))
19248 ((org-at-table-p)
19249 (org-table-maybe-eval-formula)
19250 (if arg
19251 (call-interactively 'org-table-recalculate)
19252 (org-table-maybe-recalculate-line))
19253 (call-interactively 'org-table-align)
19254 (orgtbl-send-table 'maybe))
19255 ((or (org-footnote-at-reference-p)
19256 (org-footnote-at-definition-p))
19257 (call-interactively 'org-footnote-action))
19258 ((org-at-item-checkbox-p)
19259 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19260 ;; list only if at top item.
19261 (let* ((cbox (match-string 1))
19262 (struct (org-list-struct))
19263 (old-struct (copy-tree struct))
19264 (parents (org-list-parents-alist struct))
19265 (orderedp (org-entry-get nil "ORDERED"))
19266 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19267 block-item)
19268 ;; Use a light version of `org-toggle-checkbox' to avoid
19269 ;; computing list structure twice.
19270 (let ((new-box (cond
19271 ((equal arg '(16)) "[-]")
19272 ((equal arg '(4)) nil)
19273 ((equal "[X]" cbox) "[ ]")
19274 (t "[X]"))))
19275 (if (and firstp arg)
19276 ;; If at first item of sub-list, remove check-box from
19277 ;; every item at the same level.
19278 (mapc
19279 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19280 (org-list-get-all-items
19281 (point-at-bol) struct (org-list-prevs-alist struct)))
19282 (org-list-set-checkbox (point-at-bol) struct new-box)))
19283 ;; Replicate `org-list-write-struct', while grabbing a return
19284 ;; value from `org-list-struct-fix-box'.
19285 (org-list-struct-fix-ind struct parents 2)
19286 (org-list-struct-fix-item-end struct)
19287 (let ((prevs (org-list-prevs-alist struct)))
19288 (org-list-struct-fix-bul struct prevs)
19289 (org-list-struct-fix-ind struct parents)
19290 (setq block-item
19291 (org-list-struct-fix-box struct parents prevs orderedp)))
19292 (org-list-struct-apply-struct struct old-struct)
19293 (org-update-checkbox-count-maybe)
19294 (when block-item
19295 (message
19296 "Checkboxes were removed due to unchecked box at line %d"
19297 (org-current-line block-item)))
19298 (when firstp (org-list-send-list 'maybe))))
19299 ((org-at-item-p)
19300 ;; Cursor at an item: repair list. Do checkbox related actions
19301 ;; only if function was called with an argument. Send list only
19302 ;; if at top item.
19303 (let* ((struct (org-list-struct))
19304 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19305 old-struct)
19306 (when arg
19307 (setq old-struct (copy-tree struct))
19308 (if firstp
19309 ;; If at first item of sub-list, add check-box to every
19310 ;; item at the same level.
19311 (mapc
19312 (lambda (pos)
19313 (unless (org-list-get-checkbox pos struct)
19314 (org-list-set-checkbox pos struct "[ ]")))
19315 (org-list-get-all-items
19316 (point-at-bol) struct (org-list-prevs-alist struct)))
19317 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19318 (org-list-write-struct
19319 struct (org-list-parents-alist struct) old-struct)
19320 (when arg (org-update-checkbox-count-maybe))
19321 (when firstp (org-list-send-list 'maybe))))
19322 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19323 ;; Dynamic block
19324 (beginning-of-line 1)
19325 (save-excursion (org-update-dblock)))
19326 ((save-excursion
19327 (let ((case-fold-search t))
19328 (beginning-of-line 1)
19329 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19330 (cond
19331 ((or (equal (match-string 1) "TBLFM")
19332 (equal (match-string 1) "tblfm"))
19333 ;; Recalculate the table before this line
19334 (save-excursion
19335 (beginning-of-line 1)
19336 (skip-chars-backward " \r\n\t")
19337 (if (org-at-table-p)
19338 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19340 (let ((org-inhibit-startup-visibility-stuff t)
19341 (org-startup-align-all-tables nil))
19342 (when (boundp 'org-table-coordinate-overlays)
19343 (mapc 'delete-overlay org-table-coordinate-overlays)
19344 (setq org-table-coordinate-overlays nil))
19345 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19346 (message "Local setup has been refreshed"))))
19347 ((org-clock-update-time-maybe))
19349 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19350 (error "C-c C-c can do nothing useful at this location"))))))
19352 (defun org-mode-restart ()
19353 "Restart Org-mode, to scan again for special lines.
19354 Also updates the keyword regular expressions."
19355 (interactive)
19356 (org-mode)
19357 (message "Org-mode restarted"))
19359 (defun org-kill-note-or-show-branches ()
19360 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19361 (interactive)
19362 (if (not org-finish-function)
19363 (progn
19364 (hide-subtree)
19365 (call-interactively 'show-branches))
19366 (let ((org-note-abort t))
19367 (funcall org-finish-function))))
19369 (defun org-return (&optional indent)
19370 "Goto next table row or insert a newline.
19371 Calls `org-table-next-row' or `newline', depending on context.
19372 See the individual commands for more information."
19373 (interactive)
19374 (let (org-ts-what)
19375 (cond
19376 ((or (bobp) (org-in-src-block-p))
19377 (if indent (newline-and-indent) (newline)))
19378 ((org-at-table-p)
19379 (org-table-justify-field-maybe)
19380 (call-interactively 'org-table-next-row))
19381 ;; when `newline-and-indent' is called within a list, make sure
19382 ;; text moved stays inside the item.
19383 ((and (org-in-item-p) indent)
19384 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19385 (progn
19386 (save-match-data (newline))
19387 (org-indent-line-to (length (match-string 0))))
19388 (let ((ind (org-get-indentation)))
19389 (newline)
19390 (if (org-looking-back org-list-end-re)
19391 (org-indent-line)
19392 (org-indent-line-to ind)))))
19393 ((and org-return-follows-link
19394 (org-at-timestamp-p t)
19395 (not (eq org-ts-what 'after)))
19396 (org-follow-timestamp-link))
19397 ((and org-return-follows-link
19398 (let ((tprop (get-text-property (point) 'face)))
19399 (or (eq tprop 'org-link)
19400 (and (listp tprop) (memq 'org-link tprop)))))
19401 (call-interactively 'org-open-at-point))
19402 ((and (org-at-heading-p)
19403 (looking-at
19404 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19405 (org-show-entry)
19406 (end-of-line 1)
19407 (newline))
19408 (t (if indent (newline-and-indent) (newline))))))
19410 (defun org-return-indent ()
19411 "Goto next table row or insert a newline and indent.
19412 Calls `org-table-next-row' or `newline-and-indent', depending on
19413 context. See the individual commands for more information."
19414 (interactive)
19415 (org-return t))
19417 (defun org-ctrl-c-star ()
19418 "Compute table, or change heading status of lines.
19419 Calls `org-table-recalculate' or `org-toggle-heading',
19420 depending on context."
19421 (interactive)
19422 (cond
19423 ((org-at-table-p)
19424 (call-interactively 'org-table-recalculate))
19426 ;; Convert all lines in region to list items
19427 (call-interactively 'org-toggle-heading))))
19429 (defun org-ctrl-c-minus ()
19430 "Insert separator line in table or modify bullet status of line.
19431 Also turns a plain line or a region of lines into list items.
19432 Calls `org-table-insert-hline', `org-toggle-item', or
19433 `org-cycle-list-bullet', depending on context."
19434 (interactive)
19435 (cond
19436 ((org-at-table-p)
19437 (call-interactively 'org-table-insert-hline))
19438 ((org-region-active-p)
19439 (call-interactively 'org-toggle-item))
19440 ((org-in-item-p)
19441 (call-interactively 'org-cycle-list-bullet))
19443 (call-interactively 'org-toggle-item))))
19445 (defun org-toggle-item (arg)
19446 "Convert headings or normal lines to items, items to normal lines.
19447 If there is no active region, only the current line is considered.
19449 If the first non blank line in the region is an headline, convert
19450 all headlines to items, shifting text accordingly.
19452 If it is an item, convert all items to normal lines.
19454 If it is normal text, change region into an item. With a prefix
19455 argument ARG, change each line in region into an item."
19456 (interactive "P")
19457 (let ((shift-text
19458 (function
19459 ;; Shift text in current section to IND, from point to END.
19460 ;; The function leaves point to END line.
19461 (lambda (ind end)
19462 (let ((min-i 1000) (end (copy-marker end)))
19463 ;; First determine the minimum indentation (MIN-I) of
19464 ;; the text.
19465 (save-excursion
19466 (catch 'exit
19467 (while (< (point) end)
19468 (let ((i (org-get-indentation)))
19469 (cond
19470 ;; Skip blank lines and inline tasks.
19471 ((looking-at "^[ \t]*$"))
19472 ((looking-at org-outline-regexp-bol))
19473 ;; We can't find less than 0 indentation.
19474 ((zerop i) (throw 'exit (setq min-i 0)))
19475 ((< i min-i) (setq min-i i))))
19476 (forward-line))))
19477 ;; Then indent each line so that a line indented to
19478 ;; MIN-I becomes indented to IND. Ignore blank lines
19479 ;; and inline tasks in the process.
19480 (let ((delta (- ind min-i)))
19481 (while (< (point) end)
19482 (unless (or (looking-at "^[ \t]*$")
19483 (looking-at org-outline-regexp-bol))
19484 (org-indent-line-to (+ (org-get-indentation) delta)))
19485 (forward-line)))))))
19486 (skip-blanks
19487 (function
19488 ;; Return beginning of first non-blank line, starting from
19489 ;; line at POS.
19490 (lambda (pos)
19491 (save-excursion
19492 (goto-char pos)
19493 (skip-chars-forward " \r\t\n")
19494 (point-at-bol)))))
19495 beg end)
19496 ;; Determine boundaries of changes.
19497 (if (org-region-active-p)
19498 (setq beg (funcall skip-blanks (region-beginning))
19499 end (copy-marker (region-end)))
19500 (setq beg (funcall skip-blanks (point-at-bol))
19501 end (copy-marker (point-at-eol))))
19502 ;; Depending on the starting line, choose an action on the text
19503 ;; between BEG and END.
19504 (org-with-limited-levels
19505 (save-excursion
19506 (goto-char beg)
19507 (cond
19508 ;; Case 1. Start at an item: de-itemize. Note that it only
19509 ;; happens when a region is active: `org-ctrl-c-minus'
19510 ;; would call `org-cycle-list-bullet' otherwise.
19511 ((org-at-item-p)
19512 (while (< (point) end)
19513 (when (org-at-item-p)
19514 (skip-chars-forward " \t")
19515 (delete-region (point) (match-end 0)))
19516 (forward-line)))
19517 ;; Case 2. Start at an heading: convert to items.
19518 ((org-at-heading-p)
19519 (let* ((bul (org-list-bullet-string "-"))
19520 (bul-len (length bul))
19521 ;; Indentation of the first heading. It should be
19522 ;; relative to the indentation of its parent, if any.
19523 (start-ind (save-excursion
19524 (cond
19525 ((not org-adapt-indentation) 0)
19526 ((not (outline-previous-heading)) 0)
19527 (t (length (match-string 0))))))
19528 ;; Level of first heading. Further headings will be
19529 ;; compared to it to determine hierarchy in the list.
19530 (ref-level (org-reduced-level (org-outline-level))))
19531 (while (< (point) end)
19532 (let* ((level (org-reduced-level (org-outline-level)))
19533 (delta (max 0 (- level ref-level))))
19534 ;; If current headline is less indented than the first
19535 ;; one, set it as reference, in order to preserve
19536 ;; subtrees.
19537 (when (< level ref-level) (setq ref-level level))
19538 (replace-match bul t t)
19539 (org-indent-line-to (+ start-ind (* delta bul-len)))
19540 ;; Ensure all text down to END (or SECTION-END) belongs
19541 ;; to the newly created item.
19542 (let ((section-end (save-excursion
19543 (or (outline-next-heading) (point)))))
19544 (forward-line)
19545 (funcall shift-text
19546 (+ start-ind (* (1+ delta) bul-len))
19547 (min end section-end)))))))
19548 ;; Case 3. Normal line with ARG: turn each non-item line into
19549 ;; an item.
19550 (arg
19551 (while (< (point) end)
19552 (unless (or (org-at-heading-p) (org-at-item-p))
19553 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19554 (replace-match
19555 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19556 (forward-line)))
19557 ;; Case 4. Normal line without ARG: make the first line of
19558 ;; region an item, and shift indentation of others
19559 ;; lines to set them as item's body.
19560 (t (let* ((bul (org-list-bullet-string "-"))
19561 (bul-len (length bul))
19562 (ref-ind (org-get-indentation)))
19563 (skip-chars-forward " \t")
19564 (insert bul)
19565 (forward-line)
19566 (while (< (point) end)
19567 ;; Ensure that lines less indented than first one
19568 ;; still get included in item body.
19569 (funcall shift-text
19570 (+ ref-ind bul-len)
19571 (min end (save-excursion (or (outline-next-heading)
19572 (point)))))
19573 (forward-line)))))))))
19575 (defun org-toggle-heading (&optional nstars)
19576 "Convert headings to normal text, or items or text to headings.
19577 If there is no active region, only the current line is considered.
19579 With a \\[universal-argument] prefix, convert the whole list at
19580 point into heading.
19582 In a region:
19584 - If the first non blank line is an headline, remove the stars
19585 from all headlines in the region.
19587 - If it is a normal line turn each and every normal line (i.e. not an
19588 heading or an item) in the region into a heading.
19590 - If it is a plain list item, turn all plain list items into headings.
19592 When converting a line into a heading, the number of stars is chosen
19593 such that the lines become children of the current entry. However,
19594 when a prefix argument is given, its value determines the number of
19595 stars to add."
19596 (interactive "P")
19597 (let ((skip-blanks
19598 (function
19599 ;; Return beginning of first non-blank line, starting from
19600 ;; line at POS.
19601 (lambda (pos)
19602 (save-excursion
19603 (goto-char pos)
19604 (while (org-at-comment-p) (forward-line))
19605 (skip-chars-forward " \r\t\n")
19606 (point-at-bol)))))
19607 beg end toggled)
19608 ;; Determine boundaries of changes. If a universal prefix has
19609 ;; been given, put the list in a region. If region ends at a bol,
19610 ;; do not consider the last line to be in the region.
19612 (when (and current-prefix-arg (org-at-item-p))
19613 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19614 (org-mark-element))
19616 (if (org-region-active-p)
19617 (setq beg (funcall skip-blanks (region-beginning))
19618 end (copy-marker (save-excursion
19619 (goto-char (region-end))
19620 (if (bolp) (point) (point-at-eol)))))
19621 (setq beg (funcall skip-blanks (point-at-bol))
19622 end (copy-marker (point-at-eol))))
19623 ;; Ensure inline tasks don't count as headings.
19624 (org-with-limited-levels
19625 (save-excursion
19626 (goto-char beg)
19627 (cond
19628 ;; Case 1. Started at an heading: de-star headings.
19629 ((org-at-heading-p)
19630 (while (< (point) end)
19631 (when (org-at-heading-p t)
19632 (looking-at org-outline-regexp) (replace-match "")
19633 (setq toggled t))
19634 (forward-line)))
19635 ;; Case 2. Started at an item: change items into headlines.
19636 ;; One star will be added by `org-list-to-subtree'.
19637 ((org-at-item-p)
19638 (let* ((stars (make-string
19639 (if nstars
19640 ;; subtract the star that will be added again by
19641 ;; `org-list-to-subtree'
19642 (1- (prefix-numeric-value current-prefix-arg))
19643 (or (org-current-level) 0))
19644 ?*))
19645 (add-stars
19646 (cond (nstars "") ; stars from prefix only
19647 ((equal stars "") "") ; before first heading
19648 (org-odd-levels-only "*") ; inside heading, odd
19649 (t "")))) ; inside heading, oddeven
19650 (while (< (point) end)
19651 (when (org-at-item-p)
19652 ;; Pay attention to cases when region ends before list.
19653 (let* ((struct (org-list-struct))
19654 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19655 (save-restriction
19656 (narrow-to-region (point) list-end)
19657 (insert
19658 (org-list-to-subtree
19659 (org-list-parse-list t)
19660 '(:istart (concat stars add-stars (funcall get-stars depth))
19661 :icount (concat stars add-stars (funcall get-stars depth)))))))
19662 (setq toggled t))
19663 (forward-line))))
19664 ;; Case 3. Started at normal text: make every line an heading,
19665 ;; skipping headlines and items.
19666 (t (let* ((stars (make-string
19667 (if nstars
19668 (prefix-numeric-value current-prefix-arg)
19669 (or (org-current-level) 0))
19670 ?*))
19671 (add-stars
19672 (cond (nstars "") ; stars from prefix only
19673 ((equal stars "") "*") ; before first heading
19674 (org-odd-levels-only "**") ; inside heading, odd
19675 (t "*"))) ; inside heading, oddeven
19676 (rpl (concat stars add-stars " ")))
19677 (while (< (point) end)
19678 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19679 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19680 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19681 (forward-line)))))))
19682 (unless toggled (message "Cannot toggle heading from here"))))
19684 (defun org-meta-return (&optional arg)
19685 "Insert a new heading or wrap a region in a table.
19686 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19687 See the individual commands for more information."
19688 (interactive "P")
19689 (cond
19690 ((run-hook-with-args-until-success 'org-metareturn-hook))
19691 ((or (org-at-drawer-p) (org-at-property-p))
19692 (newline-and-indent))
19693 ((org-at-table-p)
19694 (call-interactively 'org-table-wrap-region))
19695 (t (call-interactively 'org-insert-heading))))
19697 ;;; Menu entries
19699 ;; Define the Org-mode menus
19700 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19701 '("Tbl"
19702 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19703 ["Next Field" org-cycle (org-at-table-p)]
19704 ["Previous Field" org-shifttab (org-at-table-p)]
19705 ["Next Row" org-return (org-at-table-p)]
19706 "--"
19707 ["Blank Field" org-table-blank-field (org-at-table-p)]
19708 ["Edit Field" org-table-edit-field (org-at-table-p)]
19709 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19710 "--"
19711 ("Column"
19712 ["Move Column Left" org-metaleft (org-at-table-p)]
19713 ["Move Column Right" org-metaright (org-at-table-p)]
19714 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19715 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19716 ("Row"
19717 ["Move Row Up" org-metaup (org-at-table-p)]
19718 ["Move Row Down" org-metadown (org-at-table-p)]
19719 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19720 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19721 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19722 "--"
19723 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19724 ("Rectangle"
19725 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19726 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19727 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19728 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19729 "--"
19730 ("Calculate"
19731 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19732 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19733 ["Edit Formulas" org-edit-special (org-at-table-p)]
19734 "--"
19735 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19736 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19737 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19738 "--"
19739 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19740 "--"
19741 ["Sum Column/Rectangle" org-table-sum
19742 (or (org-at-table-p) (org-region-active-p))]
19743 ["Which Column?" org-table-current-column (org-at-table-p)])
19744 ["Debug Formulas"
19745 org-table-toggle-formula-debugger
19746 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19747 ["Show Col/Row Numbers"
19748 org-table-toggle-coordinate-overlays
19749 :style toggle
19750 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19751 "--"
19752 ["Create" org-table-create (and (not (org-at-table-p))
19753 org-enable-table-editor)]
19754 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19755 ["Import from File" org-table-import (not (org-at-table-p))]
19756 ["Export to File" org-table-export (org-at-table-p)]
19757 "--"
19758 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19760 (easy-menu-define org-org-menu org-mode-map "Org menu"
19761 '("Org"
19762 ("Show/Hide"
19763 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19764 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19765 ["Sparse Tree..." org-sparse-tree t]
19766 ["Reveal Context" org-reveal t]
19767 ["Show All" show-all t]
19768 "--"
19769 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19770 "--"
19771 ["New Heading" org-insert-heading t]
19772 ("Navigate Headings"
19773 ["Up" outline-up-heading t]
19774 ["Next" outline-next-visible-heading t]
19775 ["Previous" outline-previous-visible-heading t]
19776 ["Next Same Level" outline-forward-same-level t]
19777 ["Previous Same Level" outline-backward-same-level t]
19778 "--"
19779 ["Jump" org-goto t])
19780 ("Edit Structure"
19781 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
19782 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
19783 "--"
19784 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
19785 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
19786 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19787 "--"
19788 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19789 "--"
19790 ["Copy visible text" org-copy-visible t]
19791 "--"
19792 ["Promote Heading" org-metaleft (not (org-at-table-p))]
19793 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
19794 ["Demote Heading" org-metaright (not (org-at-table-p))]
19795 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
19796 "--"
19797 ["Sort Region/Children" org-sort (not (org-at-table-p))]
19798 "--"
19799 ["Convert to odd levels" org-convert-to-odd-levels t]
19800 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19801 ("Editing"
19802 ["Emphasis..." org-emphasize t]
19803 ["Edit Source Example" org-edit-special t]
19804 "--"
19805 ["Footnote new/jump" org-footnote-action t]
19806 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19807 ("Archive"
19808 ["Archive (default method)" org-archive-subtree-default t]
19809 "--"
19810 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
19811 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
19812 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
19814 "--"
19815 ("Hyperlinks"
19816 ["Store Link (Global)" org-store-link t]
19817 ["Find existing link to here" org-occur-link-in-agenda-files t]
19818 ["Insert Link" org-insert-link t]
19819 ["Follow Link" org-open-at-point t]
19820 "--"
19821 ["Next link" org-next-link t]
19822 ["Previous link" org-previous-link t]
19823 "--"
19824 ["Descriptive Links"
19825 org-toggle-link-display
19826 :style radio
19827 :selected org-descriptive-links
19829 ["Literal Links"
19830 org-toggle-link-display
19831 :style radio
19832 :selected (not org-descriptive-links)])
19833 "--"
19834 ("TODO Lists"
19835 ["TODO/DONE/-" org-todo t]
19836 ("Select keyword"
19837 ["Next keyword" org-shiftright (org-at-heading-p)]
19838 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19839 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19840 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19841 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19842 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19843 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19844 "--"
19845 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19846 :selected org-enforce-todo-dependencies :style toggle :active t]
19847 "Settings for tree at point"
19848 ["Do Children sequentially" org-toggle-ordered-property :style radio
19849 :selected (org-entry-get nil "ORDERED")
19850 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19851 ["Do Children parallel" org-toggle-ordered-property :style radio
19852 :selected (not (org-entry-get nil "ORDERED"))
19853 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19854 "--"
19855 ["Set Priority" org-priority t]
19856 ["Priority Up" org-shiftup t]
19857 ["Priority Down" org-shiftdown t]
19858 "--"
19859 ["Get news from all feeds" org-feed-update-all t]
19860 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19861 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19862 ("TAGS and Properties"
19863 ["Set Tags" org-set-tags-command t]
19864 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19865 "--"
19866 ["Set property" org-set-property t]
19867 ["Column view of properties" org-columns t]
19868 ["Insert Column View DBlock" org-insert-columns-dblock t])
19869 ("Dates and Scheduling"
19870 ["Timestamp" org-time-stamp t]
19871 ["Timestamp (inactive)" org-time-stamp-inactive t]
19872 ("Change Date"
19873 ["1 Day Later" org-shiftright t]
19874 ["1 Day Earlier" org-shiftleft t]
19875 ["1 ... Later" org-shiftup t]
19876 ["1 ... Earlier" org-shiftdown t])
19877 ["Compute Time Range" org-evaluate-time-range t]
19878 ["Schedule Item" org-schedule t]
19879 ["Deadline" org-deadline t]
19880 "--"
19881 ["Custom time format" org-toggle-time-stamp-overlays
19882 :style radio :selected org-display-custom-times]
19883 "--"
19884 ["Goto Calendar" org-goto-calendar t]
19885 ["Date from Calendar" org-date-from-calendar t]
19886 "--"
19887 ["Start/Restart Timer" org-timer-start t]
19888 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19889 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19890 ["Insert Timer String" org-timer t]
19891 ["Insert Timer Item" org-timer-item t])
19892 ("Logging work"
19893 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19894 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19895 ["Clock out" org-clock-out t]
19896 ["Clock cancel" org-clock-cancel t]
19897 "--"
19898 ["Mark as default task" org-clock-mark-default-task t]
19899 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19900 ["Goto running clock" org-clock-goto t]
19901 "--"
19902 ["Display times" org-clock-display t]
19903 ["Create clock table" org-clock-report t]
19904 "--"
19905 ["Record DONE time"
19906 (progn (setq org-log-done (not org-log-done))
19907 (message "Switching to %s will %s record a timestamp"
19908 (car org-done-keywords)
19909 (if org-log-done "automatically" "not")))
19910 :style toggle :selected org-log-done])
19911 "--"
19912 ["Agenda Command..." org-agenda t]
19913 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19914 ("File List for Agenda")
19915 ("Special views current file"
19916 ["TODO Tree" org-show-todo-tree t]
19917 ["Check Deadlines" org-check-deadlines t]
19918 ["Timeline" org-timeline t]
19919 ["Tags/Property tree" org-match-sparse-tree t])
19920 "--"
19921 ["Export/Publish..." org-export t]
19922 ("LaTeX"
19923 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19924 :selected org-cdlatex-mode]
19925 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19926 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19927 ["Modify math symbol" org-cdlatex-math-modify
19928 (org-inside-LaTeX-fragment-p)]
19929 ["Insert citation" org-reftex-citation t]
19930 "--"
19931 ["Template for BEAMER" (progn (require 'org-beamer)
19932 (org-insert-beamer-options-template)) t])
19933 "--"
19934 ("MobileOrg"
19935 ["Push Files and Views" org-mobile-push t]
19936 ["Get Captured and Flagged" org-mobile-pull t]
19937 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19938 "--"
19939 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19940 "--"
19941 ("Documentation"
19942 ["Show Version" org-version t]
19943 ["Info Documentation" org-info t])
19944 ("Customize"
19945 ["Browse Org Group" org-customize t]
19946 "--"
19947 ["Expand This Menu" org-create-customize-menu
19948 (fboundp 'customize-menu-create)])
19949 ["Send bug report" org-submit-bug-report t]
19950 "--"
19951 ("Refresh/Reload"
19952 ["Refresh setup current buffer" org-mode-restart t]
19953 ["Reload Org (after update)" org-reload t]
19954 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19957 (defun org-info (&optional node)
19958 "Read documentation for Org-mode in the info system.
19959 With optional NODE, go directly to that node."
19960 (interactive)
19961 (info (format "(org)%s" (or node ""))))
19963 ;;;###autoload
19964 (defun org-submit-bug-report ()
19965 "Submit a bug report on Org-mode via mail.
19967 Don't hesitate to report any problems or inaccurate documentation.
19969 If you don't have setup sending mail from (X)Emacs, please copy the
19970 output buffer into your mail program, as it gives us important
19971 information about your Org-mode version and configuration."
19972 (interactive)
19973 (require 'reporter)
19974 (org-load-modules-maybe)
19975 (org-require-autoloaded-modules)
19976 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19977 (reporter-submit-bug-report
19978 "emacs-orgmode@gnu.org"
19979 (org-version nil 'full)
19980 (let (list)
19981 (save-window-excursion
19982 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19983 (delete-other-windows)
19984 (erase-buffer)
19985 (insert "You are about to submit a bug report to the Org-mode mailing list.
19987 We would like to add your full Org-mode and Outline configuration to the
19988 bug report. This greatly simplifies the work of the maintainer and
19989 other experts on the mailing list.
19991 HOWEVER, some variables you have customized may contain private
19992 information. The names of customers, colleagues, or friends, might
19993 appear in the form of file names, tags, todo states, or search strings.
19994 If you answer yes to the prompt, you might want to check and remove
19995 such private information before sending the email.")
19996 (add-text-properties (point-min) (point-max) '(face org-warning))
19997 (when (yes-or-no-p "Include your Org-mode configuration ")
19998 (mapatoms
19999 (lambda (v)
20000 (and (boundp v)
20001 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20002 (or (and (symbol-value v)
20003 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20004 (and
20005 (get v 'custom-type) (get v 'standard-value)
20006 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20007 (push v list)))))
20008 (kill-buffer (get-buffer "*Warn about privacy*"))
20009 list))
20010 nil nil
20011 "Remember to cover the basics, that is, what you expected to happen and
20012 what in fact did happen. You don't know how to make a good report? See
20014 http://orgmode.org/manual/Feedback.html#Feedback
20016 Your bug report will be posted to the Org-mode mailing list.
20017 ------------------------------------------------------------------------")
20018 (save-excursion
20019 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20020 (replace-match "\\1Bug: \\3 [\\2]")))))
20023 (defun org-install-agenda-files-menu ()
20024 (let ((bl (buffer-list)))
20025 (save-excursion
20026 (while bl
20027 (set-buffer (pop bl))
20028 (if (derived-mode-p 'org-mode) (setq bl nil)))
20029 (when (derived-mode-p 'org-mode)
20030 (easy-menu-change
20031 '("Org") "File List for Agenda"
20032 (append
20033 (list
20034 ["Edit File List" (org-edit-agenda-file-list) t]
20035 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20036 ["Remove Current File from List" org-remove-file t]
20037 ["Cycle through agenda files" org-cycle-agenda-files t]
20038 ["Occur in all agenda files" org-occur-in-agenda-files t]
20039 "--")
20040 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20042 ;;;; Documentation
20044 ;;;###autoload
20045 (defun org-require-autoloaded-modules ()
20046 (interactive)
20047 (mapc 'require
20048 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20049 org-docbook org-exp org-html org-icalendar
20050 org-id org-latex
20051 org-publish org-remember org-table
20052 org-timer org-xoxo)))
20054 ;;;###autoload
20055 (defun org-reload (&optional uncompiled)
20056 "Reload all org lisp files.
20057 With prefix arg UNCOMPILED, load the uncompiled versions."
20058 (interactive "P")
20059 (require 'find-func)
20060 (let* ((file-re "^org\\(-.*\\)?\\.el")
20061 (dir-org (file-name-directory (org-find-library-dir "org")))
20062 (dir-org-contrib (ignore-errors
20063 (file-name-directory
20064 (org-find-library-dir "org-contribdir"))))
20065 (babel-files
20066 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
20067 (append (list nil "comint" "eval" "exp" "keys"
20068 "lob" "ref" "table" "tangle")
20069 (delq nil
20070 (mapcar
20071 (lambda (lang)
20072 (when (cdr lang) (symbol-name (car lang))))
20073 org-babel-load-languages)))))
20074 (files
20075 (append babel-files
20076 (and dir-org-contrib
20077 (directory-files dir-org-contrib t file-re))
20078 (directory-files dir-org t file-re)))
20079 (remove-re (concat (if (featurep 'xemacs)
20080 "org-colview" "org-colview-xemacs")
20081 "\\'")))
20082 (setq files (mapcar 'file-name-sans-extension files))
20083 (setq files (mapcar
20084 (lambda (x) (if (string-match remove-re x) nil x))
20085 files))
20086 (setq files (delq nil files))
20087 (mapc
20088 (lambda (f)
20089 (when (featurep (intern (file-name-nondirectory f)))
20090 (if (and (not uncompiled)
20091 (file-exists-p (concat f ".elc")))
20092 (load (concat f ".elc") nil nil 'nosuffix)
20093 (load (concat f ".el") nil nil 'nosuffix))))
20094 files)
20095 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20096 (org-version nil 'full 'message))
20098 ;;;###autoload
20099 (defun org-customize ()
20100 "Call the customize function with org as argument."
20101 (interactive)
20102 (org-load-modules-maybe)
20103 (org-require-autoloaded-modules)
20104 (customize-browse 'org))
20106 (defun org-create-customize-menu ()
20107 "Create a full customization menu for Org-mode, insert it into the menu."
20108 (interactive)
20109 (org-load-modules-maybe)
20110 (org-require-autoloaded-modules)
20111 (if (fboundp 'customize-menu-create)
20112 (progn
20113 (easy-menu-change
20114 '("Org") "Customize"
20115 `(["Browse Org group" org-customize t]
20116 "--"
20117 ,(customize-menu-create 'org)
20118 ["Set" Custom-set t]
20119 ["Save" Custom-save t]
20120 ["Reset to Current" Custom-reset-current t]
20121 ["Reset to Saved" Custom-reset-saved t]
20122 ["Reset to Standard Settings" Custom-reset-standard t]))
20123 (message "\"Org\"-menu now contains full customization menu"))
20124 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20126 ;;;; Miscellaneous stuff
20128 ;;; Generally useful functions
20130 (defun org-get-at-bol (property)
20131 "Get text property PROPERTY at beginning of line."
20132 (get-text-property (point-at-bol) property))
20134 (defun org-find-text-property-in-string (prop s)
20135 "Return the first non-nil value of property PROP in string S."
20136 (or (get-text-property 0 prop s)
20137 (get-text-property (or (next-single-property-change 0 prop s) 0)
20138 prop s)))
20140 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20141 "Display the given MESSAGE as a warning."
20142 (if (fboundp 'display-warning)
20143 (display-warning 'org message
20144 (if (featurep 'xemacs) 'warning :warning))
20145 (let ((buf (get-buffer-create "*Org warnings*")))
20146 (with-current-buffer buf
20147 (goto-char (point-max))
20148 (insert "Warning (Org): " message)
20149 (unless (bolp)
20150 (newline)))
20151 (display-buffer buf)
20152 (sit-for 0))))
20154 (defun org-eval (form)
20155 "Eval FORM and return result."
20156 (condition-case error
20157 (eval form)
20158 (error (format "%%![Error: %s]" error))))
20160 (defun org-in-clocktable-p ()
20161 "Check if the cursor is in a clocktable."
20162 (let ((pos (point)) start)
20163 (save-excursion
20164 (end-of-line 1)
20165 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20166 (setq start (match-beginning 0))
20167 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20168 (>= (match-end 0) pos)
20169 start))))
20171 (defun org-in-commented-line ()
20172 "Is point in a line starting with `#'?"
20173 (equal (char-after (point-at-bol)) ?#))
20175 (defun org-in-indented-comment-line ()
20176 "Is point in a line starting with `#' after some white space?"
20177 (save-excursion
20178 (save-match-data
20179 (goto-char (point-at-bol))
20180 (looking-at "[ \t]*#"))))
20182 (defun org-in-verbatim-emphasis ()
20183 (save-match-data
20184 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20186 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20187 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20188 (if (and marker (marker-buffer marker)
20189 (buffer-live-p (marker-buffer marker)))
20190 (progn
20191 (org-pop-to-buffer-same-window (marker-buffer marker))
20192 (if (or (> marker (point-max)) (< marker (point-min)))
20193 (widen))
20194 (goto-char marker)
20195 (org-show-context 'org-goto))
20196 (if bookmark
20197 (bookmark-jump bookmark)
20198 (error "Cannot find location"))))
20200 (defun org-quote-csv-field (s)
20201 "Quote field for inclusion in CSV material."
20202 (if (string-match "[\",]" s)
20203 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20206 (defun org-force-self-insert (N)
20207 "Needed to enforce self-insert under remapping."
20208 (interactive "p")
20209 (self-insert-command N))
20211 (defun org-string-width (s)
20212 "Compute width of string, ignoring invisible characters.
20213 This ignores character with invisibility property `org-link', and also
20214 characters with property `org-cwidth', because these will become invisible
20215 upon the next fontification round."
20216 (let (b l)
20217 (when (or (eq t buffer-invisibility-spec)
20218 (assq 'org-link buffer-invisibility-spec))
20219 (while (setq b (text-property-any 0 (length s)
20220 'invisible 'org-link s))
20221 (setq s (concat (substring s 0 b)
20222 (substring s (or (next-single-property-change
20223 b 'invisible s) (length s)))))))
20224 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20225 (setq s (concat (substring s 0 b)
20226 (substring s (or (next-single-property-change
20227 b 'org-cwidth s) (length s))))))
20228 (setq l (string-width s) b -1)
20229 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20230 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20233 (defun org-shorten-string (s maxlength)
20234 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20235 If the string is shorter or has length MAXLENGTH, just return the
20236 original string. If it is longer, the functions finds a space in the
20237 string, breaks this string off at that locations and adds three dots
20238 as ellipsis. Including the ellipsis, the string will not be longer
20239 than MAXLENGTH. If finding a good breaking point in the string does
20240 not work, the string is just chopped off in the middle of a word
20241 if necessary."
20242 (if (<= (length s) maxlength)
20244 (let* ((n (max (- maxlength 4) 1))
20245 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20246 (if (string-match re s)
20247 (concat (match-string 1 s) "...")
20248 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20250 (defun org-get-indentation (&optional line)
20251 "Get the indentation of the current line, interpreting tabs.
20252 When LINE is given, assume it represents a line and compute its indentation."
20253 (if line
20254 (if (string-match "^ *" (org-remove-tabs line))
20255 (match-end 0))
20256 (save-excursion
20257 (beginning-of-line 1)
20258 (skip-chars-forward " \t")
20259 (current-column))))
20261 (defun org-get-string-indentation (s)
20262 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20263 (let ((n -1) (i 0) (w tab-width) c)
20264 (catch 'exit
20265 (while (< (setq n (1+ n)) (length s))
20266 (setq c (aref s n))
20267 (cond ((= c ?\ ) (setq i (1+ i)))
20268 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20269 (t (throw 'exit t)))))
20272 (defun org-remove-tabs (s &optional width)
20273 "Replace tabulators in S with spaces.
20274 Assumes that s is a single line, starting in column 0."
20275 (setq width (or width tab-width))
20276 (while (string-match "\t" s)
20277 (setq s (replace-match
20278 (make-string
20279 (- (* width (/ (+ (match-beginning 0) width) width))
20280 (match-beginning 0)) ?\ )
20281 t t s)))
20284 (defun org-fix-indentation (line ind)
20285 "Fix indentation in LINE.
20286 IND is a cons cell with target and minimum indentation.
20287 If the current indentation in LINE is smaller than the minimum,
20288 leave it alone. If it is larger than ind, set it to the target."
20289 (let* ((l (org-remove-tabs line))
20290 (i (org-get-indentation l))
20291 (i1 (car ind)) (i2 (cdr ind)))
20292 (if (>= i i2) (setq l (substring line i2)))
20293 (if (> i1 0)
20294 (concat (make-string i1 ?\ ) l)
20295 l)))
20297 (defun org-remove-indentation (code &optional n)
20298 "Remove the maximum common indentation from the lines in CODE.
20299 N may optionally be the number of spaces to remove."
20300 (with-temp-buffer
20301 (insert code)
20302 (org-do-remove-indentation n)
20303 (buffer-string)))
20305 (defun org-do-remove-indentation (&optional n)
20306 "Remove the maximum common indentation from the buffer."
20307 (untabify (point-min) (point-max))
20308 (let ((min 10000) re)
20309 (if n
20310 (setq min n)
20311 (goto-char (point-min))
20312 (while (re-search-forward "^ *[^ \n]" nil t)
20313 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20314 (unless (or (= min 0) (= min 10000))
20315 (setq re (format "^ \\{%d\\}" min))
20316 (goto-char (point-min))
20317 (while (re-search-forward re nil t)
20318 (replace-match "")
20319 (end-of-line 1))
20320 min)))
20322 (defun org-fill-template (template alist)
20323 "Find each %key of ALIST in TEMPLATE and replace it."
20324 (let ((case-fold-search nil)
20325 entry key value)
20326 (setq alist (sort (copy-sequence alist)
20327 (lambda (a b) (< (length (car a)) (length (car b))))))
20328 (while (setq entry (pop alist))
20329 (setq template
20330 (replace-regexp-in-string
20331 (concat "%" (regexp-quote (car entry)))
20332 (or (cdr entry) "") template t t)))
20333 template))
20335 (defun org-base-buffer (buffer)
20336 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20337 (if (not buffer)
20338 buffer
20339 (or (buffer-base-buffer buffer)
20340 buffer)))
20342 (defun org-trim (s)
20343 "Remove whitespace at beginning and end of string."
20344 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20345 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20348 (defun org-wrap (string &optional width lines)
20349 "Wrap string to either a number of lines, or a width in characters.
20350 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20351 that costs. If there is a word longer than WIDTH, the text is actually
20352 wrapped to the length of that word.
20353 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20354 many lines, whatever width that takes.
20355 The return value is a list of lines, without newlines at the end."
20356 (let* ((words (org-split-string string "[ \t\n]+"))
20357 (maxword (apply 'max (mapcar 'org-string-width words)))
20358 w ll)
20359 (cond (width
20360 (org-do-wrap words (max maxword width)))
20361 (lines
20362 (setq w maxword)
20363 (setq ll (org-do-wrap words maxword))
20364 (if (<= (length ll) lines)
20366 (setq ll words)
20367 (while (> (length ll) lines)
20368 (setq w (1+ w))
20369 (setq ll (org-do-wrap words w)))
20370 ll))
20371 (t (error "Cannot wrap this")))))
20373 (defun org-do-wrap (words width)
20374 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20375 (let (lines line)
20376 (while words
20377 (setq line (pop words))
20378 (while (and words (< (+ (length line) (length (car words))) width))
20379 (setq line (concat line " " (pop words))))
20380 (setq lines (push line lines)))
20381 (nreverse lines)))
20383 (defun org-split-string (string &optional separators)
20384 "Splits STRING into substrings at SEPARATORS.
20385 No empty strings are returned if there are matches at the beginning
20386 and end of string."
20387 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20388 (start 0)
20389 notfirst
20390 (list nil))
20391 (while (and (string-match rexp string
20392 (if (and notfirst
20393 (= start (match-beginning 0))
20394 (< start (length string)))
20395 (1+ start) start))
20396 (< (match-beginning 0) (length string)))
20397 (setq notfirst t)
20398 (or (eq (match-beginning 0) 0)
20399 (and (eq (match-beginning 0) (match-end 0))
20400 (eq (match-beginning 0) start))
20401 (setq list
20402 (cons (substring string start (match-beginning 0))
20403 list)))
20404 (setq start (match-end 0)))
20405 (or (eq start (length string))
20406 (setq list
20407 (cons (substring string start)
20408 list)))
20409 (nreverse list)))
20411 (defun org-quote-vert (s)
20412 "Replace \"|\" with \"\\vert\"."
20413 (while (string-match "|" s)
20414 (setq s (replace-match "\\vert" t t s)))
20417 (defun org-uuidgen-p (s)
20418 "Is S an ID created by UUIDGEN?"
20419 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20421 (defun org-in-src-block-p nil
20422 "Whether point is in a code source block."
20423 (let (ov)
20424 (when (setq ov (overlays-at (point)))
20425 (memq 'org-block-background
20426 (overlay-properties
20427 (car ov))))))
20429 (defun org-context ()
20430 "Return a list of contexts of the current cursor position.
20431 If several contexts apply, all are returned.
20432 Each context entry is a list with a symbol naming the context, and
20433 two positions indicating start and end of the context. Possible
20434 contexts are:
20436 :headline anywhere in a headline
20437 :headline-stars on the leading stars in a headline
20438 :todo-keyword on a TODO keyword (including DONE) in a headline
20439 :tags on the TAGS in a headline
20440 :priority on the priority cookie in a headline
20441 :item on the first line of a plain list item
20442 :item-bullet on the bullet/number of a plain list item
20443 :checkbox on the checkbox in a plain list item
20444 :table in an org-mode table
20445 :table-special on a special filed in a table
20446 :table-table in a table.el table
20447 :clocktable in a clocktable
20448 :src-block in a source block
20449 :link on a hyperlink
20450 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20451 :target on a <<target>>
20452 :radio-target on a <<<radio-target>>>
20453 :latex-fragment on a LaTeX fragment
20454 :latex-preview on a LaTeX fragment with overlaid preview image
20456 This function expects the position to be visible because it uses font-lock
20457 faces as a help to recognize the following contexts: :table-special, :link,
20458 and :keyword."
20459 (let* ((f (get-text-property (point) 'face))
20460 (faces (if (listp f) f (list f)))
20461 (case-fold-search t)
20462 (p (point)) clist o)
20463 ;; First the large context
20464 (cond
20465 ((org-at-heading-p t)
20466 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20467 (when (progn
20468 (beginning-of-line 1)
20469 (looking-at org-todo-line-tags-regexp))
20470 (push (org-point-in-group p 1 :headline-stars) clist)
20471 (push (org-point-in-group p 2 :todo-keyword) clist)
20472 (push (org-point-in-group p 4 :tags) clist))
20473 (goto-char p)
20474 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20475 (if (looking-at "\\[#[A-Z0-9]\\]")
20476 (push (org-point-in-group p 0 :priority) clist)))
20478 ((org-at-item-p)
20479 (push (org-point-in-group p 2 :item-bullet) clist)
20480 (push (list :item (point-at-bol)
20481 (save-excursion (org-end-of-item) (point)))
20482 clist)
20483 (and (org-at-item-checkbox-p)
20484 (push (org-point-in-group p 0 :checkbox) clist)))
20486 ((org-at-table-p)
20487 (push (list :table (org-table-begin) (org-table-end)) clist)
20488 (if (memq 'org-formula faces)
20489 (push (list :table-special
20490 (previous-single-property-change p 'face)
20491 (next-single-property-change p 'face)) clist)))
20492 ((org-at-table-p 'any)
20493 (push (list :table-table) clist)))
20494 (goto-char p)
20496 (let ((case-fold-search t))
20497 ;; New the "medium" contexts: clocktables, source blocks
20498 (cond ((org-in-clocktable-p)
20499 (push (list :clocktable
20500 (and (or (looking-at "#\\+BEGIN: clocktable")
20501 (search-backward "#+BEGIN: clocktable" nil t))
20502 (match-beginning 0))
20503 (and (re-search-forward "#\\+END:?" nil t)
20504 (match-end 0))) clist))
20505 ((org-in-src-block-p)
20506 (push (list :src-block
20507 (and (or (looking-at "#\\+BEGIN_SRC")
20508 (search-backward "#+BEGIN_SRC" nil t))
20509 (match-beginning 0))
20510 (and (search-forward "#+END_SRC" nil t)
20511 (match-beginning 0))) clist))))
20512 (goto-char p)
20514 ;; Now the small context
20515 (cond
20516 ((org-at-timestamp-p)
20517 (push (org-point-in-group p 0 :timestamp) clist))
20518 ((memq 'org-link faces)
20519 (push (list :link
20520 (previous-single-property-change p 'face)
20521 (next-single-property-change p 'face)) clist))
20522 ((memq 'org-special-keyword faces)
20523 (push (list :keyword
20524 (previous-single-property-change p 'face)
20525 (next-single-property-change p 'face)) clist))
20526 ((org-at-target-p)
20527 (push (org-point-in-group p 0 :target) clist)
20528 (goto-char (1- (match-beginning 0)))
20529 (if (looking-at org-radio-target-regexp)
20530 (push (org-point-in-group p 0 :radio-target) clist))
20531 (goto-char p))
20532 ((setq o (car (delq nil
20533 (mapcar
20534 (lambda (x)
20535 (if (memq x org-latex-fragment-image-overlays) x))
20536 (overlays-at (point))))))
20537 (push (list :latex-fragment
20538 (overlay-start o) (overlay-end o)) clist)
20539 (push (list :latex-preview
20540 (overlay-start o) (overlay-end o)) clist))
20541 ((org-inside-LaTeX-fragment-p)
20542 ;; FIXME: positions wrong.
20543 (push (list :latex-fragment (point) (point)) clist)))
20545 (setq clist (nreverse (delq nil clist)))
20546 clist))
20548 ;; FIXME: Compare with at-regexp-p Do we need both?
20549 (defun org-in-regexp (re &optional nlines visually)
20550 "Check if point is inside a match of regexp.
20551 Normally only the current line is checked, but you can include NLINES extra
20552 lines both before and after point into the search.
20553 If VISUALLY is set, require that the cursor is not after the match but
20554 really on, so that the block visually is on the match."
20555 (catch 'exit
20556 (let ((pos (point))
20557 (eol (point-at-eol (+ 1 (or nlines 0))))
20558 (inc (if visually 1 0)))
20559 (save-excursion
20560 (beginning-of-line (- 1 (or nlines 0)))
20561 (while (re-search-forward re eol t)
20562 (if (and (<= (match-beginning 0) pos)
20563 (>= (+ inc (match-end 0)) pos))
20564 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20566 (defun org-at-regexp-p (regexp)
20567 "Is point inside a match of REGEXP in the current line?"
20568 (catch 'exit
20569 (save-excursion
20570 (let ((pos (point)) (end (point-at-eol)))
20571 (beginning-of-line 1)
20572 (while (re-search-forward regexp end t)
20573 (if (and (<= (match-beginning 0) pos)
20574 (>= (match-end 0) pos))
20575 (throw 'exit t)))
20576 nil))))
20578 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20579 "Non-nil when point is between matches of START-RE and END-RE.
20581 Also return a non-nil value when point is on one of the matches.
20583 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20584 buffer positions. Default values are the positions of headlines
20585 surrounding the point.
20587 The functions returns a cons cell whose car (resp. cdr) is the
20588 position before START-RE (resp. after END-RE)."
20589 (save-match-data
20590 (let ((pos (point))
20591 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20592 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20593 beg end)
20594 (save-excursion
20595 ;; Point is on a block when on START-RE or if START-RE can be
20596 ;; found before it...
20597 (and (or (org-at-regexp-p start-re)
20598 (re-search-backward start-re limit-up t))
20599 (setq beg (match-beginning 0))
20600 ;; ... and END-RE after it...
20601 (goto-char (match-end 0))
20602 (re-search-forward end-re limit-down t)
20603 (> (setq end (match-end 0)) pos)
20604 ;; ... without another START-RE in-between.
20605 (goto-char (match-beginning 0))
20606 (not (re-search-backward start-re (1+ beg) t))
20607 ;; Return value.
20608 (cons beg end))))))
20610 (defun org-in-block-p (names)
20611 "Non-nil when point belongs to a block whose name belongs to NAMES.
20613 NAMES is a list of strings containing names of blocks.
20615 Return first block name matched, or nil. Beware that in case of
20616 nested blocks, the returned name may not belong to the closest
20617 block from point."
20618 (save-match-data
20619 (catch 'exit
20620 (let ((case-fold-search t)
20621 (lim-up (save-excursion (outline-previous-heading)))
20622 (lim-down (save-excursion (outline-next-heading))))
20623 (mapc (lambda (name)
20624 (let ((n (regexp-quote name)))
20625 (when (org-between-regexps-p
20626 (concat "^[ \t]*#\\+begin_" n)
20627 (concat "^[ \t]*#\\+end_" n)
20628 lim-up lim-down)
20629 (throw 'exit n))))
20630 names))
20631 nil)))
20633 (defun org-occur-in-agenda-files (regexp &optional nlines)
20634 "Call `multi-occur' with buffers for all agenda files."
20635 (interactive "sOrg-files matching: \np")
20636 (let* ((files (org-agenda-files))
20637 (tnames (mapcar 'file-truename files))
20638 (extra org-agenda-text-search-extra-files)
20640 (when (eq (car extra) 'agenda-archives)
20641 (setq extra (cdr extra))
20642 (setq files (org-add-archive-files files)))
20643 (while (setq f (pop extra))
20644 (unless (member (file-truename f) tnames)
20645 (add-to-list 'files f 'append)
20646 (add-to-list 'tnames (file-truename f) 'append)))
20647 (multi-occur
20648 (mapcar (lambda (x)
20649 (with-current-buffer
20650 (or (get-file-buffer x) (find-file-noselect x))
20651 (widen)
20652 (current-buffer)))
20653 files)
20654 regexp)))
20656 (if (boundp 'occur-mode-find-occurrence-hook)
20657 ;; Emacs 23
20658 (add-hook 'occur-mode-find-occurrence-hook
20659 (lambda ()
20660 (when (derived-mode-p 'org-mode)
20661 (org-reveal))))
20662 ;; Emacs 22
20663 (defadvice occur-mode-goto-occurrence
20664 (after org-occur-reveal activate)
20665 (and (derived-mode-p 'org-mode) (org-reveal)))
20666 (defadvice occur-mode-goto-occurrence-other-window
20667 (after org-occur-reveal activate)
20668 (and (derived-mode-p 'org-mode) (org-reveal)))
20669 (defadvice occur-mode-display-occurrence
20670 (after org-occur-reveal activate)
20671 (when (derived-mode-p 'org-mode)
20672 (let ((pos (occur-mode-find-occurrence)))
20673 (with-current-buffer (marker-buffer pos)
20674 (save-excursion
20675 (goto-char pos)
20676 (org-reveal)))))))
20678 (defun org-occur-link-in-agenda-files ()
20679 "Create a link and search for it in the agendas.
20680 The link is not stored in `org-stored-links', it is just created
20681 for the search purpose."
20682 (interactive)
20683 (let ((link (condition-case nil
20684 (org-store-link nil)
20685 (error "Unable to create a link to here"))))
20686 (org-occur-in-agenda-files (regexp-quote link))))
20688 (defun org-uniquify (list)
20689 "Remove duplicate elements from LIST."
20690 (let (res)
20691 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20692 res))
20694 (defun org-delete-all (elts list)
20695 "Remove all elements in ELTS from LIST."
20696 (while elts
20697 (setq list (delete (pop elts) list)))
20698 list)
20700 (defun org-count (cl-item cl-seq)
20701 "Count the number of occurrences of ITEM in SEQ.
20702 Taken from `count' in cl-seq.el with all keyword arguments removed."
20703 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20704 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20705 (while (< cl-start cl-end)
20706 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20707 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20708 (setq cl-start (1+ cl-start)))
20709 cl-count))
20711 (defun org-remove-if (predicate seq)
20712 "Remove everything from SEQ that fulfills PREDICATE."
20713 (let (res e)
20714 (while seq
20715 (setq e (pop seq))
20716 (if (not (funcall predicate e)) (push e res)))
20717 (nreverse res)))
20719 (defun org-remove-if-not (predicate seq)
20720 "Remove everything from SEQ that does not fulfill PREDICATE."
20721 (let (res e)
20722 (while seq
20723 (setq e (pop seq))
20724 (if (funcall predicate e) (push e res)))
20725 (nreverse res)))
20727 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20728 "Reduce two-argument FUNCTION across SEQ.
20729 Taken from `reduce' in cl-seq.el with all keyword arguments but
20730 \":initial-value\" removed."
20731 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20732 (cadr (memq :initial-value cl-keys)))
20733 (cl-seq (pop cl-seq))
20734 (t (funcall cl-func)))))
20735 (while cl-seq
20736 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20737 cl-accum))
20739 (defun org-back-over-empty-lines ()
20740 "Move backwards over whitespace, to the beginning of the first empty line.
20741 Returns the number of empty lines passed."
20742 (let ((pos (point)))
20743 (if (cdr (assoc 'heading org-blank-before-new-entry))
20744 (skip-chars-backward " \t\n\r")
20745 (unless (eobp)
20746 (forward-line -1)))
20747 (beginning-of-line 2)
20748 (goto-char (min (point) pos))
20749 (count-lines (point) pos)))
20751 (defun org-skip-whitespace ()
20752 (skip-chars-forward " \t\n\r"))
20754 (defun org-point-in-group (point group &optional context)
20755 "Check if POINT is in match-group GROUP.
20756 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20757 match. If the match group does not exist or point is not inside it,
20758 return nil."
20759 (and (match-beginning group)
20760 (>= point (match-beginning group))
20761 (<= point (match-end group))
20762 (if context
20763 (list context (match-beginning group) (match-end group))
20764 t)))
20766 (defun org-switch-to-buffer-other-window (&rest args)
20767 "Switch to buffer in a second window on the current frame.
20768 In particular, do not allow pop-up frames.
20769 Returns the newly created buffer."
20770 (let (pop-up-frames special-display-buffer-names special-display-regexps
20771 special-display-function)
20772 (apply 'switch-to-buffer-other-window args)))
20774 (defun org-combine-plists (&rest plists)
20775 "Create a single property list from all plists in PLISTS.
20776 The process starts by copying the first list, and then setting properties
20777 from the other lists. Settings in the last list are the most significant
20778 ones and overrule settings in the other lists."
20779 (let ((rtn (copy-sequence (pop plists)))
20780 p v ls)
20781 (while plists
20782 (setq ls (pop plists))
20783 (while ls
20784 (setq p (pop ls) v (pop ls))
20785 (setq rtn (plist-put rtn p v))))
20786 rtn))
20788 (defun org-replace-escapes (string table)
20789 "Replace %-escapes in STRING with values in TABLE.
20790 TABLE is an association list with keys like \"%a\" and string values.
20791 The sequences in STRING may contain normal field width and padding information,
20792 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20793 so values can contain further %-escapes if they are define later in TABLE."
20794 (let ((tbl (copy-alist table))
20795 (case-fold-search nil)
20796 (pchg 0)
20797 e re rpl)
20798 (while (setq e (pop tbl))
20799 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20800 (when (and (cdr e) (string-match re (cdr e)))
20801 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20802 (safe "SREF"))
20803 (add-text-properties 0 3 (list 'sref sref) safe)
20804 (setcdr e (replace-match safe t t (cdr e)))))
20805 (while (string-match re string)
20806 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20807 (cdr e)))
20808 (setq string (replace-match rpl t t string))))
20809 (while (setq pchg (next-property-change pchg string))
20810 (let ((sref (get-text-property pchg 'sref string)))
20811 (when (and sref (string-match "SREF" string pchg))
20812 (setq string (replace-match sref t t string)))))
20813 string))
20815 (defun org-sublist (list start end)
20816 "Return a section of LIST, from START to END.
20817 Counting starts at 1."
20818 (let (rtn (c start))
20819 (setq list (nthcdr (1- start) list))
20820 (while (and list (<= c end))
20821 (push (pop list) rtn)
20822 (setq c (1+ c)))
20823 (nreverse rtn)))
20825 (defun org-find-base-buffer-visiting (file)
20826 "Like `find-buffer-visiting' but always return the base buffer and
20827 not an indirect buffer."
20828 (let ((buf (or (get-file-buffer file)
20829 (find-buffer-visiting file))))
20830 (if buf
20831 (or (buffer-base-buffer buf) buf)
20832 nil)))
20834 (defun org-image-file-name-regexp (&optional extensions)
20835 "Return regexp matching the file names of images.
20836 If EXTENSIONS is given, only match these."
20837 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20838 (image-file-name-regexp)
20839 (let ((image-file-name-extensions
20840 (or extensions
20841 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20842 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20843 (concat "\\."
20844 (regexp-opt (nconc (mapcar 'upcase
20845 image-file-name-extensions)
20846 image-file-name-extensions)
20848 "\\'"))))
20850 (defun org-file-image-p (file &optional extensions)
20851 "Return non-nil if FILE is an image."
20852 (save-match-data
20853 (string-match (org-image-file-name-regexp extensions) file)))
20855 (defun org-get-cursor-date ()
20856 "Return the date at cursor in as a time.
20857 This works in the calendar and in the agenda, anywhere else it just
20858 returns the current time."
20859 (let (date day defd)
20860 (cond
20861 ((eq major-mode 'calendar-mode)
20862 (setq date (calendar-cursor-to-date)
20863 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20864 ((eq major-mode 'org-agenda-mode)
20865 (setq day (get-text-property (point) 'day))
20866 (if day
20867 (setq date (calendar-gregorian-from-absolute day)
20868 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20869 (nth 2 date))))))
20870 (or defd (current-time))))
20872 (defvar org-agenda-action-marker (make-marker)
20873 "Marker pointing to the entry for the next agenda action.")
20875 (defun org-mark-entry-for-agenda-action ()
20876 "Mark the current entry as target of an agenda action.
20877 Agenda actions are actions executed from the agenda with the key `k',
20878 which make use of the date at the cursor."
20879 (interactive)
20880 (move-marker org-agenda-action-marker
20881 (save-excursion (org-back-to-heading t) (point))
20882 (current-buffer))
20883 (message
20884 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20886 (defun org-mark-subtree (&optional up)
20887 "Mark the current subtree.
20888 This puts point at the start of the current subtree, and mark at
20889 the end. If a numeric prefix UP is given, move up into the
20890 hierarchy of headlines by UP levels before marking the subtree."
20891 (interactive "P")
20892 (org-with-limited-levels
20893 (cond ((org-at-heading-p) (beginning-of-line))
20894 ((org-before-first-heading-p) (error "Not in a subtree"))
20895 (t (outline-previous-visible-heading 1))))
20896 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20897 (if (org-called-interactively-p 'any)
20898 (call-interactively 'org-mark-element)
20899 (org-mark-element)))
20902 ;;; Macros
20904 ;; Macros are expanded with `org-macro-replace-all', which relies
20905 ;; internally on `org-macro-expand'.
20907 ;; Templates for expansion are stored in the buffer-local variable
20908 ;; `org-macro-templates'. This variable is updated by
20909 ;; `org-macro-initialize-templates'.
20912 (defvar org-macro-templates nil
20913 "Alist containing all macro templates in current buffer.
20914 Associations are in the shape of (NAME . TEMPLATE) where NAME
20915 stands for macro's name and template for its replacement value,
20916 both as strings. This is an internal variable. Do not set it
20917 directly, use instead:
20919 #+MACRO: name template")
20920 (make-variable-buffer-local 'org-macro-templates)
20922 (defun org-macro-expand (macro)
20923 "Return expanded MACRO, as a string.
20924 MACRO is an object, obtained, for example, with
20925 `org-element-context'. Return nil if no template was found."
20926 (let ((template
20927 (cdr (assoc-string (org-element-property :key macro)
20928 org-macro-templates
20929 ;; Macro names are case-insensitive.
20930 t))))
20931 (when template
20932 (let ((value (replace-regexp-in-string
20933 "\\$[0-9]+"
20934 (lambda (arg)
20935 (or (nth (1- (string-to-number (substring arg 1)))
20936 (org-element-property :args macro))
20937 ;; No argument provided: remove
20938 ;; place-holder.
20939 ""))
20940 template)))
20941 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
20942 (when (string-match "\\`(eval\\>" value)
20943 (setq value (eval (read value))))
20944 ;; Return string.
20945 (format "%s" (or value ""))))))
20947 (defun org-macro-replace-all ()
20948 "Replace all macros in current buffer by their expansion."
20949 (save-excursion
20950 (goto-char (point-min))
20951 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
20952 (let ((object (org-element-context)))
20953 (when (eq (org-element-type object) 'macro)
20954 (let ((value (org-macro-expand object)))
20955 (when value
20956 (delete-region
20957 (org-element-property :begin object)
20958 ;; Preserve white spaces after the macro.
20959 (progn (goto-char (org-element-property :end object))
20960 (skip-chars-backward " \t")
20961 (point)))
20962 ;; Leave point before replacement in case of recursive
20963 ;; expansions.
20964 (save-excursion (insert value)))))))))
20966 (defun org-macro-initialize-templates ()
20967 "Collect macro templates defined in current buffer.
20968 Templates are stored in buffer-local variable
20969 `org-macro-templates'. In addition to buffer-defined macros, the
20970 function installs the following ones: \"property\", \"date\",
20971 \"time\". and, if appropriate, \"input-file\" and
20972 \"modification-time\"."
20973 (let ((case-fold-search t)
20974 (set-template
20975 (lambda (cell)
20976 ;; Add CELL to `org-macro-templates' if there's no
20977 ;; association matching its name already. Otherwise,
20978 ;; replace old association with the new one in that
20979 ;; variable.
20980 (let ((old-template (assoc (car cell) org-macro-templates)))
20981 (if old-template (setcdr old-template (cdr cell))
20982 (push cell org-macro-templates))))))
20983 ;; Install buffer-local macros.
20984 (org-with-wide-buffer
20985 (goto-char (point-min))
20986 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
20987 (let ((element (org-element-at-point)))
20988 (when (eq (org-element-type element) 'keyword)
20989 (let ((value (org-element-property :value element)))
20990 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
20991 (funcall set-template
20992 (cons (match-string 1 value)
20993 (or (match-string 2 value) "")))))))))
20994 ;; Install hard-coded macros.
20995 (mapc (lambda (cell) (funcall set-template cell))
20996 (list
20997 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
20998 (cons "date" "(eval (format-time-string \"$1\"))")
20999 (cons "time" "(eval (format-time-string \"$1\"))")))
21000 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21001 (when (and visited-file (file-exists-p visited-file))
21002 (mapc (lambda (cell) (funcall set-template cell))
21003 (list
21004 (cons "input-file" (file-name-nondirectory visited-file))
21005 (cons "modification-time"
21006 (format "(eval (format-time-string \"$1\" '%s))"
21007 (prin1-to-string
21008 (nth 5 (file-attributes visited-file)))))))))))
21011 ;;; Indentation
21013 (defun org-indent-line ()
21014 "Indent line depending on context."
21015 (interactive)
21016 (let* ((pos (point))
21017 (itemp (org-at-item-p))
21018 (case-fold-search t)
21019 (org-drawer-regexp (or org-drawer-regexp "\000"))
21020 (inline-task-p (and (featurep 'org-inlinetask)
21021 (org-inlinetask-in-task-p)))
21022 (inline-re (and inline-task-p
21023 (org-inlinetask-outline-regexp)))
21024 column)
21025 (if (and orgstruct-is-++ (eq pos (point)))
21026 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21027 (indent-according-to-mode))
21028 (beginning-of-line 1)
21029 (cond
21030 ;; Headings
21031 ((looking-at org-outline-regexp) (setq column 0))
21032 ;; Included files
21033 ((looking-at "#\\+include:") (setq column 0))
21034 ;; Footnote definition
21035 ((looking-at org-footnote-definition-re) (setq column 0))
21036 ;; Literal examples
21037 ((looking-at "[ \t]*:\\( \\|$\\)")
21038 (setq column (org-get-indentation))) ; do nothing
21039 ;; Lists
21040 ((ignore-errors (goto-char (org-in-item-p)))
21041 (setq column (if itemp
21042 (org-get-indentation)
21043 (org-list-item-body-column (point))))
21044 (goto-char pos))
21045 ;; Drawers
21046 ((and (looking-at "[ \t]*:END:")
21047 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21048 (save-excursion
21049 (goto-char (1- (match-beginning 1)))
21050 (setq column (current-column))))
21051 ;; Special blocks
21052 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21053 (save-excursion
21054 (re-search-backward
21055 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21056 (setq column (org-get-indentation (match-string 0))))
21057 ((and (not (looking-at "[ \t]*#\\+begin_"))
21058 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21059 (save-excursion
21060 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21061 (setq column
21062 (cond ((equal (downcase (match-string 1)) "src")
21063 ;; src blocks: let `org-edit-src-exit' handle them
21064 (org-get-indentation))
21065 ((equal (downcase (match-string 1)) "example")
21066 (max (org-get-indentation)
21067 (org-get-indentation (match-string 0))))
21069 (org-get-indentation (match-string 0))))))
21070 ;; This line has nothing special, look at the previous relevant
21071 ;; line to compute indentation
21073 (beginning-of-line 0)
21074 (while (and (not (bobp))
21075 (not (looking-at org-drawer-regexp))
21076 ;; When point started in an inline task, do not move
21077 ;; above task starting line.
21078 (not (and inline-task-p (looking-at inline-re)))
21079 ;; Skip drawers, blocks, empty lines, verbatim,
21080 ;; comments, tables, footnotes definitions, lists,
21081 ;; inline tasks.
21082 (or (and (looking-at "[ \t]*:END:")
21083 (re-search-backward org-drawer-regexp nil t))
21084 (and (looking-at "[ \t]*#\\+end_")
21085 (re-search-backward "[ \t]*#\\+begin_"nil t))
21086 (looking-at "[ \t]*[\n:#|]")
21087 (looking-at org-footnote-definition-re)
21088 (and (ignore-errors (goto-char (org-in-item-p)))
21089 (goto-char
21090 (org-list-get-top-point (org-list-struct))))
21091 (and (not inline-task-p)
21092 (featurep 'org-inlinetask)
21093 (org-inlinetask-in-task-p)
21094 (or (org-inlinetask-goto-beginning) t))))
21095 (beginning-of-line 0))
21096 (cond
21097 ;; There was an heading above.
21098 ((looking-at "\\*+[ \t]+")
21099 (if (not org-adapt-indentation)
21100 (setq column 0)
21101 (goto-char (match-end 0))
21102 (setq column (current-column))))
21103 ;; A drawer had started and is unfinished
21104 ((looking-at org-drawer-regexp)
21105 (goto-char (1- (match-beginning 1)))
21106 (setq column (current-column)))
21107 ;; Else, nothing noticeable found: get indentation and go on.
21108 (t (setq column (org-get-indentation))))))
21109 ;; Now apply indentation and move cursor accordingly
21110 (goto-char pos)
21111 (if (<= (current-column) (current-indentation))
21112 (org-indent-line-to column)
21113 (save-excursion (org-indent-line-to column)))
21114 ;; Special polishing for properties, see `org-property-format'
21115 (setq column (current-column))
21116 (beginning-of-line 1)
21117 (if (looking-at
21118 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21119 (replace-match (concat (match-string 1)
21120 (format org-property-format
21121 (match-string 2) (match-string 3)))
21122 t t))
21123 (org-move-to-column column))))
21125 (defun org-indent-drawer ()
21126 "Indent the drawer at point."
21127 (interactive)
21128 (let ((p (point))
21129 (e (and (save-excursion (re-search-forward ":END:" nil t))
21130 (match-end 0)))
21131 (folded
21132 (save-excursion
21133 (end-of-line)
21134 (when (overlays-at (point))
21135 (member 'invisible (overlay-properties
21136 (car (overlays-at (point)))))))))
21137 (when folded (org-cycle))
21138 (indent-for-tab-command)
21139 (while (and (move-beginning-of-line 2) (< (point) e))
21140 (indent-for-tab-command))
21141 (goto-char p)
21142 (when folded (org-cycle)))
21143 (message "Drawer at point indented"))
21145 (defun org-indent-block ()
21146 "Indent the block at point."
21147 (interactive)
21148 (let ((p (point))
21149 (case-fold-search t)
21150 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21151 (match-end 0)))
21152 (folded
21153 (save-excursion
21154 (end-of-line)
21155 (when (overlays-at (point))
21156 (member 'invisible (overlay-properties
21157 (car (overlays-at (point)))))))))
21158 (when folded (org-cycle))
21159 (indent-for-tab-command)
21160 (while (and (move-beginning-of-line 2) (< (point) e))
21161 (indent-for-tab-command))
21162 (goto-char p)
21163 (when folded (org-cycle)))
21164 (message "Block at point indented"))
21166 (defun org-indent-region (start end)
21167 "Indent region."
21168 (interactive "r")
21169 (save-excursion
21170 (let ((line-end (org-current-line end)))
21171 (goto-char start)
21172 (while (< (org-current-line) line-end)
21173 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21174 (t (call-interactively 'org-indent-line)))
21175 (move-beginning-of-line 2)))))
21178 ;;; Filling
21180 ;; We use our own fill-paragraph and auto-fill functions.
21182 ;; `org-fill-paragraph' relies on adaptive filling and context
21183 ;; checking. Appropriate `fill-prefix' is computed with
21184 ;; `org-adaptive-fill-function'.
21186 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21187 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21188 ;; `org-adaptive-fill-function' value. Internally,
21189 ;; `org-comment-line-break-function' breaks the line.
21191 ;; `org-setup-filling' installs filling and auto-filling related
21192 ;; variables during `org-mode' initialization.
21194 (defun org-setup-filling ()
21195 (interactive)
21196 ;; Prevent auto-fill from inserting unwanted new items.
21197 (when (boundp 'fill-nobreak-predicate)
21198 (org-set-local
21199 'fill-nobreak-predicate
21200 (org-uniquify
21201 (append fill-nobreak-predicate
21202 '(org-fill-paragraph-separate-nobreak-p
21203 org-fill-line-break-nobreak-p)))))
21204 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21205 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21206 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21207 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21209 (defvar org-element-paragraph-separate) ; org-element.el
21210 (defun org-fill-paragraph-separate-nobreak-p ()
21211 "Non-nil when a line break at point would insert a new item."
21212 (looking-at (substring org-element-paragraph-separate 1)))
21214 (defun org-fill-line-break-nobreak-p ()
21215 "Non-nil when a line break at point would create an Org line break."
21216 (save-excursion
21217 (skip-chars-backward "[ \t]")
21218 (skip-chars-backward "\\\\")
21219 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21221 (declare-function message-in-body-p "message" ())
21222 (defvar org-element--affiliated-re) ; From org-element.el
21223 (defun org-adaptive-fill-function ()
21224 "Compute a fill prefix for the current line.
21225 Return fill prefix, as a string, or nil if current line isn't
21226 meant to be filled."
21227 (org-with-wide-buffer
21228 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21229 ;; FIXME: This is really the job of orgstruct++-mode
21230 (let* ((p (line-beginning-position))
21231 (element (save-excursion (beginning-of-line)
21232 (org-element-at-point)))
21233 (type (org-element-type element))
21234 (post-affiliated
21235 (save-excursion
21236 (goto-char (org-element-property :begin element))
21237 (while (looking-at org-element--affiliated-re) (forward-line))
21238 (point))))
21239 (unless (< p post-affiliated)
21240 (case type
21241 (comment (looking-at "[ \t]*# ?") (match-string 0))
21242 (footnote-definition "")
21243 ((item plain-list)
21244 (make-string (org-list-item-body-column post-affiliated) ? ))
21245 (paragraph
21246 ;; Fill prefix is usually the same as the current line,
21247 ;; except if the paragraph is at the beginning of an item.
21248 (let ((parent (org-element-property :parent element)))
21249 (cond ((eq (org-element-type parent) 'item)
21250 (make-string (org-list-item-body-column
21251 (org-element-property :begin parent))
21252 ? ))
21253 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21254 (match-string 0))
21255 (t ""))))
21256 (comment-block
21257 ;; Only fill contents if P is within block boundaries.
21258 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21259 (forward-line)
21260 (point)))
21261 (cend (save-excursion
21262 (goto-char (org-element-property :end element))
21263 (skip-chars-backward " \r\t\n")
21264 (line-beginning-position))))
21265 (when (and (>= p cbeg) (< p cend))
21266 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21267 (match-string 0)
21268 ""))))))))))
21270 (declare-function message-goto-body "message" ())
21271 (defvar message-cite-prefix-regexp) ; From message.el
21272 (defvar org-element-all-objects) ; From org-element.el
21273 (defun org-fill-paragraph (&optional justify)
21274 "Fill element at point, when applicable.
21276 This function only applies to comment blocks, comments, example
21277 blocks and paragraphs. Also, as a special case, re-align table
21278 when point is at one.
21280 If JUSTIFY is non-nil (interactively, with prefix argument),
21281 justify as well. If `sentence-end-double-space' is non-nil, then
21282 period followed by one space does not end a sentence, so don't
21283 break a line there. The variable `fill-column' controls the
21284 width for filling.
21286 For convenience, when point is at a plain list, an item or
21287 a footnote definition, try to fill the first paragraph within."
21288 ;; Falls back on message-fill-paragraph when necessary
21289 (interactive)
21290 (if (and (derived-mode-p 'message-mode)
21291 (or (not (message-in-body-p))
21292 (save-excursion (move-beginning-of-line 1)
21293 (looking-at message-cite-prefix-regexp))))
21294 (let ((fill-paragraph-function
21295 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21296 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21297 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21298 (paragraph-separate
21299 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21300 (fill-paragraph nil))
21301 (save-excursion
21302 ;; Move to end of line in order to get the first paragraph
21303 ;; within a plain list or a footnote definition.
21304 (end-of-line)
21305 (let ((element (org-element-at-point)))
21306 ;; First check if point is in a blank line at the beginning of
21307 ;; the buffer. In that case, ignore filling.
21308 (if (< (point) (org-element-property :begin element)) t
21309 (case (org-element-type element)
21310 ;; Align Org tables, leave table.el tables as-is.
21311 (table-row (org-table-align) t)
21312 (table
21313 (when (eq (org-element-property :type element) 'org)
21314 (org-table-align))
21316 (paragraph
21317 ;; Paragraphs may contain `line-break' type objects.
21318 (let ((beg (max (point-min)
21319 (org-element-property :contents-begin element)))
21320 (end (min (point-max)
21321 (org-element-property :contents-end element))))
21322 ;; Do nothing if point is at an affiliated keyword.
21323 (if (< (point) beg) t
21324 (when (derived-mode-p 'message-mode)
21325 ;; In `message-mode', do not fill following
21326 ;; citation in current paragraph nor text before
21327 ;; message body.
21328 (let ((body-start (save-excursion (message-goto-body))))
21329 (when body-start (setq beg (max body-start beg))))
21330 (when (save-excursion
21331 (re-search-forward
21332 (concat "^" message-cite-prefix-regexp) end t))
21333 (setq end (match-beginning 0))))
21334 ;; Fill paragraph, taking line breaks into
21335 ;; consideration. For that, slice the paragraph
21336 ;; using line breaks as separators, and fill the
21337 ;; parts in reverse order to avoid messing with
21338 ;; markers.
21339 (save-excursion
21340 (goto-char end)
21341 (mapc
21342 (lambda (pos)
21343 (fill-region-as-paragraph pos (point) justify)
21344 (goto-char pos))
21345 ;; Find the list of ending positions for line
21346 ;; breaks in the current paragraph. Add paragraph
21347 ;; beginning to include first slice.
21348 (nreverse
21349 (cons
21351 (org-element-map
21352 (org-element--parse-objects
21353 beg end nil org-element-all-objects)
21354 'line-break
21355 (lambda (lb) (org-element-property :end lb)))))))
21356 t)))
21357 ;; Contents of `comment-block' type elements should be
21358 ;; filled as plain text, but only if point is within block
21359 ;; markers.
21360 (comment-block
21361 (let* ((case-fold-search t)
21362 (beg (save-excursion
21363 (goto-char (org-element-property :begin element))
21364 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21365 (forward-line)
21366 (point)))
21367 (end (save-excursion
21368 (goto-char (org-element-property :end element))
21369 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21370 (line-beginning-position))))
21371 (when (and (>= (point) beg) (< (point) end))
21372 (fill-region-as-paragraph
21373 (save-excursion
21374 (end-of-line)
21375 (re-search-backward "^[ \t]*$" beg 'move)
21376 (line-beginning-position))
21377 (save-excursion
21378 (beginning-of-line)
21379 (re-search-forward "^[ \t]*$" end 'move)
21380 (line-beginning-position))
21381 justify)))
21383 ;; Fill comments.
21384 (comment (fill-comment-paragraph justify))
21385 ;; Ignore every other element.
21386 (otherwise t)))))))
21388 (defun org-auto-fill-function ()
21389 "Auto-fill function."
21390 ;; Check if auto-filling is meaningful.
21391 (let ((fc (current-fill-column)))
21392 (when (and fc (> (current-column) fc))
21393 (let ((fill-prefix (org-adaptive-fill-function)))
21394 (when fill-prefix (do-auto-fill))))))
21396 (defun org-comment-line-break-function (&optional soft)
21397 "Break line at point and indent, continuing comment if within one.
21398 The inserted newline is marked hard if variable
21399 `use-hard-newlines' is true, unless optional argument SOFT is
21400 non-nil."
21401 (if soft (insert-and-inherit ?\n) (newline 1))
21402 (save-excursion (forward-char -1) (delete-horizontal-space))
21403 (delete-horizontal-space)
21404 (indent-to-left-margin)
21405 (insert-before-markers-and-inherit fill-prefix))
21408 ;;; Comments
21410 ;; Org comments syntax is quite complex. It requires the entire line
21411 ;; to be just a comment. Also, even with the right syntax at the
21412 ;; beginning of line, some some elements (i.e. verse-block or
21413 ;; example-block) don't accept comments. Usual Emacs comment commands
21414 ;; cannot cope with those requirements. Therefore, Org replaces them.
21416 ;; Org still relies on `comment-dwim', but cannot trust
21417 ;; `comment-only-p'. So, `comment-region-function' and
21418 ;; `uncomment-region-function' both point
21419 ;; to`org-comment-or-uncomment-region'. Eventually,
21420 ;; `org-insert-comment' takes care of insertion of comments at the
21421 ;; beginning of line.
21423 ;; `org-setup-comments-handling' install comments related variables
21424 ;; during `org-mode' initialization.
21426 (defun org-setup-comments-handling ()
21427 (interactive)
21428 (org-set-local 'comment-use-syntax nil)
21429 (org-set-local 'comment-start "# ")
21430 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21431 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21432 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21433 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21435 (defun org-insert-comment ()
21436 "Insert an empty comment above current line.
21437 If the line is empty, insert comment at its beginning."
21438 (beginning-of-line)
21439 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21440 (org-indent-line)
21441 (insert "# "))
21443 (defvar comment-empty-lines) ; From newcomment.el.
21444 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21445 "Comment or uncomment each non-blank line in the region.
21446 Uncomment each non-blank line between BEG and END if it only
21447 contains commented lines. Otherwise, comment them."
21448 (save-restriction
21449 ;; Restrict region
21450 (narrow-to-region (save-excursion (goto-char beg)
21451 (skip-chars-forward " \r\t\n" end)
21452 (line-beginning-position))
21453 (save-excursion (goto-char end)
21454 (skip-chars-backward " \r\t\n" beg)
21455 (line-end-position)))
21456 (let ((uncommentp
21457 ;; UNCOMMENTP is non-nil when every non blank line between
21458 ;; BEG and END is a comment.
21459 (save-excursion
21460 (goto-char (point-min))
21461 (while (and (not (eobp))
21462 (let ((element (org-element-at-point)))
21463 (and (eq (org-element-type element) 'comment)
21464 (goto-char (min (point-max)
21465 (org-element-property
21466 :end element)))))))
21467 (eobp))))
21468 (if uncommentp
21469 ;; Only blank lines and comments in region: uncomment it.
21470 (save-excursion
21471 (goto-char (point-min))
21472 (while (not (eobp))
21473 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21474 (replace-match "" nil nil nil 1))
21475 (forward-line)))
21476 ;; Comment each line in region.
21477 (let ((min-indent (point-max)))
21478 ;; First find the minimum indentation across all lines.
21479 (save-excursion
21480 (goto-char (point-min))
21481 (while (and (not (eobp)) (not (zerop min-indent)))
21482 (unless (looking-at "[ \t]*$")
21483 (setq min-indent (min min-indent (current-indentation))))
21484 (forward-line)))
21485 ;; Then loop over all lines.
21486 (save-excursion
21487 (goto-char (point-min))
21488 (while (not (eobp))
21489 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21490 (org-move-to-column min-indent t)
21491 (insert comment-start))
21492 (forward-line))))))))
21495 ;;; Other stuff.
21497 (defun org-toggle-fixed-width-section (arg)
21498 "Toggle the fixed-width export.
21499 If there is no active region, the QUOTE keyword at the current headline is
21500 inserted or removed. When present, it causes the text between this headline
21501 and the next to be exported as fixed-width text, and unmodified.
21502 If there is an active region, this command adds or removes a colon as the
21503 first character of this line. If the first character of a line is a colon,
21504 this line is also exported in fixed-width font."
21505 (interactive "P")
21506 (let* ((cc 0)
21507 (regionp (org-region-active-p))
21508 (beg (if regionp (region-beginning) (point)))
21509 (end (if regionp (region-end)))
21510 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21511 (case-fold-search nil)
21512 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21513 off)
21514 (if regionp
21515 (save-excursion
21516 (goto-char beg)
21517 (setq cc (current-column))
21518 (beginning-of-line 1)
21519 (setq off (looking-at re))
21520 (while (> nlines 0)
21521 (setq nlines (1- nlines))
21522 (beginning-of-line 1)
21523 (cond
21524 (arg
21525 (org-move-to-column cc t)
21526 (insert ": \n")
21527 (forward-line -1))
21528 ((and off (looking-at re))
21529 (replace-match "" t t nil 1))
21530 ((not off) (org-move-to-column cc t) (insert ": ")))
21531 (forward-line 1)))
21532 (save-excursion
21533 (org-back-to-heading)
21534 (cond
21535 ((looking-at (format org-heading-keyword-regexp-format
21536 org-quote-string))
21537 (goto-char (match-end 1))
21538 (looking-at (concat " +" org-quote-string))
21539 (replace-match "" t t)
21540 (when (eolp) (insert " ")))
21541 ((looking-at org-outline-regexp)
21542 (goto-char (match-end 0))
21543 (insert org-quote-string " ")))))))
21545 (defun org-reftex-citation ()
21546 "Use reftex-citation to insert a citation into the buffer.
21547 This looks for a line like
21549 #+BIBLIOGRAPHY: foo plain option:-d
21551 and derives from it that foo.bib is the bibliography file relevant
21552 for this document. It then installs the necessary environment for RefTeX
21553 to work in this buffer and calls `reftex-citation' to insert a citation
21554 into the buffer.
21556 Export of such citations to both LaTeX and HTML is handled by the contributed
21557 package org-exp-bibtex by Taru Karttunen."
21558 (interactive)
21559 (let ((reftex-docstruct-symbol 'rds)
21560 (reftex-cite-format "\\cite{%l}")
21561 rds bib)
21562 (save-excursion
21563 (save-restriction
21564 (widen)
21565 (let ((case-fold-search t)
21566 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21567 (if (not (save-excursion
21568 (or (re-search-forward re nil t)
21569 (re-search-backward re nil t))))
21570 (error "No bibliography defined in file")
21571 (setq bib (concat (match-string 1) ".bib")
21572 rds (list (list 'bib bib)))))))
21573 (call-interactively 'reftex-citation)))
21575 ;;;; Functions extending outline functionality
21577 (defun org-beginning-of-line (&optional arg)
21578 "Go to the beginning of the current line. If that is invisible, continue
21579 to a visible line beginning. This makes the function of C-a more intuitive.
21580 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21581 first attempt, and only move to after the tags when the cursor is already
21582 beyond the end of the headline."
21583 (interactive "P")
21584 (let ((pos (point))
21585 (special (if (consp org-special-ctrl-a/e)
21586 (car org-special-ctrl-a/e)
21587 org-special-ctrl-a/e))
21588 refpos)
21589 (if (org-bound-and-true-p line-move-visual)
21590 (beginning-of-visual-line 1)
21591 (beginning-of-line 1))
21592 (if (and arg (fboundp 'move-beginning-of-line))
21593 (call-interactively 'move-beginning-of-line)
21594 (if (bobp)
21596 (backward-char 1)
21597 (if (org-truely-invisible-p)
21598 (while (and (not (bobp)) (org-truely-invisible-p))
21599 (backward-char 1)
21600 (beginning-of-line 1))
21601 (forward-char 1))))
21602 (when special
21603 (cond
21604 ((and (looking-at org-complex-heading-regexp)
21605 (= (char-after (match-end 1)) ?\ ))
21606 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21607 (point-at-eol)))
21608 (goto-char
21609 (if (eq special t)
21610 (cond ((> pos refpos) refpos)
21611 ((= pos (point)) refpos)
21612 (t (point)))
21613 (cond ((> pos (point)) (point))
21614 ((not (eq last-command this-command)) (point))
21615 (t refpos)))))
21616 ((org-at-item-p)
21617 ;; Being at an item and not looking at an the item means point
21618 ;; was previously moved to beginning of a visual line, which
21619 ;; doesn't contain the item. Therefore, do nothing special,
21620 ;; just stay here.
21621 (when (looking-at org-list-full-item-re)
21622 ;; Set special position at first white space character after
21623 ;; bullet, and check-box, if any.
21624 (let ((after-bullet
21625 (let ((box (match-end 3)))
21626 (if (not box) (match-end 1)
21627 (let ((after (char-after box)))
21628 (if (and after (= after ? )) (1+ box) box))))))
21629 ;; Special case: Move point to special position when
21630 ;; currently after it or at beginning of line.
21631 (if (eq special t)
21632 (when (or (> pos after-bullet) (= (point) pos))
21633 (goto-char after-bullet))
21634 ;; Reversed case: Move point to special position when
21635 ;; point was already at beginning of line and command is
21636 ;; repeated.
21637 (when (and (= (point) pos) (eq last-command this-command))
21638 (goto-char after-bullet))))))))
21639 (org-no-warnings
21640 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21642 (defun org-end-of-line (&optional arg)
21643 "Go to the end of the line.
21644 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21645 first attempt, and only move to after the tags when the cursor is already
21646 beyond the end of the headline."
21647 (interactive "P")
21648 (let ((special (if (consp org-special-ctrl-a/e)
21649 (cdr org-special-ctrl-a/e)
21650 org-special-ctrl-a/e)))
21651 (cond
21652 ((or (not special) arg
21653 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21654 (call-interactively
21655 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21656 ((fboundp 'move-end-of-line) 'move-end-of-line)
21657 (t 'end-of-line))))
21658 ((org-at-heading-p)
21659 (let ((pos (point)))
21660 (beginning-of-line 1)
21661 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21662 (if (eq special t)
21663 (if (or (< pos (match-beginning 1))
21664 (= pos (match-end 0)))
21665 (goto-char (match-beginning 1))
21666 (goto-char (match-end 0)))
21667 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21668 (goto-char (match-end 0))
21669 (goto-char (match-beginning 1))))
21670 (call-interactively (if (fboundp 'move-end-of-line)
21671 'move-end-of-line
21672 'end-of-line)))))
21673 ((org-at-drawer-p)
21674 (move-end-of-line 1)
21675 (when (overlays-at (1- (point))) (backward-char 1)))
21676 ;; At an item: Move before any hidden text.
21677 (t (call-interactively
21678 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21679 ((fboundp 'move-end-of-line) 'move-end-of-line)
21680 (t 'end-of-line)))))
21681 (org-no-warnings
21682 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21684 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21685 (define-key org-mode-map "\C-e" 'org-end-of-line)
21687 (defun org-backward-sentence (&optional arg)
21688 "Go to beginning of sentence, or beginning of table field.
21689 This will call `backward-sentence' or `org-table-beginning-of-field',
21690 depending on context."
21691 (interactive "P")
21692 (cond
21693 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21694 (t (call-interactively 'backward-sentence))))
21696 (defun org-forward-sentence (&optional arg)
21697 "Go to end of sentence, or end of table field.
21698 This will call `forward-sentence' or `org-table-end-of-field',
21699 depending on context."
21700 (interactive "P")
21701 (cond
21702 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21703 (t (call-interactively 'forward-sentence))))
21705 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21706 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21708 (defun org-kill-line (&optional arg)
21709 "Kill line, to tags or end of line."
21710 (interactive "P")
21711 (cond
21712 ((or (not org-special-ctrl-k)
21713 (bolp)
21714 (not (org-at-heading-p)))
21715 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21716 org-ctrl-k-protect-subtree)
21717 (if (or (eq org-ctrl-k-protect-subtree 'error)
21718 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21719 (error "C-k aborted - would kill hidden subtree")))
21720 (call-interactively
21721 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21722 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21723 (kill-region (point) (match-beginning 1))
21724 (org-set-tags nil t))
21725 (t (kill-region (point) (point-at-eol)))))
21727 (define-key org-mode-map "\C-k" 'org-kill-line)
21729 (defun org-yank (&optional arg)
21730 "Yank. If the kill is a subtree, treat it specially.
21731 This command will look at the current kill and check if is a single
21732 subtree, or a series of subtrees[1]. If it passes the test, and if the
21733 cursor is at the beginning of a line or after the stars of a currently
21734 empty headline, then the yank is handled specially. How exactly depends
21735 on the value of the following variables, both set by default.
21737 org-yank-folded-subtrees
21738 When set, the subtree(s) will be folded after insertion, but only
21739 if doing so would now swallow text after the yanked text.
21741 org-yank-adjusted-subtrees
21742 When set, the subtree will be promoted or demoted in order to
21743 fit into the local outline tree structure, which means that the level
21744 will be adjusted so that it becomes the smaller one of the two
21745 *visible* surrounding headings.
21747 Any prefix to this command will cause `yank' to be called directly with
21748 no special treatment. In particular, a simple \\[universal-argument] prefix \
21749 will just
21750 plainly yank the text as it is.
21752 \[1] The test checks if the first non-white line is a heading
21753 and if there are no other headings with fewer stars."
21754 (interactive "P")
21755 (org-yank-generic 'yank arg))
21757 (defun org-yank-generic (command arg)
21758 "Perform some yank-like command.
21760 This function implements the behavior described in the `org-yank'
21761 documentation. However, it has been generalized to work for any
21762 interactive command with similar behavior."
21764 ;; pretend to be command COMMAND
21765 (setq this-command command)
21767 (if arg
21768 (call-interactively command)
21770 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21771 (and (org-kill-is-subtree-p)
21772 (or (bolp)
21773 (and (looking-at "[ \t]*$")
21774 (string-match
21775 "\\`\\*+\\'"
21776 (buffer-substring (point-at-bol) (point)))))))
21777 swallowp)
21778 (cond
21779 ((and subtreep org-yank-folded-subtrees)
21780 (let ((beg (point))
21781 end)
21782 (if (and subtreep org-yank-adjusted-subtrees)
21783 (org-paste-subtree nil nil 'for-yank)
21784 (call-interactively command))
21786 (setq end (point))
21787 (goto-char beg)
21788 (when (and (bolp) subtreep
21789 (not (setq swallowp
21790 (org-yank-folding-would-swallow-text beg end))))
21791 (org-with-limited-levels
21792 (or (looking-at org-outline-regexp)
21793 (re-search-forward org-outline-regexp-bol end t))
21794 (while (and (< (point) end) (looking-at org-outline-regexp))
21795 (hide-subtree)
21796 (org-cycle-show-empty-lines 'folded)
21797 (condition-case nil
21798 (outline-forward-same-level 1)
21799 (error (goto-char end))))))
21800 (when swallowp
21801 (message
21802 "Inserted text not folded because that would swallow text"))
21804 (goto-char end)
21805 (skip-chars-forward " \t\n\r")
21806 (beginning-of-line 1)
21807 (push-mark beg 'nomsg)))
21808 ((and subtreep org-yank-adjusted-subtrees)
21809 (let ((beg (point-at-bol)))
21810 (org-paste-subtree nil nil 'for-yank)
21811 (push-mark beg 'nomsg)))
21813 (call-interactively command))))))
21815 (defun org-yank-folding-would-swallow-text (beg end)
21816 "Would hide-subtree at BEG swallow any text after END?"
21817 (let (level)
21818 (org-with-limited-levels
21819 (save-excursion
21820 (goto-char beg)
21821 (when (or (looking-at org-outline-regexp)
21822 (re-search-forward org-outline-regexp-bol end t))
21823 (setq level (org-outline-level)))
21824 (goto-char end)
21825 (skip-chars-forward " \t\r\n\v\f")
21826 (if (or (eobp)
21827 (and (bolp) (looking-at org-outline-regexp)
21828 (<= (org-outline-level) level)))
21829 nil ; Nothing would be swallowed
21830 t))))) ; something would swallow
21832 (define-key org-mode-map "\C-y" 'org-yank)
21834 (defun org-truely-invisible-p ()
21835 "Check if point is at a character currently not visible.
21836 This version does not only check the character property, but also
21837 `visible-mode'."
21838 ;; Early versions of noutline don't have `outline-invisible-p'.
21839 (if (org-bound-and-true-p visible-mode)
21841 (outline-invisible-p)))
21843 (defun org-invisible-p2 ()
21844 "Check if point is at a character currently not visible."
21845 (save-excursion
21846 (if (and (eolp) (not (bobp))) (backward-char 1))
21847 ;; Early versions of noutline don't have `outline-invisible-p'.
21848 (outline-invisible-p)))
21850 (defun org-back-to-heading (&optional invisible-ok)
21851 "Call `outline-back-to-heading', but provide a better error message."
21852 (condition-case nil
21853 (outline-back-to-heading invisible-ok)
21854 (error (error "Before first headline at position %d in buffer %s"
21855 (point) (current-buffer)))))
21857 (defun org-before-first-heading-p ()
21858 "Before first heading?"
21859 (save-excursion
21860 (end-of-line)
21861 (null (re-search-backward org-outline-regexp-bol nil t))))
21863 (defun org-at-heading-p (&optional ignored)
21864 (outline-on-heading-p t))
21865 ;; Compatibility alias with Org versions < 7.8.03
21866 (defalias 'org-on-heading-p 'org-at-heading-p)
21868 (defun org-at-comment-p nil
21869 "Is cursor in a line starting with a # character?"
21870 (save-excursion
21871 (beginning-of-line)
21872 (looking-at "^#")))
21874 (defun org-at-drawer-p nil
21875 "Is cursor at a drawer keyword?"
21876 (save-excursion
21877 (move-beginning-of-line 1)
21878 (looking-at org-drawer-regexp)))
21880 (defun org-at-block-p nil
21881 "Is cursor at a block keyword?"
21882 (save-excursion
21883 (move-beginning-of-line 1)
21884 (looking-at org-block-regexp)))
21886 (defun org-point-at-end-of-empty-headline ()
21887 "If point is at the end of an empty headline, return t, else nil.
21888 If the heading only contains a TODO keyword, it is still still considered
21889 empty."
21890 (and (looking-at "[ \t]*$")
21891 (when org-todo-line-regexp
21892 (save-excursion
21893 (beginning-of-line 1)
21894 (let ((case-fold-search nil))
21895 (looking-at org-todo-line-regexp)
21896 (string= (match-string 3) ""))))))
21898 (defun org-at-heading-or-item-p ()
21899 (or (org-at-heading-p) (org-at-item-p)))
21901 (defun org-at-target-p ()
21902 (or (org-in-regexp org-radio-target-regexp)
21903 (org-in-regexp org-target-regexp)))
21904 ;; Compatibility alias with Org versions < 7.8.03
21905 (defalias 'org-on-target-p 'org-at-target-p)
21907 (defun org-up-heading-all (arg)
21908 "Move to the heading line of which the present line is a subheading.
21909 This function considers both visible and invisible heading lines.
21910 With argument, move up ARG levels."
21911 (if (fboundp 'outline-up-heading-all)
21912 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21913 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21915 (defun org-up-heading-safe ()
21916 "Move to the heading line of which the present line is a subheading.
21917 This version will not throw an error. It will return the level of the
21918 headline found, or nil if no higher level is found.
21920 Also, this function will be a lot faster than `outline-up-heading',
21921 because it relies on stars being the outline starters. This can really
21922 make a significant difference in outlines with very many siblings."
21923 (let (start-level re)
21924 (org-back-to-heading t)
21925 (setq start-level (funcall outline-level))
21926 (if (equal start-level 1)
21928 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21929 (if (re-search-backward re nil t)
21930 (funcall outline-level)))))
21932 (defun org-first-sibling-p ()
21933 "Is this heading the first child of its parents?"
21934 (interactive)
21935 (let ((re org-outline-regexp-bol)
21936 level l)
21937 (unless (org-at-heading-p t)
21938 (error "Not at a heading"))
21939 (setq level (funcall outline-level))
21940 (save-excursion
21941 (if (not (re-search-backward re nil t))
21943 (setq l (funcall outline-level))
21944 (< l level)))))
21946 (defun org-goto-sibling (&optional previous)
21947 "Goto the next sibling, even if it is invisible.
21948 When PREVIOUS is set, go to the previous sibling instead. Returns t
21949 when a sibling was found. When none is found, return nil and don't
21950 move point."
21951 (let ((fun (if previous 're-search-backward 're-search-forward))
21952 (pos (point))
21953 (re org-outline-regexp-bol)
21954 level l)
21955 (when (condition-case nil (org-back-to-heading t) (error nil))
21956 (setq level (funcall outline-level))
21957 (catch 'exit
21958 (or previous (forward-char 1))
21959 (while (funcall fun re nil t)
21960 (setq l (funcall outline-level))
21961 (when (< l level) (goto-char pos) (throw 'exit nil))
21962 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21963 (goto-char pos)
21964 nil))))
21966 (defun org-show-siblings ()
21967 "Show all siblings of the current headline."
21968 (save-excursion
21969 (while (org-goto-sibling) (org-flag-heading nil)))
21970 (save-excursion
21971 (while (org-goto-sibling 'previous)
21972 (org-flag-heading nil))))
21974 (defun org-goto-first-child ()
21975 "Goto the first child, even if it is invisible.
21976 Return t when a child was found. Otherwise don't move point and
21977 return nil."
21978 (let (level (pos (point)) (re org-outline-regexp-bol))
21979 (when (condition-case nil (org-back-to-heading t) (error nil))
21980 (setq level (outline-level))
21981 (forward-char 1)
21982 (if (and (re-search-forward re nil t) (> (outline-level) level))
21983 (progn (goto-char (match-beginning 0)) t)
21984 (goto-char pos) nil))))
21986 (defun org-show-hidden-entry ()
21987 "Show an entry where even the heading is hidden."
21988 (save-excursion
21989 (org-show-entry)))
21991 (defun org-flag-heading (flag &optional entry)
21992 "Flag the current heading. FLAG non-nil means make invisible.
21993 When ENTRY is non-nil, show the entire entry."
21994 (save-excursion
21995 (org-back-to-heading t)
21996 ;; Check if we should show the entire entry
21997 (if entry
21998 (progn
21999 (org-show-entry)
22000 (save-excursion
22001 (and (outline-next-heading)
22002 (org-flag-heading nil))))
22003 (outline-flag-region (max (point-min) (1- (point)))
22004 (save-excursion (outline-end-of-heading) (point))
22005 flag))))
22007 (defun org-get-next-sibling ()
22008 "Move to next heading of the same level, and return point.
22009 If there is no such heading, return nil.
22010 This is like outline-next-sibling, but invisible headings are ok."
22011 (let ((level (funcall outline-level)))
22012 (outline-next-heading)
22013 (while (and (not (eobp)) (> (funcall outline-level) level))
22014 (outline-next-heading))
22015 (if (or (eobp) (< (funcall outline-level) level))
22017 (point))))
22019 (defun org-get-last-sibling ()
22020 "Move to previous heading of the same level, and return point.
22021 If there is no such heading, return nil."
22022 (let ((opoint (point))
22023 (level (funcall outline-level)))
22024 (outline-previous-heading)
22025 (when (and (/= (point) opoint) (outline-on-heading-p t))
22026 (while (and (> (funcall outline-level) level)
22027 (not (bobp)))
22028 (outline-previous-heading))
22029 (if (< (funcall outline-level) level)
22031 (point)))))
22033 (defun org-end-of-subtree (&optional invisible-OK to-heading)
22034 ;; This contains an exact copy of the original function, but it uses
22035 ;; `org-back-to-heading', to make it work also in invisible
22036 ;; trees. And is uses an invisible-OK argument.
22037 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22038 ;; Furthermore, when used inside Org, finding the end of a large subtree
22039 ;; with many children and grandchildren etc, this can be much faster
22040 ;; than the outline version.
22041 (org-back-to-heading invisible-OK)
22042 (let ((first t)
22043 (level (funcall outline-level)))
22044 (if (and (derived-mode-p 'org-mode) (< level 1000))
22045 ;; A true heading (not a plain list item), in Org-mode
22046 ;; This means we can easily find the end by looking
22047 ;; only for the right number of stars. Using a regexp to do
22048 ;; this is so much faster than using a Lisp loop.
22049 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22050 (forward-char 1)
22051 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22052 ;; something else, do it the slow way
22053 (while (and (not (eobp))
22054 (or first (> (funcall outline-level) level)))
22055 (setq first nil)
22056 (outline-next-heading)))
22057 (unless to-heading
22058 (if (memq (preceding-char) '(?\n ?\^M))
22059 (progn
22060 ;; Go to end of line before heading
22061 (forward-char -1)
22062 (if (memq (preceding-char) '(?\n ?\^M))
22063 ;; leave blank line before heading
22064 (forward-char -1))))))
22065 (point))
22067 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22068 "Use Org version in org-mode, for dramatic speed-up."
22069 (if (derived-mode-p 'org-mode)
22070 (progn
22071 (org-end-of-subtree nil t)
22072 (unless (eobp) (backward-char 1)))
22073 ad-do-it))
22075 (defun org-end-of-meta-data-and-drawers ()
22076 "Jump to the first text after meta data and drawers in the current entry.
22077 This will move over empty lines, lines with planning time stamps,
22078 clocking lines, and drawers."
22079 (org-back-to-heading t)
22080 (let ((end (save-excursion (outline-next-heading) (point)))
22081 (re (concat "\\(" org-drawer-regexp "\\)"
22082 "\\|" "[ \t]*" org-keyword-time-regexp)))
22083 (forward-line 1)
22084 (while (re-search-forward re end t)
22085 (if (not (match-end 1))
22086 ;; empty or planning line
22087 (forward-line 1)
22088 ;; a drawer, find the end
22089 (re-search-forward "^[ \t]*:END:" end 'move)
22090 (forward-line 1)))
22091 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22092 (point)))
22094 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22095 "Move forward to the arg'th subheading at same level as this one.
22096 Stop at the first and last subheadings of a superior heading.
22097 Normally this only looks at visible headings, but when INVISIBLE-OK is
22098 non-nil it will also look at invisible ones."
22099 (interactive "p")
22100 (org-back-to-heading invisible-ok)
22101 (org-at-heading-p)
22102 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22103 (re (format "^\\*\\{1,%d\\} " level))
22105 (forward-char 1)
22106 (while (> arg 0)
22107 (while (and (re-search-forward re nil 'move)
22108 (setq l (- (match-end 0) (match-beginning 0) 1))
22109 (= l level)
22110 (not invisible-ok)
22111 (progn (backward-char 1) (outline-invisible-p)))
22112 (if (< l level) (setq arg 1)))
22113 (setq arg (1- arg)))
22114 (beginning-of-line 1)))
22116 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22117 "Move backward to the arg'th subheading at same level as this one.
22118 Stop at the first and last subheadings of a superior heading."
22119 (interactive "p")
22120 (org-back-to-heading)
22121 (org-at-heading-p)
22122 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22123 (re (format "^\\*\\{1,%d\\} " level))
22125 (while (> arg 0)
22126 (while (and (re-search-backward re nil 'move)
22127 (setq l (- (match-end 0) (match-beginning 0) 1))
22128 (= l level)
22129 (not invisible-ok)
22130 (outline-invisible-p))
22131 (if (< l level) (setq arg 1)))
22132 (setq arg (1- arg)))))
22134 ;;;###autoload
22135 (defun org-forward-element ()
22136 "Move forward by one element.
22137 Move to the next element at the same level, when possible."
22138 (interactive)
22139 (cond ((eobp) (error "Cannot move further down"))
22140 ((org-with-limited-levels (org-at-heading-p))
22141 (let ((origin (point)))
22142 (org-forward-heading-same-level 1)
22143 (unless (org-with-limited-levels (org-at-heading-p))
22144 (goto-char origin)
22145 (error "Cannot move further down"))))
22147 (let* ((elem (org-element-at-point))
22148 (end (org-element-property :end elem))
22149 (parent (org-element-property :parent elem)))
22150 (if (and parent (= (org-element-property :contents-end parent) end))
22151 (goto-char (org-element-property :end parent))
22152 (goto-char end))))))
22154 ;;;###autoload
22155 (defun org-backward-element ()
22156 "Move backward by one element.
22157 Move to the previous element at the same level, when possible."
22158 (interactive)
22159 (cond ((bobp) (error "Cannot move further up"))
22160 ((org-with-limited-levels (org-at-heading-p))
22161 ;; At an headline, move to the previous one, if any, or stay
22162 ;; here.
22163 (let ((origin (point)))
22164 (org-backward-heading-same-level 1)
22165 (unless (org-with-limited-levels (org-at-heading-p))
22166 (goto-char origin)
22167 (error "Cannot move further up"))))
22169 (let* ((trail (org-element-at-point 'keep-trail))
22170 (elem (car trail))
22171 (prev-elem (nth 1 trail))
22172 (beg (org-element-property :begin elem)))
22173 (cond
22174 ;; Move to beginning of current element if point isn't
22175 ;; there already.
22176 ((/= (point) beg) (goto-char beg))
22177 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22178 ((org-before-first-heading-p) (goto-char (point-min)))
22179 (t (org-back-to-heading)))))))
22181 ;;;###autoload
22182 (defun org-up-element ()
22183 "Move to upper element."
22184 (interactive)
22185 (if (org-with-limited-levels (org-at-heading-p))
22186 (unless (org-up-heading-safe) (error "No surrounding element"))
22187 (let* ((elem (org-element-at-point))
22188 (parent (org-element-property :parent elem)))
22189 (if parent (goto-char (org-element-property :begin parent))
22190 (if (org-with-limited-levels (org-before-first-heading-p))
22191 (error "No surrounding element")
22192 (org-with-limited-levels (org-back-to-heading)))))))
22194 ;;;###autoload
22195 (defvar org-element-greater-elements)
22196 (defun org-down-element ()
22197 "Move to inner element."
22198 (interactive)
22199 (let ((element (org-element-at-point)))
22200 (cond
22201 ((memq (org-element-type element) '(plain-list table))
22202 (goto-char (org-element-property :contents-begin element))
22203 (forward-char))
22204 ((memq (org-element-type element) org-element-greater-elements)
22205 ;; If contents are hidden, first disclose them.
22206 (when (org-element-property :hiddenp element) (org-cycle))
22207 (goto-char (or (org-element-property :contents-begin element)
22208 (error "No content for this element"))))
22209 (t (error "No inner element")))))
22211 ;;;###autoload
22212 (defun org-drag-element-backward ()
22213 "Move backward element at point."
22214 (interactive)
22215 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22216 (let* ((trail (org-element-at-point 'keep-trail))
22217 (elem (car trail))
22218 (prev-elem (nth 1 trail)))
22219 ;; Error out if no previous element or previous element is
22220 ;; a parent of the current one.
22221 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22222 (error "Cannot drag element backward")
22223 (let ((pos (point)))
22224 (org-element-swap-A-B prev-elem elem)
22225 (goto-char (+ (org-element-property :begin prev-elem)
22226 (- pos (org-element-property :begin elem)))))))))
22228 ;;;###autoload
22229 (defun org-drag-element-forward ()
22230 "Move forward element at point."
22231 (interactive)
22232 (let* ((pos (point))
22233 (elem (org-element-at-point)))
22234 (when (= (point-max) (org-element-property :end elem))
22235 (error "Cannot drag element forward"))
22236 (goto-char (org-element-property :end elem))
22237 (let ((next-elem (org-element-at-point)))
22238 (when (or (org-element-nested-p elem next-elem)
22239 (and (eq (org-element-type next-elem) 'headline)
22240 (not (eq (org-element-type elem) 'headline))))
22241 (goto-char pos)
22242 (error "Cannot drag element forward"))
22243 ;; Compute new position of point: it's shifted by NEXT-ELEM
22244 ;; body's length (without final blanks) and by the length of
22245 ;; blanks between ELEM and NEXT-ELEM.
22246 (let ((size-next (- (save-excursion
22247 (goto-char (org-element-property :end next-elem))
22248 (skip-chars-backward " \r\t\n")
22249 (forward-line)
22250 ;; Small correction if buffer doesn't end
22251 ;; with a newline character.
22252 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22253 (org-element-property :begin next-elem)))
22254 (size-blank (- (org-element-property :end elem)
22255 (save-excursion
22256 (goto-char (org-element-property :end elem))
22257 (skip-chars-backward " \r\t\n")
22258 (forward-line)
22259 (point)))))
22260 (org-element-swap-A-B elem next-elem)
22261 (goto-char (+ pos size-next size-blank))))))
22263 ;;;###autoload
22264 (defun org-mark-element ()
22265 "Put point at beginning of this element, mark at end.
22267 Interactively, if this command is repeated or (in Transient Mark
22268 mode) if the mark is active, it marks the next element after the
22269 ones already marked."
22270 (interactive)
22271 (let (deactivate-mark)
22272 (if (and (org-called-interactively-p 'any)
22273 (or (and (eq last-command this-command) (mark t))
22274 (and transient-mark-mode mark-active)))
22275 (set-mark
22276 (save-excursion
22277 (goto-char (mark))
22278 (goto-char (org-element-property :end (org-element-at-point)))))
22279 (let ((element (org-element-at-point)))
22280 (end-of-line)
22281 (push-mark (org-element-property :end element) t t)
22282 (goto-char (org-element-property :begin element))))))
22284 ;;;###autoload
22285 (defun org-narrow-to-element ()
22286 "Narrow buffer to current element."
22287 (interactive)
22288 (let ((elem (org-element-at-point)))
22289 (cond
22290 ((eq (car elem) 'headline)
22291 (narrow-to-region
22292 (org-element-property :begin elem)
22293 (org-element-property :end elem)))
22294 ((memq (car elem) org-element-greater-elements)
22295 (narrow-to-region
22296 (org-element-property :contents-begin elem)
22297 (org-element-property :contents-end elem)))
22299 (narrow-to-region
22300 (org-element-property :begin elem)
22301 (org-element-property :end elem))))))
22303 ;;;###autoload
22304 (defun org-transpose-element ()
22305 "Transpose current and previous elements, keeping blank lines between.
22306 Point is moved after both elements."
22307 (interactive)
22308 (org-skip-whitespace)
22309 (let ((end (org-element-property :end (org-element-at-point))))
22310 (org-drag-element-backward)
22311 (goto-char end)))
22313 ;;;###autoload
22314 (defun org-unindent-buffer ()
22315 "Un-indent the visible part of the buffer.
22316 Relative indentation (between items, inside blocks, etc.) isn't
22317 modified."
22318 (interactive)
22319 (unless (eq major-mode 'org-mode)
22320 (error "Cannot un-indent a buffer not in Org mode"))
22321 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22322 unindent-tree ; For byte-compiler.
22323 (unindent-tree
22324 (function
22325 (lambda (contents)
22326 (mapc
22327 (lambda (element)
22328 (if (memq (org-element-type element) '(headline section))
22329 (funcall unindent-tree (org-element-contents element))
22330 (save-excursion
22331 (save-restriction
22332 (narrow-to-region
22333 (org-element-property :begin element)
22334 (org-element-property :end element))
22335 (org-do-remove-indentation)))))
22336 (reverse contents))))))
22337 (funcall unindent-tree (org-element-contents parse-tree))))
22339 (defun org-show-subtree ()
22340 "Show everything after this heading at deeper levels."
22341 (interactive)
22342 (outline-flag-region
22343 (point)
22344 (save-excursion
22345 (org-end-of-subtree t t))
22346 nil))
22348 (defun org-show-entry ()
22349 "Show the body directly following this heading.
22350 Show the heading too, if it is currently invisible."
22351 (interactive)
22352 (save-excursion
22353 (condition-case nil
22354 (progn
22355 (org-back-to-heading t)
22356 (outline-flag-region
22357 (max (point-min) (1- (point)))
22358 (save-excursion
22359 (if (re-search-forward
22360 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22361 (match-beginning 1)
22362 (point-max)))
22363 nil)
22364 (org-cycle-hide-drawers 'children))
22365 (error nil))))
22367 (defun org-make-options-regexp (kwds &optional extra)
22368 "Make a regular expression for keyword lines."
22369 (concat
22370 "^#\\+\\("
22371 (mapconcat 'regexp-quote kwds "\\|")
22372 (if extra (concat "\\|" extra))
22373 "\\):[ \t]*\\(.*\\)"))
22375 ;; Make isearch reveal the necessary context
22376 (defun org-isearch-end ()
22377 "Reveal context after isearch exits."
22378 (when isearch-success ; only if search was successful
22379 (if (featurep 'xemacs)
22380 ;; Under XEmacs, the hook is run in the correct place,
22381 ;; we directly show the context.
22382 (org-show-context 'isearch)
22383 ;; In Emacs the hook runs *before* restoring the overlays.
22384 ;; So we have to use a one-time post-command-hook to do this.
22385 ;; (Emacs 22 has a special variable, see function `org-mode')
22386 (unless (and (boundp 'isearch-mode-end-hook-quit)
22387 isearch-mode-end-hook-quit)
22388 ;; Only when the isearch was not quitted.
22389 (org-add-hook 'post-command-hook 'org-isearch-post-command
22390 'append 'local)))))
22392 (defun org-isearch-post-command ()
22393 "Remove self from hook, and show context."
22394 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22395 (org-show-context 'isearch))
22398 ;;;; Integration with and fixes for other packages
22400 ;;; Imenu support
22402 (defvar org-imenu-markers nil
22403 "All markers currently used by Imenu.")
22404 (make-variable-buffer-local 'org-imenu-markers)
22406 (defun org-imenu-new-marker (&optional pos)
22407 "Return a new marker for use by Imenu, and remember the marker."
22408 (let ((m (make-marker)))
22409 (move-marker m (or pos (point)))
22410 (push m org-imenu-markers)
22413 (defun org-imenu-get-tree ()
22414 "Produce the index for Imenu."
22415 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22416 (setq org-imenu-markers nil)
22417 (let* ((n org-imenu-depth)
22418 (re (concat "^" (org-get-limited-outline-regexp)))
22419 (subs (make-vector (1+ n) nil))
22420 (last-level 0)
22421 m level head)
22422 (save-excursion
22423 (save-restriction
22424 (widen)
22425 (goto-char (point-max))
22426 (while (re-search-backward re nil t)
22427 (setq level (org-reduced-level (funcall outline-level)))
22428 (when (and (<= level n)
22429 (looking-at org-complex-heading-regexp))
22430 (setq head (org-link-display-format
22431 (org-match-string-no-properties 4))
22432 m (org-imenu-new-marker))
22433 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22434 (if (>= level last-level)
22435 (push (cons head m) (aref subs level))
22436 (push (cons head (aref subs (1+ level))) (aref subs level))
22437 (loop for i from (1+ level) to n do (aset subs i nil)))
22438 (setq last-level level)))))
22439 (aref subs 1)))
22441 (eval-after-load "imenu"
22442 '(progn
22443 (add-hook 'imenu-after-jump-hook
22444 (lambda ()
22445 (if (derived-mode-p 'org-mode)
22446 (org-show-context 'org-goto))))))
22448 (defun org-link-display-format (link)
22449 "Replace a link with either the description, or the link target
22450 if no description is present"
22451 (save-match-data
22452 (if (string-match org-bracket-link-analytic-regexp link)
22453 (replace-match (if (match-end 5)
22454 (match-string 5 link)
22455 (concat (match-string 1 link)
22456 (match-string 3 link)))
22457 nil t link)
22458 link)))
22460 (defun org-toggle-link-display ()
22461 "Toggle the literal or descriptive display of links."
22462 (interactive)
22463 (if org-descriptive-links
22464 (progn (org-remove-from-invisibility-spec '(org-link))
22465 (org-restart-font-lock)
22466 (setq org-descriptive-links nil))
22467 (progn (add-to-invisibility-spec '(org-link))
22468 (org-restart-font-lock)
22469 (setq org-descriptive-links t))))
22471 ;; Speedbar support
22473 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22474 "Overlay marking the agenda restriction line in speedbar.")
22475 (overlay-put org-speedbar-restriction-lock-overlay
22476 'face 'org-agenda-restriction-lock)
22477 (overlay-put org-speedbar-restriction-lock-overlay
22478 'help-echo "Agendas are currently limited to this item.")
22479 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22481 (defun org-speedbar-set-agenda-restriction ()
22482 "Restrict future agenda commands to the location at point in speedbar.
22483 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22484 (interactive)
22485 (require 'org-agenda)
22486 (let (p m tp np dir txt)
22487 (cond
22488 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22489 'org-imenu t))
22490 (setq m (get-text-property p 'org-imenu-marker))
22491 (with-current-buffer (marker-buffer m)
22492 (goto-char m)
22493 (org-agenda-set-restriction-lock 'subtree)))
22494 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22495 'speedbar-function 'speedbar-find-file))
22496 (setq tp (previous-single-property-change
22497 (1+ p) 'speedbar-function)
22498 np (next-single-property-change
22499 tp 'speedbar-function)
22500 dir (speedbar-line-directory)
22501 txt (buffer-substring-no-properties (or tp (point-min))
22502 (or np (point-max))))
22503 (with-current-buffer (find-file-noselect
22504 (let ((default-directory dir))
22505 (expand-file-name txt)))
22506 (unless (derived-mode-p 'org-mode)
22507 (error "Cannot restrict to non-Org-mode file"))
22508 (org-agenda-set-restriction-lock 'file)))
22509 (t (error "Don't know how to restrict Org-mode's agenda")))
22510 (move-overlay org-speedbar-restriction-lock-overlay
22511 (point-at-bol) (point-at-eol))
22512 (setq current-prefix-arg nil)
22513 (org-agenda-maybe-redo)))
22515 (eval-after-load "speedbar"
22516 '(progn
22517 (speedbar-add-supported-extension ".org")
22518 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22519 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22520 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22521 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22522 (add-hook 'speedbar-visiting-tag-hook
22523 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22525 ;;; Fixes and Hacks for problems with other packages
22527 ;; Make flyspell not check words in links, to not mess up our keymap
22528 (defun org-mode-flyspell-verify ()
22529 "Don't let flyspell put overlays at active buttons, or on
22530 {todo,all-time,additional-option-like}-keywords."
22531 (let ((pos (max (1- (point)) (point-min)))
22532 (word (thing-at-point 'word)))
22533 (and (not (get-text-property pos 'keymap))
22534 (not (get-text-property pos 'org-no-flyspell))
22535 (not (member word org-todo-keywords-1))
22536 (not (member word org-all-time-keywords))
22537 (not (member word org-options-keywords))
22538 (not (member word (mapcar 'car org-startup-options)))
22539 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22541 (defun org-remove-flyspell-overlays-in (beg end)
22542 "Remove flyspell overlays in region."
22543 (and (org-bound-and-true-p flyspell-mode)
22544 (fboundp 'flyspell-delete-region-overlays)
22545 (flyspell-delete-region-overlays beg end))
22546 (add-text-properties beg end '(org-no-flyspell t)))
22548 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22549 (eval-after-load "bookmark"
22550 '(if (boundp 'bookmark-after-jump-hook)
22551 ;; We can use the hook
22552 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22553 ;; Hook not available, use advice
22554 (defadvice bookmark-jump (after org-make-visible activate)
22555 "Make the position visible."
22556 (org-bookmark-jump-unhide))))
22558 ;; Make sure saveplace shows the location if it was hidden
22559 (eval-after-load "saveplace"
22560 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22561 "Make the position visible."
22562 (org-bookmark-jump-unhide)))
22564 ;; Make sure ecb shows the location if it was hidden
22565 (eval-after-load "ecb"
22566 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22567 "Make hierarchy visible when jumping into location from ECB tree buffer."
22568 (if (derived-mode-p 'org-mode)
22569 (org-show-context))))
22571 (defun org-bookmark-jump-unhide ()
22572 "Unhide the current position, to show the bookmark location."
22573 (and (derived-mode-p 'org-mode)
22574 (or (outline-invisible-p)
22575 (save-excursion (goto-char (max (point-min) (1- (point))))
22576 (outline-invisible-p)))
22577 (org-show-context 'bookmark-jump)))
22579 ;; Make session.el ignore our circular variable
22580 (eval-after-load "session"
22581 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22583 ;;;; Experimental code
22585 (defun org-closed-in-range ()
22586 "Sparse tree of items closed in a certain time range.
22587 Still experimental, may disappear in the future."
22588 (interactive)
22589 ;; Get the time interval from the user.
22590 (let* ((time1 (org-float-time
22591 (org-read-date nil 'to-time nil "Starting date: ")))
22592 (time2 (org-float-time
22593 (org-read-date nil 'to-time nil "End date:")))
22594 ;; callback function
22595 (callback (lambda ()
22596 (let ((time
22597 (org-float-time
22598 (apply 'encode-time
22599 (org-parse-time-string
22600 (match-string 1))))))
22601 ;; check if time in interval
22602 (and (>= time time1) (<= time time2))))))
22603 ;; make tree, check each match with the callback
22604 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22606 ;;;; Finish up
22608 (provide 'org)
22610 (run-hooks 'org-load-hook)
22612 ;;; org.el ends here