Rename some functions and move some hooks.
[org-mode.git] / lisp / org.el
blob3acacdc066c3afe4c676b4e9995bcd093c3a1b75
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
82 ;; some places -- e.g. see the macro org-with-limited-levels.
84 ;; In Org buffers, the value of `outline-regexp' is that of
85 ;; `org-outline-regexp'. The only function still directly relying on
86 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
87 ;; job when `orgstruct-mode' is active.
88 (defvar org-outline-regexp "\\*+ "
89 "Regexp to match Org headlines.")
91 (defvar org-outline-regexp-bol "^\\*+ "
92 "Regexp to match Org headlines.
93 This is similar to `org-outline-regexp' but additionally makes
94 sure that we are at the beginning of the line.")
96 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
97 "Matches an headline, putting stars and text into groups.
98 Stars are put in group 1 and the trimmed body in group 2.")
100 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
101 (when (fboundp 'defvaralias)
102 (unless (boundp 'calendar-view-holidays-initially-flag)
103 (defvaralias 'calendar-view-holidays-initially-flag
104 'view-calendar-holidays-initially))
105 (unless (boundp 'calendar-view-diary-initially-flag)
106 (defvaralias 'calendar-view-diary-initially-flag
107 'view-diary-entries-initially))
108 (unless (boundp 'diary-fancy-buffer)
109 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
111 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
112 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
113 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
114 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
115 (declare-function org-at-clock-log-p "org-clock" ())
116 (declare-function org-clock-timestamps-up "org-clock" ())
117 (declare-function org-clock-timestamps-down "org-clock" ())
118 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
120 ;; load languages based on value of `org-babel-load-languages'
121 (defvar org-babel-load-languages)
122 ;;;###autoload
123 (defun org-babel-do-load-languages (sym value)
124 "Load the languages defined in `org-babel-load-languages'."
125 (set-default sym value)
126 (mapc (lambda (pair)
127 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
128 (if active
129 (progn
130 (require (intern (concat "ob-" lang))))
131 (progn
132 (funcall 'fmakunbound
133 (intern (concat "org-babel-execute:" lang)))
134 (funcall 'fmakunbound
135 (intern (concat "org-babel-expand-body:" lang)))))))
136 org-babel-load-languages))
138 (defcustom org-babel-load-languages '((emacs-lisp . t))
139 "Languages which can be evaluated in Org-mode buffers.
140 This list can be used to load support for any of the languages
141 below, note that each language will depend on a different set of
142 system executables and/or Emacs modes. When a language is
143 \"loaded\", then code blocks in that language can be evaluated
144 with `org-babel-execute-src-block' bound by default to C-c
145 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
146 be set to remove code block evaluation from the C-c C-c
147 keybinding. By default only Emacs Lisp (which has no
148 requirements) is loaded."
149 :group 'org-babel
150 :set 'org-babel-do-load-languages
151 :version "24.1"
152 :type '(alist :tag "Babel Languages"
153 :key-type
154 (choice
155 (const :tag "Awk" awk)
156 (const :tag "C" C)
157 (const :tag "R" R)
158 (const :tag "Asymptote" asymptote)
159 (const :tag "Calc" calc)
160 (const :tag "Clojure" clojure)
161 (const :tag "CSS" css)
162 (const :tag "Ditaa" ditaa)
163 (const :tag "Dot" dot)
164 (const :tag "Emacs Lisp" emacs-lisp)
165 (const :tag "Fortran" fortran)
166 (const :tag "Gnuplot" gnuplot)
167 (const :tag "Haskell" haskell)
168 (const :tag "IO" io)
169 (const :tag "Java" java)
170 (const :tag "Javascript" js)
171 (const :tag "LaTeX" latex)
172 (const :tag "Ledger" ledger)
173 (const :tag "Lilypond" lilypond)
174 (const :tag "Lisp" lisp)
175 (const :tag "Maxima" maxima)
176 (const :tag "Matlab" matlab)
177 (const :tag "Mscgen" mscgen)
178 (const :tag "Ocaml" ocaml)
179 (const :tag "Octave" octave)
180 (const :tag "Org" org)
181 (const :tag "Perl" perl)
182 (const :tag "Pico Lisp" picolisp)
183 (const :tag "PlantUML" plantuml)
184 (const :tag "Python" python)
185 (const :tag "Ruby" ruby)
186 (const :tag "Sass" sass)
187 (const :tag "Scala" scala)
188 (const :tag "Scheme" scheme)
189 (const :tag "Screen" screen)
190 (const :tag "Shell Script" sh)
191 (const :tag "Shen" shen)
192 (const :tag "Sql" sql)
193 (const :tag "Sqlite" sqlite))
194 :value-type (boolean :tag "Activate" :value t)))
196 ;;;; Customization variables
197 (defcustom org-clone-delete-id nil
198 "Remove ID property of clones of a subtree.
199 When non-nil, clones of a subtree don't inherit the ID property.
200 Otherwise they inherit the ID property with a new unique
201 identifier."
202 :type 'boolean
203 :version "24.1"
204 :group 'org-id)
206 ;;; Version
207 (require 'org-compat)
208 (org-check-version)
209 ;;;###autoload
210 (defun org-version (&optional here full message)
211 "Show the org-mode version in the echo area.
212 With prefix argument HERE, insert it at point.
213 When FULL is non-nil, use a verbose version string.
214 When MESSAGE is non-nil, display a message with the version."
215 (interactive "P")
216 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
217 (org-install-dir (ignore-errors (org-find-library-dir "org-install.el")))
218 (org-trash (or
219 (and (fboundp 'org-release) (fboundp 'org-git-version))
220 (load (concat org-dir "org-version.el")
221 'noerror 'nomessage 'nosuffix)))
222 (org-version (org-release))
223 (git-version (org-git-version))
224 (version (format "Org-mode version %s (%s @ %s)"
225 org-version
226 git-version
227 (if org-install-dir
228 (if (string= org-dir org-install-dir)
229 org-install-dir
230 (concat "mixed installation! " org-install-dir " and " org-dir))
231 "org-install.el can not be found!")))
232 (_version (if full version org-version)))
233 (if (org-called-interactively-p 'interactive)
234 (if here
235 (insert version)
236 (message version))
237 (if message (message _version))
238 _version)))
240 (defconst org-version (org-version))
242 ;;; Compatibility constants
244 ;;; The custom variables
246 (defgroup org nil
247 "Outline-based notes management and organizer."
248 :tag "Org"
249 :group 'outlines
250 :group 'calendar)
252 (defcustom org-mode-hook nil
253 "Mode hook for Org-mode, run after the mode was turned on."
254 :group 'org
255 :type 'hook)
257 (defcustom org-load-hook nil
258 "Hook that is run after org.el has been loaded."
259 :group 'org
260 :type 'hook)
262 (defcustom org-log-buffer-setup-hook nil
263 "Hook that is run after an Org log buffer is created."
264 :group 'org
265 :version "24.1"
266 :type 'hook)
268 (defvar org-modules) ; defined below
269 (defvar org-modules-loaded nil
270 "Have the modules been loaded already?")
272 (defun org-load-modules-maybe (&optional force)
273 "Load all extensions listed in `org-modules'."
274 (when (or force (not org-modules-loaded))
275 (mapc (lambda (ext)
276 (condition-case nil (require ext)
277 (error (message "Problems while trying to load feature `%s'" ext))))
278 org-modules)
279 (setq org-modules-loaded t)))
281 (defun org-set-modules (var value)
282 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
283 (set var value)
284 (when (featurep 'org)
285 (org-load-modules-maybe 'force)))
287 (when (org-bound-and-true-p org-modules)
288 (let ((a (member 'org-infojs org-modules)))
289 (and a (setcar a 'org-jsinfo))))
291 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
292 "Modules that should always be loaded together with org.el.
293 If a description starts with <C>, the file is not part of Emacs
294 and loading it will require that you have downloaded and properly installed
295 the org-mode distribution.
297 You can also use this system to load external packages (i.e. neither Org
298 core modules, nor modules from the CONTRIB directory). Just add symbols
299 to the end of the list. If the package is called org-xyz.el, then you need
300 to add the symbol `xyz', and the package must have a call to
302 (provide 'org-xyz)"
303 :group 'org
304 :set 'org-set-modules
305 :type
306 '(set :greedy t
307 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
308 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
309 (const :tag " crypt: Encryption of subtrees" org-crypt)
310 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
311 (const :tag " docview: Links to doc-view buffers" org-docview)
312 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
313 (const :tag " id: Global IDs for identifying entries" org-id)
314 (const :tag " info: Links to Info nodes" org-info)
315 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
316 (const :tag " habit: Track your consistency with habits" org-habit)
317 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
318 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
319 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
320 (const :tag " mew Links to Mew folders/messages" org-mew)
321 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
322 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
323 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
324 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
325 (const :tag " vm: Links to VM folders/messages" org-vm)
326 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
327 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
328 (const :tag " mouse: Additional mouse support" org-mouse)
329 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
331 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
332 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
333 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
334 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
335 (const :tag "C collector: Collect properties into tables" org-collector)
336 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
337 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
338 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
339 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
340 (const :tag "C eval: Include command output as text" org-eval)
341 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
342 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
343 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
344 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
345 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
347 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
349 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
350 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
351 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
352 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
353 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
354 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
355 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
356 (const :tag "C mtags: Support for muse-like tags" org-mtags)
357 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
358 (const :tag "C registry: A registry for Org-mode links" org-registry)
359 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
360 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
361 (const :tag "C secretary: Team management with org-mode" org-secretary)
362 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
363 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
364 (const :tag "C track: Keep up with Org-mode development" org-track)
365 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
366 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
367 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
369 (defcustom org-support-shift-select nil
370 "Non-nil means make shift-cursor commands select text when possible.
372 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
373 start selecting a region, or enlarge regions started in this way.
374 In Org-mode, in special contexts, these same keys are used for
375 other purposes, important enough to compete with shift selection.
376 Org tries to balance these needs by supporting `shift-select-mode'
377 outside these special contexts, under control of this variable.
379 The default of this variable is nil, to avoid confusing behavior. Shifted
380 cursor keys will then execute Org commands in the following contexts:
381 - on a headline, changing TODO state (left/right) and priority (up/down)
382 - on a time stamp, changing the time
383 - in a plain list item, changing the bullet type
384 - in a property definition line, switching between allowed values
385 - in the BEGIN line of a clock table (changing the time block).
386 Outside these contexts, the commands will throw an error.
388 When this variable is t and the cursor is not in a special
389 context, Org-mode will support shift-selection for making and
390 enlarging regions. To make this more effective, the bullet
391 cycling will no longer happen anywhere in an item line, but only
392 if the cursor is exactly on the bullet.
394 If you set this variable to the symbol `always', then the keys
395 will not be special in headlines, property lines, and item lines,
396 to make shift selection work there as well. If this is what you
397 want, you can use the following alternative commands: `C-c C-t'
398 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
399 can be used to switch TODO sets, `C-c -' to cycle item bullet
400 types, and properties can be edited by hand or in column view.
402 However, when the cursor is on a timestamp, shift-cursor commands
403 will still edit the time stamp - this is just too good to give up.
405 XEmacs user should have this variable set to nil, because
406 `shift-select-mode' is in Emacs 23 or later only."
407 :group 'org
408 :type '(choice
409 (const :tag "Never" nil)
410 (const :tag "When outside special context" t)
411 (const :tag "Everywhere except timestamps" always)))
413 (defcustom org-loop-over-headlines-in-active-region nil
414 "Shall some commands act upon headlines in the active region?
416 When set to `t', some commands will be performed in all headlines
417 within the active region.
419 When set to `start-level', some commands will be performed in all
420 headlines within the active region, provided that these headlines
421 are of the same level than the first one.
423 When set to a string, those commands will be performed on the
424 matching headlines within the active region. Such string must be
425 a tags/property/todo match as it is used in the agenda tags view.
427 The list of commands is: `org-schedule', `org-deadline',
428 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
429 `org-archive-to-archive-sibling'. The archiving commands skip
430 already archived entries."
431 :type '(choice (const :tag "Don't loop" nil)
432 (const :tag "All headlines in active region" t)
433 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
434 (string :tag "Tags/Property/Todo matcher"))
435 :version "24.1"
436 :group 'org-todo
437 :group 'org-archive)
439 (defgroup org-startup nil
440 "Options concerning startup of Org-mode."
441 :tag "Org Startup"
442 :group 'org)
444 (defcustom org-startup-folded t
445 "Non-nil means entering Org-mode will switch to OVERVIEW.
446 This can also be configured on a per-file basis by adding one of
447 the following lines anywhere in the buffer:
449 #+STARTUP: fold (or `overview', this is equivalent)
450 #+STARTUP: nofold (or `showall', this is equivalent)
451 #+STARTUP: content
452 #+STARTUP: showeverything"
453 :group 'org-startup
454 :type '(choice
455 (const :tag "nofold: show all" nil)
456 (const :tag "fold: overview" t)
457 (const :tag "content: all headlines" content)
458 (const :tag "show everything, even drawers" showeverything)))
460 (defcustom org-startup-truncated t
461 "Non-nil means entering Org-mode will set `truncate-lines'.
462 This is useful since some lines containing links can be very long and
463 uninteresting. Also tables look terrible when wrapped."
464 :group 'org-startup
465 :type 'boolean)
467 (defcustom org-startup-indented nil
468 "Non-nil means turn on `org-indent-mode' on startup.
469 This can also be configured on a per-file basis by adding one of
470 the following lines anywhere in the buffer:
472 #+STARTUP: indent
473 #+STARTUP: noindent"
474 :group 'org-structure
475 :type '(choice
476 (const :tag "Not" nil)
477 (const :tag "Globally (slow on startup in large files)" t)))
479 (defcustom org-use-sub-superscripts t
480 "Non-nil means interpret \"_\" and \"^\" for export.
481 When this option is turned on, you can use TeX-like syntax for sub- and
482 superscripts. Several characters after \"_\" or \"^\" will be
483 considered as a single item - so grouping with {} is normally not
484 needed. For example, the following things will be parsed as single
485 sub- or superscripts.
487 10^24 or 10^tau several digits will be considered 1 item.
488 10^-12 or 10^-tau a leading sign with digits or a word
489 x^2-y^3 will be read as x^2 - y^3, because items are
490 terminated by almost any nonword/nondigit char.
491 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
493 Still, ambiguity is possible - so when in doubt use {} to enclose the
494 sub/superscript. If you set this variable to the symbol `{}',
495 the braces are *required* in order to trigger interpretations as
496 sub/superscript. This can be helpful in documents that need \"_\"
497 frequently in plain text.
499 Not all export backends support this, but HTML does.
501 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
502 :group 'org-startup
503 :group 'org-export-translation
504 :version "24.1"
505 :type '(choice
506 (const :tag "Always interpret" t)
507 (const :tag "Only with braces" {})
508 (const :tag "Never interpret" nil)))
510 (if (fboundp 'defvaralias)
511 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
514 (defcustom org-startup-with-beamer-mode nil
515 "Non-nil means turn on `org-beamer-mode' on startup.
516 This can also be configured on a per-file basis by adding one of
517 the following lines anywhere in the buffer:
519 #+STARTUP: beamer"
520 :group 'org-startup
521 :version "24.1"
522 :type 'boolean)
524 (defcustom org-startup-align-all-tables nil
525 "Non-nil means align all tables when visiting a file.
526 This is useful when the column width in tables is forced with <N> cookies
527 in table fields. Such tables will look correct only after the first re-align.
528 This can also be configured on a per-file basis by adding one of
529 the following lines anywhere in the buffer:
530 #+STARTUP: align
531 #+STARTUP: noalign"
532 :group 'org-startup
533 :type 'boolean)
535 (defcustom org-startup-with-inline-images nil
536 "Non-nil means show inline images when loading a new Org file.
537 This can also be configured on a per-file basis by adding one of
538 the following lines anywhere in the buffer:
539 #+STARTUP: inlineimages
540 #+STARTUP: noinlineimages"
541 :group 'org-startup
542 :version "24.1"
543 :type 'boolean)
545 (defcustom org-insert-mode-line-in-empty-file nil
546 "Non-nil means insert the first line setting Org-mode in empty files.
547 When the function `org-mode' is called interactively in an empty file, this
548 normally means that the file name does not automatically trigger Org-mode.
549 To ensure that the file will always be in Org-mode in the future, a
550 line enforcing Org-mode will be inserted into the buffer, if this option
551 has been set."
552 :group 'org-startup
553 :type 'boolean)
555 (defcustom org-replace-disputed-keys nil
556 "Non-nil means use alternative key bindings for some keys.
557 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
558 These keys are also used by other packages like shift-selection-mode'
559 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
560 If you want to use Org-mode together with one of these other modes,
561 or more generally if you would like to move some Org-mode commands to
562 other keys, set this variable and configure the keys with the variable
563 `org-disputed-keys'.
565 This option is only relevant at load-time of Org-mode, and must be set
566 *before* org.el is loaded. Changing it requires a restart of Emacs to
567 become effective."
568 :group 'org-startup
569 :type 'boolean)
571 (defcustom org-use-extra-keys nil
572 "Non-nil means use extra key sequence definitions for certain commands.
573 This happens automatically if you run XEmacs or if `window-system'
574 is nil. This variable lets you do the same manually. You must
575 set it before loading org.
577 Example: on Carbon Emacs 22 running graphically, with an external
578 keyboard on a Powerbook, the default way of setting M-left might
579 not work for either Alt or ESC. Setting this variable will make
580 it work for ESC."
581 :group 'org-startup
582 :type 'boolean)
584 (if (fboundp 'defvaralias)
585 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
587 (defcustom org-disputed-keys
588 '(([(shift up)] . [(meta p)])
589 ([(shift down)] . [(meta n)])
590 ([(shift left)] . [(meta -)])
591 ([(shift right)] . [(meta +)])
592 ([(control shift right)] . [(meta shift +)])
593 ([(control shift left)] . [(meta shift -)]))
594 "Keys for which Org-mode and other modes compete.
595 This is an alist, cars are the default keys, second element specifies
596 the alternative to use when `org-replace-disputed-keys' is t.
598 Keys can be specified in any syntax supported by `define-key'.
599 The value of this option takes effect only at Org-mode's startup,
600 therefore you'll have to restart Emacs to apply it after changing."
601 :group 'org-startup
602 :type 'alist)
604 (defun org-key (key)
605 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
606 Or return the original if not disputed.
607 Also apply the translations defined in `org-xemacs-key-equivalents'."
608 (when org-replace-disputed-keys
609 (let* ((nkey (key-description key))
610 (x (org-find-if (lambda (x)
611 (equal (key-description (car x)) nkey))
612 org-disputed-keys)))
613 (setq key (if x (cdr x) key))))
614 (when (featurep 'xemacs)
615 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
616 key)
618 (defun org-find-if (predicate seq)
619 (catch 'exit
620 (while seq
621 (if (funcall predicate (car seq))
622 (throw 'exit (car seq))
623 (pop seq)))))
625 (defun org-defkey (keymap key def)
626 "Define a key, possibly translated, as returned by `org-key'."
627 (define-key keymap (org-key key) def))
629 (defcustom org-ellipsis nil
630 "The ellipsis to use in the Org-mode outline.
631 When nil, just use the standard three dots. When a string, use that instead,
632 When a face, use the standard 3 dots, but with the specified face.
633 The change affects only Org-mode (which will then use its own display table).
634 Changing this requires executing `M-x org-mode' in a buffer to become
635 effective."
636 :group 'org-startup
637 :type '(choice (const :tag "Default" nil)
638 (face :tag "Face" :value org-warning)
639 (string :tag "String" :value "...#")))
641 (defvar org-display-table nil
642 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
644 (defgroup org-keywords nil
645 "Keywords in Org-mode."
646 :tag "Org Keywords"
647 :group 'org)
649 (defcustom org-deadline-string "DEADLINE:"
650 "String to mark deadline entries.
651 A deadline is this string, followed by a time stamp. Should be a word,
652 terminated by a colon. You can insert a schedule keyword and
653 a timestamp with \\[org-deadline].
654 Changes become only effective after restarting Emacs."
655 :group 'org-keywords
656 :type 'string)
658 (defcustom org-scheduled-string "SCHEDULED:"
659 "String to mark scheduled TODO entries.
660 A schedule is this string, followed by a time stamp. Should be a word,
661 terminated by a colon. You can insert a schedule keyword and
662 a timestamp with \\[org-schedule].
663 Changes become only effective after restarting Emacs."
664 :group 'org-keywords
665 :type 'string)
667 (defcustom org-closed-string "CLOSED:"
668 "String used as the prefix for timestamps logging closing a TODO entry."
669 :group 'org-keywords
670 :type 'string)
672 (defcustom org-clock-string "CLOCK:"
673 "String used as prefix for timestamps clocking work hours on an item."
674 :group 'org-keywords
675 :type 'string)
677 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
678 org-scheduled-string "\\|"
679 org-deadline-string "\\|"
680 org-closed-string "\\|"
681 org-clock-string "\\)")
682 "Matches a line with planning or clock info.")
684 (defcustom org-comment-string "COMMENT"
685 "Entries starting with this keyword will never be exported.
686 An entry can be toggled between COMMENT and normal with
687 \\[org-toggle-comment].
688 Changes become only effective after restarting Emacs."
689 :group 'org-keywords
690 :type 'string)
692 (defcustom org-quote-string "QUOTE"
693 "Entries starting with this keyword will be exported in fixed-width font.
694 Quoting applies only to the text in the entry following the headline, and does
695 not extend beyond the next headline, even if that is lower level.
696 An entry can be toggled between QUOTE and normal with
697 \\[org-toggle-fixed-width-section]."
698 :group 'org-keywords
699 :type 'string)
701 (defconst org-repeat-re
702 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
703 "Regular expression for specifying repeated events.
704 After a match, group 1 contains the repeat expression.")
706 (defgroup org-structure nil
707 "Options concerning the general structure of Org-mode files."
708 :tag "Org Structure"
709 :group 'org)
711 (defgroup org-reveal-location nil
712 "Options about how to make context of a location visible."
713 :tag "Org Reveal Location"
714 :group 'org-structure)
716 (defconst org-context-choice
717 '(choice
718 (const :tag "Always" t)
719 (const :tag "Never" nil)
720 (repeat :greedy t :tag "Individual contexts"
721 (cons
722 (choice :tag "Context"
723 (const agenda)
724 (const org-goto)
725 (const occur-tree)
726 (const tags-tree)
727 (const link-search)
728 (const mark-goto)
729 (const bookmark-jump)
730 (const isearch)
731 (const default))
732 (boolean))))
733 "Contexts for the reveal options.")
735 (defcustom org-show-hierarchy-above '((default . t))
736 "Non-nil means show full hierarchy when revealing a location.
737 Org-mode often shows locations in an org-mode file which might have
738 been invisible before. When this is set, the hierarchy of headings
739 above the exposed location is shown.
740 Turning this off for example for sparse trees makes them very compact.
741 Instead of t, this can also be an alist specifying this option for different
742 contexts. Valid contexts are
743 agenda when exposing an entry from the agenda
744 org-goto when using the command `org-goto' on key C-c C-j
745 occur-tree when using the command `org-occur' on key C-c /
746 tags-tree when constructing a sparse tree based on tags matches
747 link-search when exposing search matches associated with a link
748 mark-goto when exposing the jump goal of a mark
749 bookmark-jump when exposing a bookmark location
750 isearch when exiting from an incremental search
751 default default for all contexts not set explicitly"
752 :group 'org-reveal-location
753 :type org-context-choice)
755 (defcustom org-show-following-heading '((default . nil))
756 "Non-nil means show following heading when revealing a location.
757 Org-mode often shows locations in an org-mode file which might have
758 been invisible before. When this is set, the heading following the
759 match is shown.
760 Turning this off for example for sparse trees makes them very compact,
761 but makes it harder to edit the location of the match. In such a case,
762 use the command \\[org-reveal] to show more context.
763 Instead of t, this can also be an alist specifying this option for different
764 contexts. See `org-show-hierarchy-above' for valid contexts."
765 :group 'org-reveal-location
766 :type org-context-choice)
768 (defcustom org-show-siblings '((default . nil) (isearch t))
769 "Non-nil means show all sibling heading when revealing a location.
770 Org-mode often shows locations in an org-mode file which might have
771 been invisible before. When this is set, the sibling of the current entry
772 heading are all made visible. If `org-show-hierarchy-above' is t,
773 the same happens on each level of the hierarchy above the current entry.
775 By default this is on for the isearch context, off for all other contexts.
776 Turning this off for example for sparse trees makes them very compact,
777 but makes it harder to edit the location of the match. In such a case,
778 use the command \\[org-reveal] to show more context.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. See `org-show-hierarchy-above' for valid contexts."
781 :group 'org-reveal-location
782 :type org-context-choice)
784 (defcustom org-show-entry-below '((default . nil))
785 "Non-nil means show the entry below a headline when revealing a location.
786 Org-mode often shows locations in an org-mode file which might have
787 been invisible before. When this is set, the text below the headline that is
788 exposed is also shown.
790 By default this is off for all contexts.
791 Instead of t, this can also be an alist specifying this option for different
792 contexts. See `org-show-hierarchy-above' for valid contexts."
793 :group 'org-reveal-location
794 :type org-context-choice)
796 (defcustom org-indirect-buffer-display 'other-window
797 "How should indirect tree buffers be displayed?
798 This applies to indirect buffers created with the commands
799 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
800 Valid values are:
801 current-window Display in the current window
802 other-window Just display in another window.
803 dedicated-frame Create one new frame, and re-use it each time.
804 new-frame Make a new frame each time. Note that in this case
805 previously-made indirect buffers are kept, and you need to
806 kill these buffers yourself."
807 :group 'org-structure
808 :group 'org-agenda-windows
809 :type '(choice
810 (const :tag "In current window" current-window)
811 (const :tag "In current frame, other window" other-window)
812 (const :tag "Each time a new frame" new-frame)
813 (const :tag "One dedicated frame" dedicated-frame)))
815 (defcustom org-use-speed-commands nil
816 "Non-nil means activate single letter commands at beginning of a headline.
817 This may also be a function to test for appropriate locations where speed
818 commands should be active."
819 :group 'org-structure
820 :type '(choice
821 (const :tag "Never" nil)
822 (const :tag "At beginning of headline stars" t)
823 (function)))
825 (defcustom org-speed-commands-user nil
826 "Alist of additional speed commands.
827 This list will be checked before `org-speed-commands-default'
828 when the variable `org-use-speed-commands' is non-nil
829 and when the cursor is at the beginning of a headline.
830 The car if each entry is a string with a single letter, which must
831 be assigned to `self-insert-command' in the global map.
832 The cdr is either a command to be called interactively, a function
833 to be called, or a form to be evaluated.
834 An entry that is just a list with a single string will be interpreted
835 as a descriptive headline that will be added when listing the speed
836 commands in the Help buffer using the `?' speed command."
837 :group 'org-structure
838 :type '(repeat :value ("k" . ignore)
839 (choice :value ("k" . ignore)
840 (list :tag "Descriptive Headline" (string :tag "Headline"))
841 (cons :tag "Letter and Command"
842 (string :tag "Command letter")
843 (choice
844 (function)
845 (sexp))))))
847 (defgroup org-cycle nil
848 "Options concerning visibility cycling in Org-mode."
849 :tag "Org Cycle"
850 :group 'org-structure)
852 (defcustom org-cycle-skip-children-state-if-no-children t
853 "Non-nil means skip CHILDREN state in entries that don't have any."
854 :group 'org-cycle
855 :type 'boolean)
857 (defcustom org-cycle-max-level nil
858 "Maximum level which should still be subject to visibility cycling.
859 Levels higher than this will, for cycling, be treated as text, not a headline.
860 When `org-odd-levels-only' is set, a value of N in this variable actually
861 means 2N-1 stars as the limiting headline.
862 When nil, cycle all levels.
863 Note that the limiting level of cycling is also influenced by
864 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
865 `org-inlinetask-min-level' is, cycling will be limited to levels one less
866 than its value."
867 :group 'org-cycle
868 :type '(choice
869 (const :tag "No limit" nil)
870 (integer :tag "Maximum level")))
872 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
873 "Names of drawers. Drawers are not opened by cycling on the headline above.
874 Drawers only open with a TAB on the drawer line itself. A drawer looks like
875 this:
876 :DRAWERNAME:
877 .....
878 :END:
879 The drawer \"PROPERTIES\" is special for capturing properties through
880 the property API.
882 Drawers can be defined on the per-file basis with a line like:
884 #+DRAWERS: HIDDEN STATE PROPERTIES"
885 :group 'org-structure
886 :group 'org-cycle
887 :type '(repeat (string :tag "Drawer Name")))
889 (defcustom org-hide-block-startup nil
890 "Non-nil means entering Org-mode will fold all blocks.
891 This can also be set in on a per-file basis with
893 #+STARTUP: hideblocks
894 #+STARTUP: showblocks"
895 :group 'org-startup
896 :group 'org-cycle
897 :type 'boolean)
899 (defcustom org-cycle-global-at-bob nil
900 "Cycle globally if cursor is at beginning of buffer and not at a headline.
901 This makes it possible to do global cycling without having to use S-TAB or
902 \\[universal-argument] TAB. For this special case to work, the first line
903 of the buffer must not be a headline -- it may be empty or some other text.
904 When used in this way, `org-cycle-hook' is disabled temporarily to make
905 sure the cursor stays at the beginning of the buffer. When this option is
906 nil, don't do anything special at the beginning of the buffer."
907 :group 'org-cycle
908 :type 'boolean)
910 (defcustom org-cycle-level-after-item/entry-creation t
911 "Non-nil means cycle entry level or item indentation in new empty entries.
913 When the cursor is at the end of an empty headline, i.e with only stars
914 and maybe a TODO keyword, TAB will then switch the entry to become a child,
915 and then all possible ancestor states, before returning to the original state.
916 This makes data entry extremely fast: M-RET to create a new headline,
917 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
919 When the cursor is at the end of an empty plain list item, one TAB will
920 make it a subitem, two or more tabs will back up to make this an item
921 higher up in the item hierarchy."
922 :group 'org-cycle
923 :type 'boolean)
925 (defcustom org-cycle-emulate-tab t
926 "Where should `org-cycle' emulate TAB.
927 nil Never
928 white Only in completely white lines
929 whitestart Only at the beginning of lines, before the first non-white char
930 t Everywhere except in headlines
931 exc-hl-bol Everywhere except at the start of a headline
932 If TAB is used in a place where it does not emulate TAB, the current subtree
933 visibility is cycled."
934 :group 'org-cycle
935 :type '(choice (const :tag "Never" nil)
936 (const :tag "Only in completely white lines" white)
937 (const :tag "Before first char in a line" whitestart)
938 (const :tag "Everywhere except in headlines" t)
939 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
942 (defcustom org-cycle-separator-lines 2
943 "Number of empty lines needed to keep an empty line between collapsed trees.
944 If you leave an empty line between the end of a subtree and the following
945 headline, this empty line is hidden when the subtree is folded.
946 Org-mode will leave (exactly) one empty line visible if the number of
947 empty lines is equal or larger to the number given in this variable.
948 So the default 2 means at least 2 empty lines after the end of a subtree
949 are needed to produce free space between a collapsed subtree and the
950 following headline.
952 If the number is negative, and the number of empty lines is at least -N,
953 all empty lines are shown.
955 Special case: when 0, never leave empty lines in collapsed view."
956 :group 'org-cycle
957 :type 'integer)
958 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
960 (defcustom org-pre-cycle-hook nil
961 "Hook that is run before visibility cycling is happening.
962 The function(s) in this hook must accept a single argument which indicates
963 the new state that will be set right after running this hook. The
964 argument is a symbol. Before a global state change, it can have the values
965 `overview', `content', or `all'. Before a local state change, it can have
966 the values `folded', `children', or `subtree'."
967 :group 'org-cycle
968 :type 'hook)
970 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
971 org-cycle-hide-drawers
972 org-cycle-show-empty-lines
973 org-optimize-window-after-visibility-change)
974 "Hook that is run after `org-cycle' has changed the buffer visibility.
975 The function(s) in this hook must accept a single argument which indicates
976 the new state that was set by the most recent `org-cycle' command. The
977 argument is a symbol. After a global state change, it can have the values
978 `overview', `contents', or `all'. After a local state change, it can have
979 the values `folded', `children', or `subtree'."
980 :group 'org-cycle
981 :type 'hook)
983 (defgroup org-edit-structure nil
984 "Options concerning structure editing in Org-mode."
985 :tag "Org Edit Structure"
986 :group 'org-structure)
988 (defcustom org-odd-levels-only nil
989 "Non-nil means skip even levels and only use odd levels for the outline.
990 This has the effect that two stars are being added/taken away in
991 promotion/demotion commands. It also influences how levels are
992 handled by the exporters.
993 Changing it requires restart of `font-lock-mode' to become effective
994 for fontification also in regions already fontified.
995 You may also set this on a per-file basis by adding one of the following
996 lines to the buffer:
998 #+STARTUP: odd
999 #+STARTUP: oddeven"
1000 :group 'org-edit-structure
1001 :group 'org-appearance
1002 :type 'boolean)
1004 (defcustom org-adapt-indentation t
1005 "Non-nil means adapt indentation to outline node level.
1007 When this variable is set, Org assumes that you write outlines by
1008 indenting text in each node to align with the headline (after the stars).
1009 The following issues are influenced by this variable:
1011 - When this is set and the *entire* text in an entry is indented, the
1012 indentation is increased by one space in a demotion command, and
1013 decreased by one in a promotion command. If any line in the entry
1014 body starts with text at column 0, indentation is not changed at all.
1016 - Property drawers and planning information is inserted indented when
1017 this variable s set. When nil, they will not be indented.
1019 - TAB indents a line relative to context. The lines below a headline
1020 will be indented when this variable is set.
1022 Note that this is all about true indentation, by adding and removing
1023 space characters. See also `org-indent.el' which does level-dependent
1024 indentation in a virtual way, i.e. at display time in Emacs."
1025 :group 'org-edit-structure
1026 :type 'boolean)
1028 (defcustom org-special-ctrl-a/e nil
1029 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1031 When t, `C-a' will bring back the cursor to the beginning of the
1032 headline text, i.e. after the stars and after a possible TODO
1033 keyword. In an item, this will be the position after bullet and
1034 check-box, if any. When the cursor is already at that position,
1035 another `C-a' will bring it to the beginning of the line.
1037 `C-e' will jump to the end of the headline, ignoring the presence
1038 of tags in the headline. A second `C-e' will then jump to the
1039 true end of the line, after any tags. This also means that, when
1040 this variable is non-nil, `C-e' also will never jump beyond the
1041 end of the heading of a folded section, i.e. not after the
1042 ellipses.
1044 When set to the symbol `reversed', the first `C-a' or `C-e' works
1045 normally, going to the true line boundary first. Only a directly
1046 following, identical keypress will bring the cursor to the
1047 special positions.
1049 This may also be a cons cell where the behavior for `C-a' and
1050 `C-e' is set separately."
1051 :group 'org-edit-structure
1052 :type '(choice
1053 (const :tag "off" nil)
1054 (const :tag "on: after stars/bullet and before tags first" t)
1055 (const :tag "reversed: true line boundary first" reversed)
1056 (cons :tag "Set C-a and C-e separately"
1057 (choice :tag "Special C-a"
1058 (const :tag "off" nil)
1059 (const :tag "on: after stars/bullet first" t)
1060 (const :tag "reversed: before stars/bullet first" reversed))
1061 (choice :tag "Special C-e"
1062 (const :tag "off" nil)
1063 (const :tag "on: before tags first" t)
1064 (const :tag "reversed: after tags first" reversed)))))
1065 (if (fboundp 'defvaralias)
1066 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1068 (defcustom org-special-ctrl-k nil
1069 "Non-nil means `C-k' will behave specially in headlines.
1070 When nil, `C-k' will call the default `kill-line' command.
1071 When t, the following will happen while the cursor is in the headline:
1073 - When the cursor is at the beginning of a headline, kill the entire
1074 line and possible the folded subtree below the line.
1075 - When in the middle of the headline text, kill the headline up to the tags.
1076 - When after the headline text, kill the tags."
1077 :group 'org-edit-structure
1078 :type 'boolean)
1080 (defcustom org-ctrl-k-protect-subtree nil
1081 "Non-nil means, do not delete a hidden subtree with C-k.
1082 When set to the symbol `error', simply throw an error when C-k is
1083 used to kill (part-of) a headline that has hidden text behind it.
1084 Any other non-nil value will result in a query to the user, if it is
1085 OK to kill that hidden subtree. When nil, kill without remorse."
1086 :group 'org-edit-structure
1087 :version "24.1"
1088 :type '(choice
1089 (const :tag "Do not protect hidden subtrees" nil)
1090 (const :tag "Protect hidden subtrees with a security query" t)
1091 (const :tag "Never kill a hidden subtree with C-k" error)))
1093 (defcustom org-catch-invisible-edits nil
1094 "Check if in invisible region before inserting or deleting a character.
1095 Valid values are:
1097 nil Do not check, so just do invisible edits.
1098 error Throw an error and do nothing.
1099 show Make point visible, and do the requested edit.
1100 show-and-error Make point visible, then throw an error and abort the edit.
1101 smart Make point visible, and do insertion/deletion if it is
1102 adjacent to visible text and the change feels predictable.
1103 Never delete a previously invisible character or add in the
1104 middle or right after an invisible region. Basically, this
1105 allows insertion and backward-delete right before ellipses.
1106 FIXME: maybe in this case we should not even show?"
1107 :group 'org-edit-structure
1108 :version "24.1"
1109 :type '(choice
1110 (const :tag "Do not check" nil)
1111 (const :tag "Throw error when trying to edit" error)
1112 (const :tag "Unhide, but do not do the edit" show-and-error)
1113 (const :tag "Show invisible part and do the edit" show)
1114 (const :tag "Be smart and do the right thing" smart)))
1116 (defcustom org-yank-folded-subtrees t
1117 "Non-nil means when yanking subtrees, fold them.
1118 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1119 it starts with a heading and all other headings in it are either children
1120 or siblings, then fold all the subtrees. However, do this only if no
1121 text after the yank would be swallowed into a folded tree by this action."
1122 :group 'org-edit-structure
1123 :type 'boolean)
1125 (defcustom org-yank-adjusted-subtrees nil
1126 "Non-nil means when yanking subtrees, adjust the level.
1127 With this setting, `org-paste-subtree' is used to insert the subtree, see
1128 this function for details."
1129 :group 'org-edit-structure
1130 :type 'boolean)
1132 (defcustom org-M-RET-may-split-line '((default . t))
1133 "Non-nil means M-RET will split the line at the cursor position.
1134 When nil, it will go to the end of the line before making a
1135 new line.
1136 You may also set this option in a different way for different
1137 contexts. Valid contexts are:
1139 headline when creating a new headline
1140 item when creating a new item
1141 table in a table field
1142 default the value to be used for all contexts not explicitly
1143 customized"
1144 :group 'org-structure
1145 :group 'org-table
1146 :type '(choice
1147 (const :tag "Always" t)
1148 (const :tag "Never" nil)
1149 (repeat :greedy t :tag "Individual contexts"
1150 (cons
1151 (choice :tag "Context"
1152 (const headline)
1153 (const item)
1154 (const table)
1155 (const default))
1156 (boolean)))))
1159 (defcustom org-insert-heading-respect-content nil
1160 "Non-nil means insert new headings after the current subtree.
1161 When nil, the new heading is created directly after the current line.
1162 The commands \\[org-insert-heading-respect-content] and
1163 \\[org-insert-todo-heading-respect-content] turn this variable on
1164 for the duration of the command."
1165 :group 'org-structure
1166 :type 'boolean)
1168 (defcustom org-blank-before-new-entry '((heading . auto)
1169 (plain-list-item . auto))
1170 "Should `org-insert-heading' leave a blank line before new heading/item?
1171 The value is an alist, with `heading' and `plain-list-item' as CAR,
1172 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1173 which case Org will look at the surrounding headings/items and try to
1174 make an intelligent decision whether to insert a blank line or not.
1176 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1177 set, the setting here is ignored and no empty line is inserted, to avoid
1178 breaking the list structure."
1179 :group 'org-edit-structure
1180 :type '(list
1181 (cons (const heading)
1182 (choice (const :tag "Never" nil)
1183 (const :tag "Always" t)
1184 (const :tag "Auto" auto)))
1185 (cons (const plain-list-item)
1186 (choice (const :tag "Never" nil)
1187 (const :tag "Always" t)
1188 (const :tag "Auto" auto)))))
1190 (defcustom org-insert-heading-hook nil
1191 "Hook being run after inserting a new heading."
1192 :group 'org-edit-structure
1193 :type 'hook)
1195 (defcustom org-enable-fixed-width-editor t
1196 "Non-nil means lines starting with \":\" are treated as fixed-width.
1197 This currently only means they are never auto-wrapped.
1198 When nil, such lines will be treated like ordinary lines.
1199 See also the QUOTE keyword."
1200 :group 'org-edit-structure
1201 :type 'boolean)
1203 (defcustom org-goto-auto-isearch t
1204 "Non-nil means typing characters in `org-goto' starts incremental search."
1205 :group 'org-edit-structure
1206 :type 'boolean)
1208 (defgroup org-sparse-trees nil
1209 "Options concerning sparse trees in Org-mode."
1210 :tag "Org Sparse Trees"
1211 :group 'org-structure)
1213 (defcustom org-highlight-sparse-tree-matches t
1214 "Non-nil means highlight all matches that define a sparse tree.
1215 The highlights will automatically disappear the next time the buffer is
1216 changed by an edit command."
1217 :group 'org-sparse-trees
1218 :type 'boolean)
1220 (defcustom org-remove-highlights-with-change t
1221 "Non-nil means any change to the buffer will remove temporary highlights.
1222 Such highlights are created by `org-occur' and `org-clock-display'.
1223 When nil, `C-c C-c needs to be used to get rid of the highlights.
1224 The highlights created by `org-preview-latex-fragment' always need
1225 `C-c C-c' to be removed."
1226 :group 'org-sparse-trees
1227 :group 'org-time
1228 :type 'boolean)
1231 (defcustom org-occur-hook '(org-first-headline-recenter)
1232 "Hook that is run after `org-occur' has constructed a sparse tree.
1233 This can be used to recenter the window to show as much of the structure
1234 as possible."
1235 :group 'org-sparse-trees
1236 :type 'hook)
1238 (defgroup org-imenu-and-speedbar nil
1239 "Options concerning imenu and speedbar in Org-mode."
1240 :tag "Org Imenu and Speedbar"
1241 :group 'org-structure)
1243 (defcustom org-imenu-depth 2
1244 "The maximum level for Imenu access to Org-mode headlines.
1245 This also applied for speedbar access."
1246 :group 'org-imenu-and-speedbar
1247 :type 'integer)
1249 (defgroup org-table nil
1250 "Options concerning tables in Org-mode."
1251 :tag "Org Table"
1252 :group 'org)
1254 (defcustom org-enable-table-editor 'optimized
1255 "Non-nil means lines starting with \"|\" are handled by the table editor.
1256 When nil, such lines will be treated like ordinary lines.
1258 When equal to the symbol `optimized', the table editor will be optimized to
1259 do the following:
1260 - Automatic overwrite mode in front of whitespace in table fields.
1261 This makes the structure of the table stay in tact as long as the edited
1262 field does not exceed the column width.
1263 - Minimize the number of realigns. Normally, the table is aligned each time
1264 TAB or RET are pressed to move to another field. With optimization this
1265 happens only if changes to a field might have changed the column width.
1266 Optimization requires replacing the functions `self-insert-command',
1267 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1268 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1269 very good at guessing when a re-align will be necessary, but you can always
1270 force one with \\[org-ctrl-c-ctrl-c].
1272 If you would like to use the optimized version in Org-mode, but the
1273 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1275 This variable can be used to turn on and off the table editor during a session,
1276 but in order to toggle optimization, a restart is required.
1278 See also the variable `org-table-auto-blank-field'."
1279 :group 'org-table
1280 :type '(choice
1281 (const :tag "off" nil)
1282 (const :tag "on" t)
1283 (const :tag "on, optimized" optimized)))
1285 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1286 (version<= emacs-version "24.1"))
1287 "Non-nil means cluster self-insert commands for undo when possible.
1288 If this is set, then, like in the Emacs command loop, 20 consecutive
1289 characters will be undone together.
1290 This is configurable, because there is some impact on typing performance."
1291 :group 'org-table
1292 :type 'boolean)
1294 (defcustom org-table-tab-recognizes-table.el t
1295 "Non-nil means TAB will automatically notice a table.el table.
1296 When it sees such a table, it moves point into it and - if necessary -
1297 calls `table-recognize-table'."
1298 :group 'org-table-editing
1299 :type 'boolean)
1301 (defgroup org-link nil
1302 "Options concerning links in Org-mode."
1303 :tag "Org Link"
1304 :group 'org)
1306 (defvar org-link-abbrev-alist-local nil
1307 "Buffer-local version of `org-link-abbrev-alist', which see.
1308 The value of this is taken from the #+LINK lines.")
1309 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1311 (defcustom org-link-abbrev-alist nil
1312 "Alist of link abbreviations.
1313 The car of each element is a string, to be replaced at the start of a link.
1314 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1315 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1317 [[linkkey:tag][description]]
1319 The 'linkkey' must be a word word, starting with a letter, followed
1320 by letters, numbers, '-' or '_'.
1322 If REPLACE is a string, the tag will simply be appended to create the link.
1323 If the string contains \"%s\", the tag will be inserted there. If the string
1324 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1325 at that point (see the function `url-hexify-string'). If the string contains
1326 the specifier \"%(my-function)\", then the custom function `my-function' will
1327 be invoked: this function takes the tag as its only argument and must return
1328 a string.
1330 REPLACE may also be a function that will be called with the tag as the
1331 only argument to create the link, which should be returned as a string.
1333 See the manual for examples."
1334 :group 'org-link
1335 :type '(repeat
1336 (cons
1337 (string :tag "Protocol")
1338 (choice
1339 (string :tag "Format")
1340 (function)))))
1342 (defcustom org-descriptive-links t
1343 "Non-nil means Org will display descriptive links.
1344 E.g. [[http://orgmode.org][Org website]] will be displayed as
1345 \"Org Website\", hiding the link itself and just displaying its
1346 description. When set to `nil', Org will display the full links
1347 literally.
1349 You can interactively set the value of this variable by calling
1350 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1351 :group 'org-link
1352 :type 'boolean)
1354 (defcustom org-link-file-path-type 'adaptive
1355 "How the path name in file links should be stored.
1356 Valid values are:
1358 relative Relative to the current directory, i.e. the directory of the file
1359 into which the link is being inserted.
1360 absolute Absolute path, if possible with ~ for home directory.
1361 noabbrev Absolute path, no abbreviation of home directory.
1362 adaptive Use relative path for files in the current directory and sub-
1363 directories of it. For other files, use an absolute path."
1364 :group 'org-link
1365 :type '(choice
1366 (const relative)
1367 (const absolute)
1368 (const noabbrev)
1369 (const adaptive)))
1371 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1372 "Types of links that should be activated in Org-mode files.
1373 This is a list of symbols, each leading to the activation of a certain link
1374 type. In principle, it does not hurt to turn on most link types - there may
1375 be a small gain when turning off unused link types. The types are:
1377 bracket The recommended [[link][description]] or [[link]] links with hiding.
1378 angle Links in angular brackets that may contain whitespace like
1379 <bbdb:Carsten Dominik>.
1380 plain Plain links in normal text, no whitespace, like http://google.com.
1381 radio Text that is matched by a radio target, see manual for details.
1382 tag Tag settings in a headline (link to tag search).
1383 date Time stamps (link to calendar).
1384 footnote Footnote labels.
1386 Changing this variable requires a restart of Emacs to become effective."
1387 :group 'org-link
1388 :type '(set :greedy t
1389 (const :tag "Double bracket links" bracket)
1390 (const :tag "Angular bracket links" angle)
1391 (const :tag "Plain text links" plain)
1392 (const :tag "Radio target matches" radio)
1393 (const :tag "Tags" tag)
1394 (const :tag "Timestamps" date)
1395 (const :tag "Footnotes" footnote)))
1397 (defcustom org-make-link-description-function nil
1398 "Function to use to generate link descriptions from links.
1399 If nil the link location will be used. This function must take
1400 two parameters; the first is the link and the second the
1401 description `org-insert-link' has generated, and should return the
1402 description to use."
1403 :group 'org-link
1404 :type 'function)
1406 (defgroup org-link-store nil
1407 "Options concerning storing links in Org-mode."
1408 :tag "Org Store Link"
1409 :group 'org-link)
1411 (defcustom org-url-hexify-p t
1412 "When non-nil, hexify URL when creating a link."
1413 :type 'boolean
1414 ;; :version "24.3"
1415 :group 'org-link-store)
1417 (defcustom org-email-link-description-format "Email %c: %.30s"
1418 "Format of the description part of a link to an email or usenet message.
1419 The following %-escapes will be replaced by corresponding information:
1421 %F full \"From\" field
1422 %f name, taken from \"From\" field, address if no name
1423 %T full \"To\" field
1424 %t first name in \"To\" field, address if no name
1425 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1426 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1427 %s subject
1428 %d date
1429 %m message-id.
1431 You may use normal field width specification between the % and the letter.
1432 This is for example useful to limit the length of the subject.
1434 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1435 :group 'org-link-store
1436 :type 'string)
1438 (defcustom org-from-is-user-regexp
1439 (let (r1 r2)
1440 (when (and user-mail-address (not (string= user-mail-address "")))
1441 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1442 (when (and user-full-name (not (string= user-full-name "")))
1443 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1444 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1445 "Regexp matched against the \"From:\" header of an email or usenet message.
1446 It should match if the message is from the user him/herself."
1447 :group 'org-link-store
1448 :type 'regexp)
1450 (defcustom org-context-in-file-links t
1451 "Non-nil means file links from `org-store-link' contain context.
1452 A search string will be added to the file name with :: as separator and
1453 used to find the context when the link is activated by the command
1454 `org-open-at-point'. When this option is t, the entire active region
1455 will be placed in the search string of the file link. If set to a
1456 positive integer, only the first n lines of context will be stored.
1458 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1459 negates this setting for the duration of the command."
1460 :group 'org-link-store
1461 :type '(choice boolean integer))
1463 (defcustom org-keep-stored-link-after-insertion nil
1464 "Non-nil means keep link in list for entire session.
1466 The command `org-store-link' adds a link pointing to the current
1467 location to an internal list. These links accumulate during a session.
1468 The command `org-insert-link' can be used to insert links into any
1469 Org-mode file (offering completion for all stored links). When this
1470 option is nil, every link which has been inserted once using \\[org-insert-link]
1471 will be removed from the list, to make completing the unused links
1472 more efficient."
1473 :group 'org-link-store
1474 :type 'boolean)
1476 (defgroup org-link-follow nil
1477 "Options concerning following links in Org-mode."
1478 :tag "Org Follow Link"
1479 :group 'org-link)
1481 (defcustom org-link-translation-function nil
1482 "Function to translate links with different syntax to Org syntax.
1483 This can be used to translate links created for example by the Planner
1484 or emacs-wiki packages to Org syntax.
1485 The function must accept two parameters, a TYPE containing the link
1486 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1487 which is everything after the link protocol. It should return a cons
1488 with possibly modified values of type and path.
1489 Org contains a function for this, so if you set this variable to
1490 `org-translate-link-from-planner', you should be able follow many
1491 links created by planner."
1492 :group 'org-link-follow
1493 :type 'function)
1495 (defcustom org-follow-link-hook nil
1496 "Hook that is run after a link has been followed."
1497 :group 'org-link-follow
1498 :type 'hook)
1500 (defcustom org-tab-follows-link nil
1501 "Non-nil means on links TAB will follow the link.
1502 Needs to be set before org.el is loaded.
1503 This really should not be used, it does not make sense, and the
1504 implementation is bad."
1505 :group 'org-link-follow
1506 :type 'boolean)
1508 (defcustom org-return-follows-link nil
1509 "Non-nil means on links RET will follow the link."
1510 :group 'org-link-follow
1511 :type 'boolean)
1513 (defcustom org-mouse-1-follows-link
1514 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1515 "Non-nil means mouse-1 on a link will follow the link.
1516 A longer mouse click will still set point. Does not work on XEmacs.
1517 Needs to be set before org.el is loaded."
1518 :group 'org-link-follow
1519 :type 'boolean)
1521 (defcustom org-mark-ring-length 4
1522 "Number of different positions to be recorded in the ring.
1523 Changing this requires a restart of Emacs to work correctly."
1524 :group 'org-link-follow
1525 :type 'integer)
1527 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1528 "Non-nil means internal links in Org files must exactly match a headline.
1529 When nil, the link search tries to match a phrase with all words
1530 in the search text."
1531 :group 'org-link-follow
1532 :version "24.1"
1533 :type '(choice
1534 (const :tag "Use fuzzy text search" nil)
1535 (const :tag "Match only exact headline" t)
1536 (const :tag "Match exact headline or query to create it"
1537 query-to-create)))
1539 (defcustom org-link-frame-setup
1540 '((vm . vm-visit-folder-other-frame)
1541 (vm-imap . vm-visit-imap-folder-other-frame)
1542 (gnus . org-gnus-no-new-news)
1543 (file . find-file-other-window)
1544 (wl . wl-other-frame))
1545 "Setup the frame configuration for following links.
1546 When following a link with Emacs, it may often be useful to display
1547 this link in another window or frame. This variable can be used to
1548 set this up for the different types of links.
1549 For VM, use any of
1550 `vm-visit-folder'
1551 `vm-visit-folder-other-window'
1552 `vm-visit-folder-other-frame'
1553 For Gnus, use any of
1554 `gnus'
1555 `gnus-other-frame'
1556 `org-gnus-no-new-news'
1557 For FILE, use any of
1558 `find-file'
1559 `find-file-other-window'
1560 `find-file-other-frame'
1561 For Wanderlust use any of
1562 `wl'
1563 `wl-other-frame'
1564 For the calendar, use the variable `calendar-setup'.
1565 For BBDB, it is currently only possible to display the matches in
1566 another window."
1567 :group 'org-link-follow
1568 :type '(list
1569 (cons (const vm)
1570 (choice
1571 (const vm-visit-folder)
1572 (const vm-visit-folder-other-window)
1573 (const vm-visit-folder-other-frame)))
1574 (cons (const gnus)
1575 (choice
1576 (const gnus)
1577 (const gnus-other-frame)
1578 (const org-gnus-no-new-news)))
1579 (cons (const file)
1580 (choice
1581 (const find-file)
1582 (const find-file-other-window)
1583 (const find-file-other-frame)))
1584 (cons (const wl)
1585 (choice
1586 (const wl)
1587 (const wl-other-frame)))))
1589 (defcustom org-display-internal-link-with-indirect-buffer nil
1590 "Non-nil means use indirect buffer to display infile links.
1591 Activating internal links (from one location in a file to another location
1592 in the same file) normally just jumps to the location. When the link is
1593 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1594 is displayed in
1595 another window. When this option is set, the other window actually displays
1596 an indirect buffer clone of the current buffer, to avoid any visibility
1597 changes to the current buffer."
1598 :group 'org-link-follow
1599 :type 'boolean)
1601 (defcustom org-open-non-existing-files nil
1602 "Non-nil means `org-open-file' will open non-existing files.
1603 When nil, an error will be generated.
1604 This variable applies only to external applications because they
1605 might choke on non-existing files. If the link is to a file that
1606 will be opened in Emacs, the variable is ignored."
1607 :group 'org-link-follow
1608 :type 'boolean)
1610 (defcustom org-open-directory-means-index-dot-org nil
1611 "Non-nil means a link to a directory really means to index.org.
1612 When nil, following a directory link will run dired or open a finder/explorer
1613 window on that directory."
1614 :group 'org-link-follow
1615 :type 'boolean)
1617 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1618 "Function and arguments to call for following mailto links.
1619 This is a list with the first element being a Lisp function, and the
1620 remaining elements being arguments to the function. In string arguments,
1621 %a will be replaced by the address, and %s will be replaced by the subject
1622 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1623 :group 'org-link-follow
1624 :type '(choice
1625 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1626 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1627 (const :tag "message-mail" (message-mail "%a" "%s"))
1628 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1630 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1631 "Non-nil means ask for confirmation before executing shell links.
1632 Shell links can be dangerous: just think about a link
1634 [[shell:rm -rf ~/*][Google Search]]
1636 This link would show up in your Org-mode document as \"Google Search\",
1637 but really it would remove your entire home directory.
1638 Therefore we advise against setting this variable to nil.
1639 Just change it to `y-or-n-p' if you want to confirm with a
1640 single keystroke rather than having to type \"yes\"."
1641 :group 'org-link-follow
1642 :type '(choice
1643 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1644 (const :tag "with y-or-n (faster)" y-or-n-p)
1645 (const :tag "no confirmation (dangerous)" nil)))
1646 (put 'org-confirm-shell-link-function
1647 'safe-local-variable
1648 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1650 (defcustom org-confirm-shell-link-not-regexp ""
1651 "A regexp to skip confirmation for shell links."
1652 :group 'org-link-follow
1653 :version "24.1"
1654 :type 'regexp)
1656 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1657 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1658 Elisp links can be dangerous: just think about a link
1660 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1662 This link would show up in your Org-mode document as \"Google Search\",
1663 but really it would remove your entire home directory.
1664 Therefore we advise against setting this variable to nil.
1665 Just change it to `y-or-n-p' if you want to confirm with a
1666 single keystroke rather than having to type \"yes\"."
1667 :group 'org-link-follow
1668 :type '(choice
1669 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1670 (const :tag "with y-or-n (faster)" y-or-n-p)
1671 (const :tag "no confirmation (dangerous)" nil)))
1672 (put 'org-confirm-shell-link-function
1673 'safe-local-variable
1674 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1676 (defcustom org-confirm-elisp-link-not-regexp ""
1677 "A regexp to skip confirmation for Elisp links."
1678 :group 'org-link-follow
1679 :version "24.1"
1680 :type 'regexp)
1682 (defconst org-file-apps-defaults-gnu
1683 '((remote . emacs)
1684 (system . mailcap)
1685 (t . mailcap))
1686 "Default file applications on a UNIX or GNU/Linux system.
1687 See `org-file-apps'.")
1689 (defconst org-file-apps-defaults-macosx
1690 '((remote . emacs)
1691 (t . "open %s")
1692 (system . "open %s")
1693 ("ps.gz" . "gv %s")
1694 ("eps.gz" . "gv %s")
1695 ("dvi" . "xdvi %s")
1696 ("fig" . "xfig %s"))
1697 "Default file applications on a MacOS X system.
1698 The system \"open\" is known as a default, but we use X11 applications
1699 for some files for which the OS does not have a good default.
1700 See `org-file-apps'.")
1702 (defconst org-file-apps-defaults-windowsnt
1703 (list
1704 '(remote . emacs)
1705 (cons t
1706 (list (if (featurep 'xemacs)
1707 'mswindows-shell-execute
1708 'w32-shell-execute)
1709 "open" 'file))
1710 (cons 'system
1711 (list (if (featurep 'xemacs)
1712 'mswindows-shell-execute
1713 'w32-shell-execute)
1714 "open" 'file)))
1715 "Default file applications on a Windows NT system.
1716 The system \"open\" is used for most files.
1717 See `org-file-apps'.")
1719 (defcustom org-file-apps
1721 (auto-mode . emacs)
1722 ("\\.mm\\'" . default)
1723 ("\\.x?html?\\'" . default)
1724 ("\\.pdf\\'" . default)
1726 "External applications for opening `file:path' items in a document.
1727 Org-mode uses system defaults for different file types, but
1728 you can use this variable to set the application for a given file
1729 extension. The entries in this list are cons cells where the car identifies
1730 files and the cdr the corresponding command. Possible values for the
1731 file identifier are
1732 \"string\" A string as a file identifier can be interpreted in different
1733 ways, depending on its contents:
1735 - Alphanumeric characters only:
1736 Match links with this file extension.
1737 Example: (\"pdf\" . \"evince %s\")
1738 to open PDFs with evince.
1740 - Regular expression: Match links where the
1741 filename matches the regexp. If you want to
1742 use groups here, use shy groups.
1744 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1745 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1746 to open *.html and *.xhtml with firefox.
1748 - Regular expression which contains (non-shy) groups:
1749 Match links where the whole link, including \"::\", and
1750 anything after that, matches the regexp.
1751 In a custom command string, %1, %2, etc. are replaced with
1752 the parts of the link that were matched by the groups.
1753 For backwards compatibility, if a command string is given
1754 that does not use any of the group matches, this case is
1755 handled identically to the second one (i.e. match against
1756 file name only).
1757 In a custom lisp form, you can access the group matches with
1758 (match-string n link).
1760 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1761 to open [[file:document.pdf::5]] with evince at page 5.
1763 `directory' Matches a directory
1764 `remote' Matches a remote file, accessible through tramp or efs.
1765 Remote files most likely should be visited through Emacs
1766 because external applications cannot handle such paths.
1767 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1768 so all files Emacs knows how to handle. Using this with
1769 command `emacs' will open most files in Emacs. Beware that this
1770 will also open html files inside Emacs, unless you add
1771 (\"html\" . default) to the list as well.
1772 t Default for files not matched by any of the other options.
1773 `system' The system command to open files, like `open' on Windows
1774 and Mac OS X, and mailcap under GNU/Linux. This is the command
1775 that will be selected if you call `C-c C-o' with a double
1776 \\[universal-argument] \\[universal-argument] prefix.
1778 Possible values for the command are:
1779 `emacs' The file will be visited by the current Emacs process.
1780 `default' Use the default application for this file type, which is the
1781 association for t in the list, most likely in the system-specific
1782 part.
1783 This can be used to overrule an unwanted setting in the
1784 system-specific variable.
1785 `system' Use the system command for opening files, like \"open\".
1786 This command is specified by the entry whose car is `system'.
1787 Most likely, the system-specific version of this variable
1788 does define this command, but you can overrule/replace it
1789 here.
1790 string A command to be executed by a shell; %s will be replaced
1791 by the path to the file.
1792 sexp A Lisp form which will be evaluated. The file path will
1793 be available in the Lisp variable `file'.
1794 For more examples, see the system specific constants
1795 `org-file-apps-defaults-macosx'
1796 `org-file-apps-defaults-windowsnt'
1797 `org-file-apps-defaults-gnu'."
1798 :group 'org-link-follow
1799 :type '(repeat
1800 (cons (choice :value ""
1801 (string :tag "Extension")
1802 (const :tag "System command to open files" system)
1803 (const :tag "Default for unrecognized files" t)
1804 (const :tag "Remote file" remote)
1805 (const :tag "Links to a directory" directory)
1806 (const :tag "Any files that have Emacs modes"
1807 auto-mode))
1808 (choice :value ""
1809 (const :tag "Visit with Emacs" emacs)
1810 (const :tag "Use default" default)
1811 (const :tag "Use the system command" system)
1812 (string :tag "Command")
1813 (sexp :tag "Lisp form")))))
1815 (defcustom org-doi-server-url "http://dx.doi.org/"
1816 "The URL of the DOI server."
1817 :type 'string
1818 ;; :version "24.3"
1819 :group 'org-link-follow)
1821 (defgroup org-refile nil
1822 "Options concerning refiling entries in Org-mode."
1823 :tag "Org Refile"
1824 :group 'org)
1826 (defcustom org-directory "~/org"
1827 "Directory with org files.
1828 This is just a default location to look for Org files. There is no need
1829 at all to put your files into this directory. It is only used in the
1830 following situations:
1832 1. When a capture template specifies a target file that is not an
1833 absolute path. The path will then be interpreted relative to
1834 `org-directory'
1835 2. When a capture note is filed away in an interactive way (when exiting the
1836 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1837 with `org-directory' as the default path."
1838 :group 'org-refile
1839 :group 'org-remember
1840 :group 'org-capture
1841 :type 'directory)
1843 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1844 "Default target for storing notes.
1845 Used as a fall back file for org-remember.el and org-capture.el, for
1846 templates that do not specify a target file."
1847 :group 'org-refile
1848 :group 'org-remember
1849 :group 'org-capture
1850 :type '(choice
1851 (const :tag "Default from remember-data-file" nil)
1852 file))
1854 (defcustom org-goto-interface 'outline
1855 "The default interface to be used for `org-goto'.
1856 Allowed values are:
1857 outline The interface shows an outline of the relevant file
1858 and the correct heading is found by moving through
1859 the outline or by searching with incremental search.
1860 outline-path-completion Headlines in the current buffer are offered via
1861 completion. This is the interface also used by
1862 the refile command."
1863 :group 'org-refile
1864 :type '(choice
1865 (const :tag "Outline" outline)
1866 (const :tag "Outline-path-completion" outline-path-completion)))
1868 (defcustom org-goto-max-level 5
1869 "Maximum target level when running `org-goto' with refile interface."
1870 :group 'org-refile
1871 :type 'integer)
1873 (defcustom org-reverse-note-order nil
1874 "Non-nil means store new notes at the beginning of a file or entry.
1875 When nil, new notes will be filed to the end of a file or entry.
1876 This can also be a list with cons cells of regular expressions that
1877 are matched against file names, and values."
1878 :group 'org-remember
1879 :group 'org-capture
1880 :group 'org-refile
1881 :type '(choice
1882 (const :tag "Reverse always" t)
1883 (const :tag "Reverse never" nil)
1884 (repeat :tag "By file name regexp"
1885 (cons regexp boolean))))
1887 (defcustom org-log-refile nil
1888 "Information to record when a task is refiled.
1890 Possible values are:
1892 nil Don't add anything
1893 time Add a time stamp to the task
1894 note Prompt for a note and add it with template `org-log-note-headings'
1896 This option can also be set with on a per-file-basis with
1898 #+STARTUP: nologrefile
1899 #+STARTUP: logrefile
1900 #+STARTUP: lognoterefile
1902 You can have local logging settings for a subtree by setting the LOGGING
1903 property to one or more of these keywords.
1905 When bulk-refiling from the agenda, the value `note' is forbidden and
1906 will temporarily be changed to `time'."
1907 :group 'org-refile
1908 :group 'org-progress
1909 :version "24.1"
1910 :type '(choice
1911 (const :tag "No logging" nil)
1912 (const :tag "Record timestamp" time)
1913 (const :tag "Record timestamp with note." note)))
1915 (defcustom org-refile-targets nil
1916 "Targets for refiling entries with \\[org-refile].
1917 This is a list of cons cells. Each cell contains:
1918 - a specification of the files to be considered, either a list of files,
1919 or a symbol whose function or variable value will be used to retrieve
1920 a file name or a list of file names. If you use `org-agenda-files' for
1921 that, all agenda files will be scanned for targets. Nil means consider
1922 headings in the current buffer.
1923 - A specification of how to find candidate refile targets. This may be
1924 any of:
1925 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1926 This tag has to be present in all target headlines, inheritance will
1927 not be considered.
1928 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1929 todo keyword.
1930 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1931 headlines that are refiling targets.
1932 - a cons cell (:level . N). Any headline of level N is considered a target.
1933 Note that, when `org-odd-levels-only' is set, level corresponds to
1934 order in hierarchy, not to the number of stars.
1935 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1936 Note that, when `org-odd-levels-only' is set, level corresponds to
1937 order in hierarchy, not to the number of stars.
1939 Each element of this list generates a set of possible targets.
1940 The union of these sets is presented (with completion) to
1941 the user by `org-refile'.
1943 You can set the variable `org-refile-target-verify-function' to a function
1944 to verify each headline found by the simple criteria above.
1946 When this variable is nil, all top-level headlines in the current buffer
1947 are used, equivalent to the value `((nil . (:level . 1))'."
1948 :group 'org-refile
1949 :type '(repeat
1950 (cons
1951 (choice :value org-agenda-files
1952 (const :tag "All agenda files" org-agenda-files)
1953 (const :tag "Current buffer" nil)
1954 (function) (variable) (file))
1955 (choice :tag "Identify target headline by"
1956 (cons :tag "Specific tag" (const :value :tag) (string))
1957 (cons :tag "TODO keyword" (const :value :todo) (string))
1958 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1959 (cons :tag "Level number" (const :value :level) (integer))
1960 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1962 (defcustom org-refile-target-verify-function nil
1963 "Function to verify if the headline at point should be a refile target.
1964 The function will be called without arguments, with point at the
1965 beginning of the headline. It should return t and leave point
1966 where it is if the headline is a valid target for refiling.
1968 If the target should not be selected, the function must return nil.
1969 In addition to this, it may move point to a place from where the search
1970 should be continued. For example, the function may decide that the entire
1971 subtree of the current entry should be excluded and move point to the end
1972 of the subtree."
1973 :group 'org-refile
1974 :type 'function)
1976 (defcustom org-refile-use-cache nil
1977 "Non-nil means cache refile targets to speed up the process.
1978 The cache for a particular file will be updated automatically when
1979 the buffer has been killed, or when any of the marker used for flagging
1980 refile targets no longer points at a live buffer.
1981 If you have added new entries to a buffer that might themselves be targets,
1982 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
1983 find that easier, `C-u C-u C-u C-c C-w'."
1984 :group 'org-refile
1985 :version "24.1"
1986 :type 'boolean)
1988 (defcustom org-refile-use-outline-path nil
1989 "Non-nil means provide refile targets as paths.
1990 So a level 3 headline will be available as level1/level2/level3.
1992 When the value is `file', also include the file name (without directory)
1993 into the path. In this case, you can also stop the completion after
1994 the file name, to get entries inserted as top level in the file.
1996 When `full-file-path', include the full file path."
1997 :group 'org-refile
1998 :type '(choice
1999 (const :tag "Not" nil)
2000 (const :tag "Yes" t)
2001 (const :tag "Start with file name" file)
2002 (const :tag "Start with full file path" full-file-path)))
2004 (defcustom org-outline-path-complete-in-steps t
2005 "Non-nil means complete the outline path in hierarchical steps.
2006 When Org-mode uses the refile interface to select an outline path
2007 \(see variable `org-refile-use-outline-path'), the completion of
2008 the path can be done is a single go, or if can be done in steps down
2009 the headline hierarchy. Going in steps is probably the best if you
2010 do not use a special completion package like `ido' or `icicles'.
2011 However, when using these packages, going in one step can be very
2012 fast, while still showing the whole path to the entry."
2013 :group 'org-refile
2014 :type 'boolean)
2016 (defcustom org-refile-allow-creating-parent-nodes nil
2017 "Non-nil means allow to create new nodes as refile targets.
2018 New nodes are then created by adding \"/new node name\" to the completion
2019 of an existing node. When the value of this variable is `confirm',
2020 new node creation must be confirmed by the user (recommended)
2021 When nil, the completion must match an existing entry.
2023 Note that, if the new heading is not seen by the criteria
2024 listed in `org-refile-targets', multiple instances of the same
2025 heading would be created by trying again to file under the new
2026 heading."
2027 :group 'org-refile
2028 :type '(choice
2029 (const :tag "Never" nil)
2030 (const :tag "Always" t)
2031 (const :tag "Prompt for confirmation" confirm)))
2033 (defcustom org-refile-active-region-within-subtree nil
2034 "Non-nil means also refile active region within a subtree.
2036 By default `org-refile' doesn't allow refiling regions if they
2037 don't contain a set of subtrees, but it might be convenient to
2038 do so sometimes: in that case, the first line of the region is
2039 converted to a headline before refiling."
2040 :group 'org-refile
2041 :version "24.1"
2042 :type 'boolean)
2044 (defgroup org-todo nil
2045 "Options concerning TODO items in Org-mode."
2046 :tag "Org TODO"
2047 :group 'org)
2049 (defgroup org-progress nil
2050 "Options concerning Progress logging in Org-mode."
2051 :tag "Org Progress"
2052 :group 'org-time)
2054 (defvar org-todo-interpretation-widgets
2055 '((:tag "Sequence (cycling hits every state)" sequence)
2056 (:tag "Type (cycling directly to DONE)" type))
2057 "The available interpretation symbols for customizing `org-todo-keywords'.
2058 Interested libraries should add to this list.")
2060 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2061 "List of TODO entry keyword sequences and their interpretation.
2062 \\<org-mode-map>This is a list of sequences.
2064 Each sequence starts with a symbol, either `sequence' or `type',
2065 indicating if the keywords should be interpreted as a sequence of
2066 action steps, or as different types of TODO items. The first
2067 keywords are states requiring action - these states will select a headline
2068 for inclusion into the global TODO list Org-mode produces. If one of
2069 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2070 signify that no further action is necessary. If \"|\" is not found,
2071 the last keyword is treated as the only DONE state of the sequence.
2073 The command \\[org-todo] cycles an entry through these states, and one
2074 additional state where no keyword is present. For details about this
2075 cycling, see the manual.
2077 TODO keywords and interpretation can also be set on a per-file basis with
2078 the special #+SEQ_TODO and #+TYP_TODO lines.
2080 Each keyword can optionally specify a character for fast state selection
2081 \(in combination with the variable `org-use-fast-todo-selection')
2082 and specifiers for state change logging, using the same syntax that
2083 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2084 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2085 indicates to record a time stamp each time this state is selected.
2087 Each keyword may also specify if a timestamp or a note should be
2088 recorded when entering or leaving the state, by adding additional
2089 characters in the parenthesis after the keyword. This looks like this:
2090 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2091 record only the time of the state change. With X and Y being either
2092 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2093 Y when leaving the state if and only if the *target* state does not
2094 define X. You may omit any of the fast-selection key or X or /Y,
2095 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2097 For backward compatibility, this variable may also be just a list
2098 of keywords. In this case the interpretation (sequence or type) will be
2099 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2100 :group 'org-todo
2101 :group 'org-keywords
2102 :type '(choice
2103 (repeat :tag "Old syntax, just keywords"
2104 (string :tag "Keyword"))
2105 (repeat :tag "New syntax"
2106 (cons
2107 (choice
2108 :tag "Interpretation"
2109 ;;Quick and dirty way to see
2110 ;;`org-todo-interpretations'. This takes the
2111 ;;place of item arguments
2112 :convert-widget
2113 (lambda (widget)
2114 (widget-put widget
2115 :args (mapcar
2116 #'(lambda (x)
2117 (widget-convert
2118 (cons 'const x)))
2119 org-todo-interpretation-widgets))
2120 widget))
2121 (repeat
2122 (string :tag "Keyword"))))))
2124 (defvar org-todo-keywords-1 nil
2125 "All TODO and DONE keywords active in a buffer.")
2126 (make-variable-buffer-local 'org-todo-keywords-1)
2127 (defvar org-todo-keywords-for-agenda nil)
2128 (defvar org-done-keywords-for-agenda nil)
2129 (defvar org-drawers-for-agenda nil)
2130 (defvar org-todo-keyword-alist-for-agenda nil)
2131 (defvar org-tag-alist-for-agenda nil)
2132 (defvar org-agenda-contributing-files nil)
2133 (defvar org-not-done-keywords nil)
2134 (make-variable-buffer-local 'org-not-done-keywords)
2135 (defvar org-done-keywords nil)
2136 (make-variable-buffer-local 'org-done-keywords)
2137 (defvar org-todo-heads nil)
2138 (make-variable-buffer-local 'org-todo-heads)
2139 (defvar org-todo-sets nil)
2140 (make-variable-buffer-local 'org-todo-sets)
2141 (defvar org-todo-log-states nil)
2142 (make-variable-buffer-local 'org-todo-log-states)
2143 (defvar org-todo-kwd-alist nil)
2144 (make-variable-buffer-local 'org-todo-kwd-alist)
2145 (defvar org-todo-key-alist nil)
2146 (make-variable-buffer-local 'org-todo-key-alist)
2147 (defvar org-todo-key-trigger nil)
2148 (make-variable-buffer-local 'org-todo-key-trigger)
2150 (defcustom org-todo-interpretation 'sequence
2151 "Controls how TODO keywords are interpreted.
2152 This variable is in principle obsolete and is only used for
2153 backward compatibility, if the interpretation of todo keywords is
2154 not given already in `org-todo-keywords'. See that variable for
2155 more information."
2156 :group 'org-todo
2157 :group 'org-keywords
2158 :type '(choice (const sequence)
2159 (const type)))
2161 (defcustom org-use-fast-todo-selection t
2162 "Non-nil means use the fast todo selection scheme with C-c C-t.
2163 This variable describes if and under what circumstances the cycling
2164 mechanism for TODO keywords will be replaced by a single-key, direct
2165 selection scheme.
2167 When nil, fast selection is never used.
2169 When the symbol `prefix', it will be used when `org-todo' is called
2170 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2171 `C-u t' in an agenda buffer.
2173 When t, fast selection is used by default. In this case, the prefix
2174 argument forces cycling instead.
2176 In all cases, the special interface is only used if access keys have
2177 actually been assigned by the user, i.e. if keywords in the configuration
2178 are followed by a letter in parenthesis, like TODO(t)."
2179 :group 'org-todo
2180 :type '(choice
2181 (const :tag "Never" nil)
2182 (const :tag "By default" t)
2183 (const :tag "Only with C-u C-c C-t" prefix)))
2185 (defcustom org-provide-todo-statistics t
2186 "Non-nil means update todo statistics after insert and toggle.
2187 ALL-HEADLINES means update todo statistics by including headlines
2188 with no TODO keyword as well, counting them as not done.
2189 A list of TODO keywords means the same, but skip keywords that are
2190 not in this list.
2192 When this is set, todo statistics is updated in the parent of the
2193 current entry each time a todo state is changed."
2194 :group 'org-todo
2195 :type '(choice
2196 (const :tag "Yes, only for TODO entries" t)
2197 (const :tag "Yes, including all entries" 'all-headlines)
2198 (repeat :tag "Yes, for TODOs in this list"
2199 (string :tag "TODO keyword"))
2200 (other :tag "No TODO statistics" nil)))
2202 (defcustom org-hierarchical-todo-statistics t
2203 "Non-nil means TODO statistics covers just direct children.
2204 When nil, all entries in the subtree are considered.
2205 This has only an effect if `org-provide-todo-statistics' is set.
2206 To set this to nil for only a single subtree, use a COOKIE_DATA
2207 property and include the word \"recursive\" into the value."
2208 :group 'org-todo
2209 :type 'boolean)
2211 (defcustom org-after-todo-state-change-hook nil
2212 "Hook which is run after the state of a TODO item was changed.
2213 The new state (a string with a TODO keyword, or nil) is available in the
2214 Lisp variable `org-state'."
2215 :group 'org-todo
2216 :type 'hook)
2218 (defvar org-blocker-hook nil
2219 "Hook for functions that are allowed to block a state change.
2221 Each function gets as its single argument a property list, see
2222 `org-trigger-hook' for more information about this list.
2224 If any of the functions in this hook returns nil, the state change
2225 is blocked.")
2227 (defvar org-trigger-hook nil
2228 "Hook for functions that are triggered by a state change.
2230 Each function gets as its single argument a property list with at least
2231 the following elements:
2233 (:type type-of-change :position pos-at-entry-start
2234 :from old-state :to new-state)
2236 Depending on the type, more properties may be present.
2238 This mechanism is currently implemented for:
2240 TODO state changes
2241 ------------------
2242 :type todo-state-change
2243 :from previous state (keyword as a string), or nil, or a symbol
2244 'todo' or 'done', to indicate the general type of state.
2245 :to new state, like in :from")
2247 (defcustom org-enforce-todo-dependencies nil
2248 "Non-nil means undone TODO entries will block switching the parent to DONE.
2249 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2250 be blocked if any prior sibling is not yet done.
2251 Finally, if the parent is blocked because of ordered siblings of its own,
2252 the child will also be blocked."
2253 :set (lambda (var val)
2254 (set var val)
2255 (if val
2256 (add-hook 'org-blocker-hook
2257 'org-block-todo-from-children-or-siblings-or-parent)
2258 (remove-hook 'org-blocker-hook
2259 'org-block-todo-from-children-or-siblings-or-parent)))
2260 :group 'org-todo
2261 :type 'boolean)
2263 (defcustom org-enforce-todo-checkbox-dependencies nil
2264 "Non-nil means unchecked boxes will block switching the parent to DONE.
2265 When this is nil, checkboxes have no influence on switching TODO states.
2266 When non-nil, you first need to check off all check boxes before the TODO
2267 entry can be switched to DONE.
2268 This variable needs to be set before org.el is loaded, and you need to
2269 restart Emacs after a change to make the change effective. The only way
2270 to change is while Emacs is running is through the customize interface."
2271 :set (lambda (var val)
2272 (set var val)
2273 (if val
2274 (add-hook 'org-blocker-hook
2275 'org-block-todo-from-checkboxes)
2276 (remove-hook 'org-blocker-hook
2277 'org-block-todo-from-checkboxes)))
2278 :group 'org-todo
2279 :type 'boolean)
2281 (defcustom org-treat-insert-todo-heading-as-state-change nil
2282 "Non-nil means inserting a TODO heading is treated as state change.
2283 So when the command \\[org-insert-todo-heading] is used, state change
2284 logging will apply if appropriate. When nil, the new TODO item will
2285 be inserted directly, and no logging will take place."
2286 :group 'org-todo
2287 :type 'boolean)
2289 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2290 "Non-nil means switching TODO states with S-cursor counts as state change.
2291 This is the default behavior. However, setting this to nil allows a
2292 convenient way to select a TODO state and bypass any logging associated
2293 with that."
2294 :group 'org-todo
2295 :type 'boolean)
2297 (defcustom org-todo-state-tags-triggers nil
2298 "Tag changes that should be triggered by TODO state changes.
2299 This is a list. Each entry is
2301 (state-change (tag . flag) .......)
2303 State-change can be a string with a state, and empty string to indicate the
2304 state that has no TODO keyword, or it can be one of the symbols `todo'
2305 or `done', meaning any not-done or done state, respectively."
2306 :group 'org-todo
2307 :group 'org-tags
2308 :type '(repeat
2309 (cons (choice :tag "When changing to"
2310 (const :tag "Not-done state" todo)
2311 (const :tag "Done state" done)
2312 (string :tag "State"))
2313 (repeat
2314 (cons :tag "Tag action"
2315 (string :tag "Tag")
2316 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2318 (defcustom org-log-done nil
2319 "Information to record when a task moves to the DONE state.
2321 Possible values are:
2323 nil Don't add anything, just change the keyword
2324 time Add a time stamp to the task
2325 note Prompt for a note and add it with template `org-log-note-headings'
2327 This option can also be set with on a per-file-basis with
2329 #+STARTUP: nologdone
2330 #+STARTUP: logdone
2331 #+STARTUP: lognotedone
2333 You can have local logging settings for a subtree by setting the LOGGING
2334 property to one or more of these keywords."
2335 :group 'org-todo
2336 :group 'org-progress
2337 :type '(choice
2338 (const :tag "No logging" nil)
2339 (const :tag "Record CLOSED timestamp" time)
2340 (const :tag "Record CLOSED timestamp with note." note)))
2342 ;; Normalize old uses of org-log-done.
2343 (cond
2344 ((eq org-log-done t) (setq org-log-done 'time))
2345 ((and (listp org-log-done) (memq 'done org-log-done))
2346 (setq org-log-done 'note)))
2348 (defcustom org-log-reschedule nil
2349 "Information to record when the scheduling date of a tasks is modified.
2351 Possible values are:
2353 nil Don't add anything, just change the date
2354 time Add a time stamp to the task
2355 note Prompt for a note and add it with template `org-log-note-headings'
2357 This option can also be set with on a per-file-basis with
2359 #+STARTUP: nologreschedule
2360 #+STARTUP: logreschedule
2361 #+STARTUP: lognotereschedule"
2362 :group 'org-todo
2363 :group 'org-progress
2364 :type '(choice
2365 (const :tag "No logging" nil)
2366 (const :tag "Record timestamp" time)
2367 (const :tag "Record timestamp with note." note)))
2369 (defcustom org-log-redeadline nil
2370 "Information to record when the deadline date of a tasks is modified.
2372 Possible values are:
2374 nil Don't add anything, just change the date
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologredeadline
2381 #+STARTUP: logredeadline
2382 #+STARTUP: lognoteredeadline
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords."
2386 :group 'org-todo
2387 :group 'org-progress
2388 :type '(choice
2389 (const :tag "No logging" nil)
2390 (const :tag "Record timestamp" time)
2391 (const :tag "Record timestamp with note." note)))
2393 (defcustom org-log-note-clock-out nil
2394 "Non-nil means record a note when clocking out of an item.
2395 This can also be configured on a per-file basis by adding one of
2396 the following lines anywhere in the buffer:
2398 #+STARTUP: lognoteclock-out
2399 #+STARTUP: nolognoteclock-out"
2400 :group 'org-todo
2401 :group 'org-progress
2402 :type 'boolean)
2404 (defcustom org-log-done-with-time t
2405 "Non-nil means the CLOSED time stamp will contain date and time.
2406 When nil, only the date will be recorded."
2407 :group 'org-progress
2408 :type 'boolean)
2410 (defcustom org-log-note-headings
2411 '((done . "CLOSING NOTE %t")
2412 (state . "State %-12s from %-12S %t")
2413 (note . "Note taken on %t")
2414 (reschedule . "Rescheduled from %S on %t")
2415 (delschedule . "Not scheduled, was %S on %t")
2416 (redeadline . "New deadline from %S on %t")
2417 (deldeadline . "Removed deadline, was %S on %t")
2418 (refile . "Refiled on %t")
2419 (clock-out . ""))
2420 "Headings for notes added to entries.
2421 The value is an alist, with the car being a symbol indicating the note
2422 context, and the cdr is the heading to be used. The heading may also be the
2423 empty string.
2424 %t in the heading will be replaced by a time stamp.
2425 %T will be an active time stamp instead the default inactive one
2426 %d will be replaced by a short-format time stamp.
2427 %D will be replaced by an active short-format time stamp.
2428 %s will be replaced by the new TODO state, in double quotes.
2429 %S will be replaced by the old TODO state, in double quotes.
2430 %u will be replaced by the user name.
2431 %U will be replaced by the full user name.
2433 In fact, it is not a good idea to change the `state' entry, because
2434 agenda log mode depends on the format of these entries."
2435 :group 'org-todo
2436 :group 'org-progress
2437 :type '(list :greedy t
2438 (cons (const :tag "Heading when closing an item" done) string)
2439 (cons (const :tag
2440 "Heading when changing todo state (todo sequence only)"
2441 state) string)
2442 (cons (const :tag "Heading when just taking a note" note) string)
2443 (cons (const :tag "Heading when clocking out" clock-out) string)
2444 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2445 (cons (const :tag "Heading when rescheduling" reschedule) string)
2446 (cons (const :tag "Heading when changing deadline" redeadline) string)
2447 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2448 (cons (const :tag "Heading when refiling" refile) string)))
2450 (unless (assq 'note org-log-note-headings)
2451 (push '(note . "%t") org-log-note-headings))
2453 (defcustom org-log-into-drawer nil
2454 "Non-nil means insert state change notes and time stamps into a drawer.
2455 When nil, state changes notes will be inserted after the headline and
2456 any scheduling and clock lines, but not inside a drawer.
2458 The value of this variable should be the name of the drawer to use.
2459 LOGBOOK is proposed as the default drawer for this purpose, you can
2460 also set this to a string to define the drawer of your choice.
2462 A value of t is also allowed, representing \"LOGBOOK\".
2464 If this variable is set, `org-log-state-notes-insert-after-drawers'
2465 will be ignored.
2467 You can set the property LOG_INTO_DRAWER to overrule this setting for
2468 a subtree."
2469 :group 'org-todo
2470 :group 'org-progress
2471 :type '(choice
2472 (const :tag "Not into a drawer" nil)
2473 (const :tag "LOGBOOK" t)
2474 (string :tag "Other")))
2476 (if (fboundp 'defvaralias)
2477 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2479 (defun org-log-into-drawer ()
2480 "Return the value of `org-log-into-drawer', but let properties overrule.
2481 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2482 used instead of the default value."
2483 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
2484 (cond
2485 ((or (not p) (equal p "nil")) org-log-into-drawer)
2486 ((equal p "t") "LOGBOOK")
2487 (t p))))
2489 (defcustom org-log-state-notes-insert-after-drawers nil
2490 "Non-nil means insert state change notes after any drawers in entry.
2491 Only the drawers that *immediately* follow the headline and the
2492 deadline/scheduled line are skipped.
2493 When nil, insert notes right after the heading and perhaps the line
2494 with deadline/scheduling if present.
2496 This variable will have no effect if `org-log-into-drawer' is
2497 set."
2498 :group 'org-todo
2499 :group 'org-progress
2500 :type 'boolean)
2502 (defcustom org-log-states-order-reversed t
2503 "Non-nil means the latest state note will be directly after heading.
2504 When nil, the state change notes will be ordered according to time."
2505 :group 'org-todo
2506 :group 'org-progress
2507 :type 'boolean)
2509 (defcustom org-todo-repeat-to-state nil
2510 "The TODO state to which a repeater should return the repeating task.
2511 By default this is the first task in a TODO sequence, or the previous state
2512 in a TODO_TYP set. But you can specify another task here.
2513 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2514 :group 'org-todo
2515 :version "24.1"
2516 :type '(choice (const :tag "Head of sequence" nil)
2517 (string :tag "Specific state")))
2519 (defcustom org-log-repeat 'time
2520 "Non-nil means record moving through the DONE state when triggering repeat.
2521 An auto-repeating task is immediately switched back to TODO when
2522 marked DONE. If you are not logging state changes (by adding \"@\"
2523 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2524 record a closing note, there will be no record of the task moving
2525 through DONE. This variable forces taking a note anyway.
2527 nil Don't force a record
2528 time Record a time stamp
2529 note Prompt for a note and add it with template `org-log-note-headings'
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: nologrepeat
2534 #+STARTUP: logrepeat
2535 #+STARTUP: lognoterepeat
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2539 :group 'org-todo
2540 :group 'org-progress
2541 :type '(choice
2542 (const :tag "Don't force a record" nil)
2543 (const :tag "Force recording the DONE state" time)
2544 (const :tag "Force recording a note with the DONE state" note)))
2547 (defgroup org-priorities nil
2548 "Priorities in Org-mode."
2549 :tag "Org Priorities"
2550 :group 'org-todo)
2552 (defcustom org-enable-priority-commands t
2553 "Non-nil means priority commands are active.
2554 When nil, these commands will be disabled, so that you never accidentally
2555 set a priority."
2556 :group 'org-priorities
2557 :type 'boolean)
2559 (defcustom org-highest-priority ?A
2560 "The highest priority of TODO items. A character like ?A, ?B etc.
2561 Must have a smaller ASCII number than `org-lowest-priority'."
2562 :group 'org-priorities
2563 :type 'character)
2565 (defcustom org-lowest-priority ?C
2566 "The lowest priority of TODO items. A character like ?A, ?B etc.
2567 Must have a larger ASCII number than `org-highest-priority'."
2568 :group 'org-priorities
2569 :type 'character)
2571 (defcustom org-default-priority ?B
2572 "The default priority of TODO items.
2573 This is the priority an item gets if no explicit priority is given.
2574 When starting to cycle on an empty priority the first step in the cycle
2575 depends on `org-priority-start-cycle-with-default'. The resulting first
2576 step priority must not exceed the range from `org-highest-priority' to
2577 `org-lowest-priority' which means that `org-default-priority' has to be
2578 in this range exclusive or inclusive the range boundaries. Else the
2579 first step refuses to set the default and the second will fall back
2580 to (depending on the command used) the highest or lowest priority."
2581 :group 'org-priorities
2582 :type 'character)
2584 (defcustom org-priority-start-cycle-with-default t
2585 "Non-nil means start with default priority when starting to cycle.
2586 When this is nil, the first step in the cycle will be (depending on the
2587 command used) one higher or lower than the default priority.
2588 See also `org-default-priority'."
2589 :group 'org-priorities
2590 :type 'boolean)
2592 (defcustom org-get-priority-function nil
2593 "Function to extract the priority from a string.
2594 The string is normally the headline. If this is nil Org computes the
2595 priority from the priority cookie like [#A] in the headline. It returns
2596 an integer, increasing by 1000 for each priority level.
2597 The user can set a different function here, which should take a string
2598 as an argument and return the numeric priority."
2599 :group 'org-priorities
2600 :version "24.1"
2601 :type 'function)
2603 (defgroup org-time nil
2604 "Options concerning time stamps and deadlines in Org-mode."
2605 :tag "Org Time"
2606 :group 'org)
2608 (defcustom org-insert-labeled-timestamps-at-point nil
2609 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2610 When nil, these labeled time stamps are forces into the second line of an
2611 entry, just after the headline. When scheduling from the global TODO list,
2612 the time stamp will always be forced into the second line."
2613 :group 'org-time
2614 :type 'boolean)
2616 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2617 "Formats for `format-time-string' which are used for time stamps.
2618 It is not recommended to change this constant.")
2620 (defcustom org-time-stamp-rounding-minutes '(0 5)
2621 "Number of minutes to round time stamps to.
2622 These are two values, the first applies when first creating a time stamp.
2623 The second applies when changing it with the commands `S-up' and `S-down'.
2624 When changing the time stamp, this means that it will change in steps
2625 of N minutes, as given by the second value.
2627 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2628 numbers should be factors of 60, so for example 5, 10, 15.
2630 When this is larger than 1, you can still force an exact time stamp by using
2631 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2632 and by using a prefix arg to `S-up/down' to specify the exact number
2633 of minutes to shift."
2634 :group 'org-time
2635 :get #'(lambda (var) ; Make sure both elements are there
2636 (if (integerp (default-value var))
2637 (list (default-value var) 5)
2638 (default-value var)))
2639 :type '(list
2640 (integer :tag "when inserting times")
2641 (integer :tag "when modifying times")))
2643 ;; Normalize old customizations of this variable.
2644 (when (integerp org-time-stamp-rounding-minutes)
2645 (setq org-time-stamp-rounding-minutes
2646 (list org-time-stamp-rounding-minutes
2647 org-time-stamp-rounding-minutes)))
2649 (defcustom org-display-custom-times nil
2650 "Non-nil means overlay custom formats over all time stamps.
2651 The formats are defined through the variable `org-time-stamp-custom-formats'.
2652 To turn this on on a per-file basis, insert anywhere in the file:
2653 #+STARTUP: customtime"
2654 :group 'org-time
2655 :set 'set-default
2656 :type 'sexp)
2657 (make-variable-buffer-local 'org-display-custom-times)
2659 (defcustom org-time-stamp-custom-formats
2660 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2661 "Custom formats for time stamps. See `format-time-string' for the syntax.
2662 These are overlaid over the default ISO format if the variable
2663 `org-display-custom-times' is set. Time like %H:%M should be at the
2664 end of the second format. The custom formats are also honored by export
2665 commands, if custom time display is turned on at the time of export."
2666 :group 'org-time
2667 :type 'sexp)
2669 (defun org-time-stamp-format (&optional long inactive)
2670 "Get the right format for a time string."
2671 (let ((f (if long (cdr org-time-stamp-formats)
2672 (car org-time-stamp-formats))))
2673 (if inactive
2674 (concat "[" (substring f 1 -1) "]")
2675 f)))
2677 (defcustom org-time-clocksum-format "%d:%02d"
2678 "The format string used when creating CLOCKSUM lines.
2679 This is also used when org-mode generates a time duration."
2680 :group 'org-time
2681 :type 'string)
2683 (defcustom org-time-clocksum-use-fractional nil
2684 "If non-nil, \\[org-clock-display] uses fractional times.
2685 org-mode generates a time duration."
2686 :group 'org-time
2687 :type 'boolean)
2689 (defcustom org-time-clocksum-fractional-format "%.2f"
2690 "The format string used when creating CLOCKSUM lines, or when
2691 org-mode generates a time duration."
2692 :group 'org-time
2693 :type 'string)
2695 (defcustom org-deadline-warning-days 14
2696 "No. of days before expiration during which a deadline becomes active.
2697 This variable governs the display in sparse trees and in the agenda.
2698 When 0 or negative, it means use this number (the absolute value of it)
2699 even if a deadline has a different individual lead time specified.
2701 Custom commands can set this variable in the options section."
2702 :group 'org-time
2703 :group 'org-agenda-daily/weekly
2704 :type 'integer)
2706 (defcustom org-read-date-prefer-future t
2707 "Non-nil means assume future for incomplete date input from user.
2708 This affects the following situations:
2709 1. The user gives a month but not a year.
2710 For example, if it is April and you enter \"feb 2\", this will be read
2711 as Feb 2, *next* year. \"May 5\", however, will be this year.
2712 2. The user gives a day, but no month.
2713 For example, if today is the 15th, and you enter \"3\", Org-mode will
2714 read this as the third of *next* month. However, if you enter \"17\",
2715 it will be considered as *this* month.
2717 If you set this variable to the symbol `time', then also the following
2718 will work:
2720 3. If the user gives a time.
2721 If the time is before now, it will be interpreted as tomorrow.
2723 Currently none of this works for ISO week specifications.
2725 When this option is nil, the current day, month and year will always be
2726 used as defaults.
2728 See also `org-agenda-jump-prefer-future'."
2729 :group 'org-time
2730 :type '(choice
2731 (const :tag "Never" nil)
2732 (const :tag "Check month and day" t)
2733 (const :tag "Check month, day, and time" time)))
2735 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2736 "Should the agenda jump command prefer the future for incomplete dates?
2737 The default is to do the same as configured in `org-read-date-prefer-future'.
2738 But you can also set a deviating value here.
2739 This may t or nil, or the symbol `org-read-date-prefer-future'."
2740 :group 'org-agenda
2741 :group 'org-time
2742 :version "24.1"
2743 :type '(choice
2744 (const :tag "Use org-read-date-prefer-future"
2745 org-read-date-prefer-future)
2746 (const :tag "Never" nil)
2747 (const :tag "Always" t)))
2749 (defcustom org-read-date-force-compatible-dates t
2750 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2752 Depending on the system Emacs is running on, certain dates cannot
2753 be represented with the type used internally to represent time.
2754 Dates between 1970-1-1 and 2038-1-1 can always be represented
2755 correctly. Some systems allow for earlier dates, some for later,
2756 some for both. One way to find out it to insert any date into an
2757 Org buffer, putting the cursor on the year and hitting S-up and
2758 S-down to test the range.
2760 When this variable is set to t, the date/time prompt will not let
2761 you specify dates outside the 1970-2037 range, so it is certain that
2762 these dates will work in whatever version of Emacs you are
2763 running, and also that you can move a file from one Emacs implementation
2764 to another. WHenever Org is forcing the year for you, it will display
2765 a message and beep.
2767 When this variable is nil, Org will check if the date is
2768 representable in the specific Emacs implementation you are using.
2769 If not, it will force a year, usually the current year, and beep
2770 to remind you. Currently this setting is not recommended because
2771 the likelihood that you will open your Org files in an Emacs that
2772 has limited date range is not negligible.
2774 A workaround for this problem is to use diary sexp dates for time
2775 stamps outside of this range."
2776 :group 'org-time
2777 :version "24.1"
2778 :type 'boolean)
2780 (defcustom org-read-date-display-live t
2781 "Non-nil means display current interpretation of date prompt live.
2782 This display will be in an overlay, in the minibuffer."
2783 :group 'org-time
2784 :type 'boolean)
2786 (defcustom org-read-date-popup-calendar t
2787 "Non-nil means pop up a calendar when prompting for a date.
2788 In the calendar, the date can be selected with mouse-1. However, the
2789 minibuffer will also be active, and you can simply enter the date as well.
2790 When nil, only the minibuffer will be available."
2791 :group 'org-time
2792 :type 'boolean)
2793 (if (fboundp 'defvaralias)
2794 (defvaralias 'org-popup-calendar-for-date-prompt
2795 'org-read-date-popup-calendar))
2797 (defcustom org-read-date-minibuffer-setup-hook nil
2798 "Hook to be used to set up keys for the date/time interface.
2799 Add key definitions to `minibuffer-local-map', which will be a temporary
2800 copy."
2801 :group 'org-time
2802 :type 'hook)
2804 (defcustom org-extend-today-until 0
2805 "The hour when your day really ends. Must be an integer.
2806 This has influence for the following applications:
2807 - When switching the agenda to \"today\". It it is still earlier than
2808 the time given here, the day recognized as TODAY is actually yesterday.
2809 - When a date is read from the user and it is still before the time given
2810 here, the current date and time will be assumed to be yesterday, 23:59.
2811 Also, timestamps inserted in capture templates follow this rule.
2813 IMPORTANT: This is a feature whose implementation is and likely will
2814 remain incomplete. Really, it is only here because past midnight seems to
2815 be the favorite working time of John Wiegley :-)"
2816 :group 'org-time
2817 :type 'integer)
2819 (defcustom org-use-effective-time nil
2820 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2821 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2822 \"effective time\" of any timestamps between midnight and 8am will be
2823 23:59 of the previous day."
2824 :group 'org-time
2825 :version "24.1"
2826 :type 'boolean)
2828 (defcustom org-edit-timestamp-down-means-later nil
2829 "Non-nil means S-down will increase the time in a time stamp.
2830 When nil, S-up will increase."
2831 :group 'org-time
2832 :type 'boolean)
2834 (defcustom org-calendar-follow-timestamp-change t
2835 "Non-nil means make the calendar window follow timestamp changes.
2836 When a timestamp is modified and the calendar window is visible, it will be
2837 moved to the new date."
2838 :group 'org-time
2839 :type 'boolean)
2841 (defgroup org-tags nil
2842 "Options concerning tags in Org-mode."
2843 :tag "Org Tags"
2844 :group 'org)
2846 (defcustom org-tag-alist nil
2847 "List of tags allowed in Org-mode files.
2848 When this list is nil, Org-mode will base TAG input on what is already in the
2849 buffer.
2850 The value of this variable is an alist, the car of each entry must be a
2851 keyword as a string, the cdr may be a character that is used to select
2852 that tag through the fast-tag-selection interface.
2853 See the manual for details."
2854 :group 'org-tags
2855 :type '(repeat
2856 (choice
2857 (cons (string :tag "Tag name")
2858 (character :tag "Access char"))
2859 (list :tag "Start radio group"
2860 (const :startgroup)
2861 (option (string :tag "Group description")))
2862 (list :tag "End radio group"
2863 (const :endgroup)
2864 (option (string :tag "Group description")))
2865 (const :tag "New line" (:newline)))))
2867 (defcustom org-tag-persistent-alist nil
2868 "List of tags that will always appear in all Org-mode files.
2869 This is in addition to any in buffer settings or customizations
2870 of `org-tag-alist'.
2871 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2872 The value of this variable is an alist, the car of each entry must be a
2873 keyword as a string, the cdr may be a character that is used to select
2874 that tag through the fast-tag-selection interface.
2875 See the manual for details.
2876 To disable these tags on a per-file basis, insert anywhere in the file:
2877 #+STARTUP: noptag"
2878 :group 'org-tags
2879 :type '(repeat
2880 (choice
2881 (cons (string :tag "Tag name")
2882 (character :tag "Access char"))
2883 (const :tag "Start radio group" (:startgroup))
2884 (const :tag "End radio group" (:endgroup))
2885 (const :tag "New line" (:newline)))))
2887 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2888 "If non-nil, always offer completion for all tags of all agenda files.
2889 Instead of customizing this variable directly, you might want to
2890 set it locally for capture buffers, because there no list of
2891 tags in that file can be created dynamically (there are none).
2893 (add-hook 'org-capture-mode-hook
2894 (lambda ()
2895 (set (make-local-variable
2896 'org-complete-tags-always-offer-all-agenda-tags)
2897 t)))"
2898 :group 'org-tags
2899 :version "24.1"
2900 :type 'boolean)
2902 (defvar org-file-tags nil
2903 "List of tags that can be inherited by all entries in the file.
2904 The tags will be inherited if the variable `org-use-tag-inheritance'
2905 says they should be.
2906 This variable is populated from #+FILETAGS lines.")
2908 (defcustom org-use-fast-tag-selection 'auto
2909 "Non-nil means use fast tag selection scheme.
2910 This is a special interface to select and deselect tags with single keys.
2911 When nil, fast selection is never used.
2912 When the symbol `auto', fast selection is used if and only if selection
2913 characters for tags have been configured, either through the variable
2914 `org-tag-alist' or through a #+TAGS line in the buffer.
2915 When t, fast selection is always used and selection keys are assigned
2916 automatically if necessary."
2917 :group 'org-tags
2918 :type '(choice
2919 (const :tag "Always" t)
2920 (const :tag "Never" nil)
2921 (const :tag "When selection characters are configured" 'auto)))
2923 (defcustom org-fast-tag-selection-single-key nil
2924 "Non-nil means fast tag selection exits after first change.
2925 When nil, you have to press RET to exit it.
2926 During fast tag selection, you can toggle this flag with `C-c'.
2927 This variable can also have the value `expert'. In this case, the window
2928 displaying the tags menu is not even shown, until you press C-c again."
2929 :group 'org-tags
2930 :type '(choice
2931 (const :tag "No" nil)
2932 (const :tag "Yes" t)
2933 (const :tag "Expert" expert)))
2935 (defvar org-fast-tag-selection-include-todo nil
2936 "Non-nil means fast tags selection interface will also offer TODO states.
2937 This is an undocumented feature, you should not rely on it.")
2939 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2940 "The column to which tags should be indented in a headline.
2941 If this number is positive, it specifies the column. If it is negative,
2942 it means that the tags should be flushright to that column. For example,
2943 -80 works well for a normal 80 character screen.
2944 When 0, place tags directly after headline text, with only one space in
2945 between."
2946 :group 'org-tags
2947 :type 'integer)
2949 (defcustom org-auto-align-tags t
2950 "Non-nil keeps tags aligned when modifying headlines.
2951 Some operations (i.e. demoting) change the length of a headline and
2952 therefore shift the tags around. With this option turned on, after
2953 each such operation the tags are again aligned to `org-tags-column'."
2954 :group 'org-tags
2955 :type 'boolean)
2957 (defcustom org-use-tag-inheritance t
2958 "Non-nil means tags in levels apply also for sublevels.
2959 When nil, only the tags directly given in a specific line apply there.
2960 This may also be a list of tags that should be inherited, or a regexp that
2961 matches tags that should be inherited. Additional control is possible
2962 with the variable `org-tags-exclude-from-inheritance' which gives an
2963 explicit list of tags to be excluded from inheritance., even if the value of
2964 `org-use-tag-inheritance' would select it for inheritance.
2966 If this option is t, a match early-on in a tree can lead to a large
2967 number of matches in the subtree when constructing the agenda or creating
2968 a sparse tree. If you only want to see the first match in a tree during
2969 a search, check out the variable `org-tags-match-list-sublevels'."
2970 :group 'org-tags
2971 :type '(choice
2972 (const :tag "Not" nil)
2973 (const :tag "Always" t)
2974 (repeat :tag "Specific tags" (string :tag "Tag"))
2975 (regexp :tag "Tags matched by regexp")))
2977 (defcustom org-tags-exclude-from-inheritance nil
2978 "List of tags that should never be inherited.
2979 This is a way to exclude a few tags from inheritance. For way to do
2980 the opposite, to actively allow inheritance for selected tags,
2981 see the variable `org-use-tag-inheritance'."
2982 :group 'org-tags
2983 :type '(repeat (string :tag "Tag")))
2985 (defun org-tag-inherit-p (tag)
2986 "Check if TAG is one that should be inherited."
2987 (cond
2988 ((member tag org-tags-exclude-from-inheritance) nil)
2989 ((eq org-use-tag-inheritance t) t)
2990 ((not org-use-tag-inheritance) nil)
2991 ((stringp org-use-tag-inheritance)
2992 (string-match org-use-tag-inheritance tag))
2993 ((listp org-use-tag-inheritance)
2994 (member tag org-use-tag-inheritance))
2995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2997 (defcustom org-tags-match-list-sublevels t
2998 "Non-nil means list also sublevels of headlines matching a search.
2999 This variable applies to tags/property searches, and also to stuck
3000 projects because this search is based on a tags match as well.
3002 When set to the symbol `indented', sublevels are indented with
3003 leading dots.
3005 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3006 the sublevels of a headline matching a tag search often also match
3007 the same search. Listing all of them can create very long lists.
3008 Setting this variable to nil causes subtrees of a match to be skipped.
3010 This variable is semi-obsolete and probably should always be true. It
3011 is better to limit inheritance to certain tags using the variables
3012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3013 :group 'org-tags
3014 :type '(choice
3015 (const :tag "No, don't list them" nil)
3016 (const :tag "Yes, do list them" t)
3017 (const :tag "List them, indented with leading dots" indented)))
3019 (defcustom org-tags-sort-function nil
3020 "When set, tags are sorted using this function as a comparator."
3021 :group 'org-tags
3022 :type '(choice
3023 (const :tag "No sorting" nil)
3024 (const :tag "Alphabetical" string<)
3025 (const :tag "Reverse alphabetical" string>)
3026 (function :tag "Custom function" nil)))
3028 (defvar org-tags-history nil
3029 "History of minibuffer reads for tags.")
3030 (defvar org-last-tags-completion-table nil
3031 "The last used completion table for tags.")
3032 (defvar org-after-tags-change-hook nil
3033 "Hook that is run after the tags in a line have changed.")
3035 (defgroup org-properties nil
3036 "Options concerning properties in Org-mode."
3037 :tag "Org Properties"
3038 :group 'org)
3040 (defcustom org-property-format "%-10s %s"
3041 "How property key/value pairs should be formatted by `indent-line'.
3042 When `indent-line' hits a property definition, it will format the line
3043 according to this format, mainly to make sure that the values are
3044 lined-up with respect to each other."
3045 :group 'org-properties
3046 :type 'string)
3048 (defcustom org-properties-postprocess-alist nil
3049 "Alist of properties and functions to adjust inserted values.
3050 Elements of this alist must be of the form
3052 ([string] [function])
3054 where [string] must be a property name and [function] must be a
3055 lambda expression: this lambda expression must take one argument,
3056 the value to adjust, and return the new value as a string.
3058 For example, this element will allow the property \"Remaining\"
3059 to be updated wrt the relation between the \"Effort\" property
3060 and the clock summary:
3062 ((\"Remaining\" (lambda(value)
3063 (let ((clocksum (org-clock-sum-current-item))
3064 (effort (org-duration-string-to-minutes
3065 (org-entry-get (point) \"Effort\"))))
3066 (org-minutes-to-hh:mm-string (- effort clocksum))))))"
3067 :group 'org-properties
3068 :version "24.1"
3069 :type '(alist :key-type (string :tag "Property")
3070 :value-type (function :tag "Function")))
3072 (defcustom org-use-property-inheritance nil
3073 "Non-nil means properties apply also for sublevels.
3075 This setting is chiefly used during property searches. Turning it on can
3076 cause significant overhead when doing a search, which is why it is not
3077 on by default.
3079 When nil, only the properties directly given in the current entry count.
3080 When t, every property is inherited. The value may also be a list of
3081 properties that should have inheritance, or a regular expression matching
3082 properties that should be inherited.
3084 However, note that some special properties use inheritance under special
3085 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3086 and the properties ending in \"_ALL\" when they are used as descriptor
3087 for valid values of a property.
3089 Note for programmers:
3090 When querying an entry with `org-entry-get', you can control if inheritance
3091 should be used. By default, `org-entry-get' looks only at the local
3092 properties. You can request inheritance by setting the inherit argument
3093 to t (to force inheritance) or to `selective' (to respect the setting
3094 in this variable)."
3095 :group 'org-properties
3096 :type '(choice
3097 (const :tag "Not" nil)
3098 (const :tag "Always" t)
3099 (repeat :tag "Specific properties" (string :tag "Property"))
3100 (regexp :tag "Properties matched by regexp")))
3102 (defun org-property-inherit-p (property)
3103 "Check if PROPERTY is one that should be inherited."
3104 (cond
3105 ((eq org-use-property-inheritance t) t)
3106 ((not org-use-property-inheritance) nil)
3107 ((stringp org-use-property-inheritance)
3108 (string-match org-use-property-inheritance property))
3109 ((listp org-use-property-inheritance)
3110 (member property org-use-property-inheritance))
3111 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3113 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3114 "The default column format, if no other format has been defined.
3115 This variable can be set on the per-file basis by inserting a line
3117 #+COLUMNS: %25ITEM ....."
3118 :group 'org-properties
3119 :type 'string)
3121 (defcustom org-columns-ellipses ".."
3122 "The ellipses to be used when a field in column view is truncated.
3123 When this is the empty string, as many characters as possible are shown,
3124 but then there will be no visual indication that the field has been truncated.
3125 When this is a string of length N, the last N characters of a truncated
3126 field are replaced by this string. If the column is narrower than the
3127 ellipses string, only part of the ellipses string will be shown."
3128 :group 'org-properties
3129 :type 'string)
3131 (defcustom org-columns-modify-value-for-display-function nil
3132 "Function that modifies values for display in column view.
3133 For example, it can be used to cut out a certain part from a time stamp.
3134 The function must take 2 arguments:
3136 column-title The title of the column (*not* the property name)
3137 value The value that should be modified.
3139 The function should return the value that should be displayed,
3140 or nil if the normal value should be used."
3141 :group 'org-properties
3142 :type 'function)
3144 (defcustom org-effort-property "Effort"
3145 "The property that is being used to keep track of effort estimates.
3146 Effort estimates given in this property need to have the format H:MM."
3147 :group 'org-properties
3148 :group 'org-progress
3149 :type '(string :tag "Property"))
3151 (defconst org-global-properties-fixed
3152 '(("VISIBILITY_ALL" . "folded children content all")
3153 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3154 "List of property/value pairs that can be inherited by any entry.
3156 These are fixed values, for the preset properties. The user variable
3157 that can be used to add to this list is `org-global-properties'.
3159 The entries in this list are cons cells where the car is a property
3160 name and cdr is a string with the value. If the value represents
3161 multiple items like an \"_ALL\" property, separate the items by
3162 spaces.")
3164 (defcustom org-global-properties nil
3165 "List of property/value pairs that can be inherited by any entry.
3167 This list will be combined with the constant `org-global-properties-fixed'.
3169 The entries in this list are cons cells where the car is a property
3170 name and cdr is a string with the value.
3172 You can set buffer-local values for the same purpose in the variable
3173 `org-file-properties' this by adding lines like
3175 #+PROPERTY: NAME VALUE"
3176 :group 'org-properties
3177 :type '(repeat
3178 (cons (string :tag "Property")
3179 (string :tag "Value"))))
3181 (defvar org-file-properties nil
3182 "List of property/value pairs that can be inherited by any entry.
3183 Valid for the current buffer.
3184 This variable is populated from #+PROPERTY lines.")
3185 (make-variable-buffer-local 'org-file-properties)
3187 (defgroup org-agenda nil
3188 "Options concerning agenda views in Org-mode."
3189 :tag "Org Agenda"
3190 :group 'org)
3192 (defvar org-category nil
3193 "Variable used by org files to set a category for agenda display.
3194 Such files should use a file variable to set it, for example
3196 # -*- mode: org; org-category: \"ELisp\"
3198 or contain a special line
3200 #+CATEGORY: ELisp
3202 If the file does not specify a category, then file's base name
3203 is used instead.")
3204 (make-variable-buffer-local 'org-category)
3205 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3207 (defcustom org-agenda-files nil
3208 "The files to be used for agenda display.
3209 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3210 \\[org-remove-file]. You can also use customize to edit the list.
3212 If an entry is a directory, all files in that directory that are matched by
3213 `org-agenda-file-regexp' will be part of the file list.
3215 If the value of the variable is not a list but a single file name, then
3216 the list of agenda files is actually stored and maintained in that file, one
3217 agenda file per line. In this file paths can be given relative to
3218 `org-directory'. Tilde expansion and environment variable substitution
3219 are also made."
3220 :group 'org-agenda
3221 :type '(choice
3222 (repeat :tag "List of files and directories" file)
3223 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3225 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3226 "Regular expression to match files for `org-agenda-files'.
3227 If any element in the list in that variable contains a directory instead
3228 of a normal file, all files in that directory that are matched by this
3229 regular expression will be included."
3230 :group 'org-agenda
3231 :type 'regexp)
3233 (defcustom org-agenda-text-search-extra-files nil
3234 "List of extra files to be searched by text search commands.
3235 These files will be search in addition to the agenda files by the
3236 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3237 Note that these files will only be searched for text search commands,
3238 not for the other agenda views like todo lists, tag searches or the weekly
3239 agenda. This variable is intended to list notes and possibly archive files
3240 that should also be searched by these two commands.
3241 In fact, if the first element in the list is the symbol `agenda-archives',
3242 than all archive files of all agenda files will be added to the search
3243 scope."
3244 :group 'org-agenda
3245 :type '(set :greedy t
3246 (const :tag "Agenda Archives" agenda-archives)
3247 (repeat :inline t (file))))
3249 (if (fboundp 'defvaralias)
3250 (defvaralias 'org-agenda-multi-occur-extra-files
3251 'org-agenda-text-search-extra-files))
3253 (defcustom org-agenda-skip-unavailable-files nil
3254 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3255 A nil value means to remove them, after a query, from the list."
3256 :group 'org-agenda
3257 :type 'boolean)
3259 (defcustom org-calendar-to-agenda-key [?c]
3260 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3261 The command `org-calendar-goto-agenda' will be bound to this key. The
3262 default is the character `c' because then `c' can be used to switch back and
3263 forth between agenda and calendar."
3264 :group 'org-agenda
3265 :type 'sexp)
3267 (defcustom org-calendar-agenda-action-key [?k]
3268 "The key to be installed in `calendar-mode-map' for agenda-action.
3269 The command `org-agenda-action' will be bound to this key. The
3270 default is the character `k' because we use the same key in the agenda."
3271 :group 'org-agenda
3272 :type 'sexp)
3274 (defcustom org-calendar-insert-diary-entry-key [?i]
3275 "The key to be installed in `calendar-mode-map' for adding diary entries.
3276 This option is irrelevant until `org-agenda-diary-file' has been configured
3277 to point to an Org-mode file. When that is the case, the command
3278 `org-agenda-diary-entry' will be bound to the key given here, by default
3279 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3280 if you want to continue doing this, you need to change this to a different
3281 key."
3282 :group 'org-agenda
3283 :type 'sexp)
3285 (defcustom org-agenda-diary-file 'diary-file
3286 "File to which to add new entries with the `i' key in agenda and calendar.
3287 When this is the symbol `diary-file', the functionality in the Emacs
3288 calendar will be used to add entries to the `diary-file'. But when this
3289 points to a file, `org-agenda-diary-entry' will be used instead."
3290 :group 'org-agenda
3291 :type '(choice
3292 (const :tag "The standard Emacs diary file" diary-file)
3293 (file :tag "Special Org file diary entries")))
3295 (eval-after-load "calendar"
3296 '(progn
3297 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3298 'org-calendar-goto-agenda)
3299 (org-defkey calendar-mode-map org-calendar-agenda-action-key
3300 'org-agenda-action)
3301 (add-hook 'calendar-mode-hook
3302 (lambda ()
3303 (unless (eq org-agenda-diary-file 'diary-file)
3304 (define-key calendar-mode-map
3305 org-calendar-insert-diary-entry-key
3306 'org-agenda-diary-entry))))))
3308 (defgroup org-latex nil
3309 "Options for embedding LaTeX code into Org-mode."
3310 :tag "Org LaTeX"
3311 :group 'org)
3313 (defcustom org-format-latex-options
3314 '(:foreground default :background default :scale 1.0
3315 :html-foreground "Black" :html-background "Transparent"
3316 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3317 "Options for creating images from LaTeX fragments.
3318 This is a property list with the following properties:
3319 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3320 `default' means use the foreground of the default face.
3321 :background the background color, or \"Transparent\".
3322 `default' means use the background of the default face.
3323 :scale a scaling factor for the size of the images, to get more pixels
3324 :html-foreground, :html-background, :html-scale
3325 the same numbers for HTML export.
3326 :matchers a list indicating which matchers should be used to
3327 find LaTeX fragments. Valid members of this list are:
3328 \"begin\" find environments
3329 \"$1\" find single characters surrounded by $.$
3330 \"$\" find math expressions surrounded by $...$
3331 \"$$\" find math expressions surrounded by $$....$$
3332 \"\\(\" find math expressions surrounded by \\(...\\)
3333 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3334 :group 'org-latex
3335 :type 'plist)
3337 (defcustom org-format-latex-signal-error t
3338 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3339 When nil, just push out a message."
3340 :group 'org-latex
3341 :version "24.1"
3342 :type 'boolean)
3344 (defcustom org-latex-to-mathml-jar-file nil
3345 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3346 Use this to specify additional executable file say a jar file.
3348 When using MathToWeb as the converter, specify the full-path to
3349 your mathtoweb.jar file."
3350 :group 'org-latex
3351 :version "24.1"
3352 :type '(choice
3353 (const :tag "None" nil)
3354 (file :tag "JAR file" :must-match t)))
3356 (defcustom org-latex-to-mathml-convert-command nil
3357 "Command to convert LaTeX fragments to MathML.
3358 Replace format-specifiers in the command as noted below and use
3359 `shell-command' to convert LaTeX to MathML.
3360 %j: Executable file in fully expanded form as specified by
3361 `org-latex-to-mathml-jar-file'.
3362 %I: Input LaTeX file in fully expanded form
3363 %o: Output MathML file
3364 This command is used by `org-create-math-formula'.
3366 When using MathToWeb as the converter, set this to
3367 \"java -jar %j -unicode -force -df %o %I\"."
3368 :group 'org-latex
3369 :version "24.1"
3370 :type '(choice
3371 (const :tag "None" nil)
3372 (string :tag "\nShell command")))
3374 (defcustom org-latex-create-formula-image-program 'dvipng
3375 "Program to convert LaTeX fragments with.
3377 dvipng Process the LaTeX fragments to dvi file, then convert
3378 dvi files to png files using dvipng.
3379 This will also include processing of non-math environments.
3380 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3381 to convert pdf files to png files"
3382 :group 'org-latex
3383 :version "24.1"
3384 :type '(choice
3385 (const :tag "dvipng" dvipng)
3386 (const :tag "imagemagick" imagemagick)))
3388 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3389 "Path to store latex preview images. A relative path here creates many
3390 directories relative to the processed org files paths. An absolute path
3391 puts all preview images at the same place."
3392 :group 'org-latex
3393 ;; :version "24.3"
3394 :type 'string)
3396 (defun org-format-latex-mathml-available-p ()
3397 "Return t if `org-latex-to-mathml-convert-command' is usable."
3398 (save-match-data
3399 (when (and (boundp 'org-latex-to-mathml-convert-command)
3400 org-latex-to-mathml-convert-command)
3401 (let ((executable (car (split-string
3402 org-latex-to-mathml-convert-command))))
3403 (when (executable-find executable)
3404 (if (string-match
3405 "%j" org-latex-to-mathml-convert-command)
3406 (file-readable-p org-latex-to-mathml-jar-file)
3407 t))))))
3409 (defcustom org-format-latex-header "\\documentclass{article}
3410 \\usepackage[usenames]{color}
3411 \\usepackage{amsmath}
3412 \\usepackage[mathscr]{eucal}
3413 \\pagestyle{empty} % do not remove
3414 \[PACKAGES]
3415 \[DEFAULT-PACKAGES]
3416 % The settings below are copied from fullpage.sty
3417 \\setlength{\\textwidth}{\\paperwidth}
3418 \\addtolength{\\textwidth}{-3cm}
3419 \\setlength{\\oddsidemargin}{1.5cm}
3420 \\addtolength{\\oddsidemargin}{-2.54cm}
3421 \\setlength{\\evensidemargin}{\\oddsidemargin}
3422 \\setlength{\\textheight}{\\paperheight}
3423 \\addtolength{\\textheight}{-\\headheight}
3424 \\addtolength{\\textheight}{-\\headsep}
3425 \\addtolength{\\textheight}{-\\footskip}
3426 \\addtolength{\\textheight}{-3cm}
3427 \\setlength{\\topmargin}{1.5cm}
3428 \\addtolength{\\topmargin}{-2.54cm}"
3429 "The document header used for processing LaTeX fragments.
3430 It is imperative that this header make sure that no page number
3431 appears on the page. The package defined in the variables
3432 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3433 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3434 will be appended."
3435 :group 'org-latex
3436 :type 'string)
3438 (defvar org-format-latex-header-extra nil)
3440 (defun org-set-packages-alist (var val)
3441 "Set the packages alist and make sure it has 3 elements per entry."
3442 (set var (mapcar (lambda (x)
3443 (if (and (consp x) (= (length x) 2))
3444 (list (car x) (nth 1 x) t)
3446 val)))
3448 (defun org-get-packages-alist (var)
3450 "Get the packages alist and make sure it has 3 elements per entry."
3451 (mapcar (lambda (x)
3452 (if (and (consp x) (= (length x) 2))
3453 (list (car x) (nth 1 x) t)
3455 (default-value var)))
3457 ;; The following variables are defined here because is it also used
3458 ;; when formatting latex fragments. Originally it was part of the
3459 ;; LaTeX exporter, which is why the name includes "export".
3460 (defcustom org-export-latex-default-packages-alist
3461 '(("AUTO" "inputenc" t)
3462 ("T1" "fontenc" t)
3463 ("" "fixltx2e" nil)
3464 ("" "graphicx" t)
3465 ("" "longtable" nil)
3466 ("" "float" nil)
3467 ("" "wrapfig" nil)
3468 ("" "soul" t)
3469 ("" "textcomp" t)
3470 ("" "marvosym" t)
3471 ("" "wasysym" t)
3472 ("" "latexsym" t)
3473 ("" "amssymb" t)
3474 ("" "hyperref" nil)
3475 "\\tolerance=1000"
3477 "Alist of default packages to be inserted in the header.
3478 Change this only if one of the packages here causes an incompatibility
3479 with another package you are using.
3480 The packages in this list are needed by one part or another of Org-mode
3481 to function properly.
3483 - inputenc, fontenc: for basic font and character selection
3484 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3485 for interpreting the entities in `org-entities'. You can skip some of these
3486 packages if you don't use any of the symbols in it.
3487 - graphicx: for including images
3488 - float, wrapfig: for figure placement
3489 - longtable: for long tables
3490 - hyperref: for cross references
3492 Therefore you should not modify this variable unless you know what you
3493 are doing. The one reason to change it anyway is that you might be loading
3494 some other package that conflicts with one of the default packages.
3495 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3496 If SNIPPET-FLAG is t, the package also needs to be included when
3497 compiling LaTeX snippets into images for inclusion into HTML."
3498 :group 'org-export-latex
3499 :set 'org-set-packages-alist
3500 :get 'org-get-packages-alist
3501 :version "24.1"
3502 :type '(repeat
3503 (choice
3504 (list :tag "options/package pair"
3505 (string :tag "options")
3506 (string :tag "package")
3507 (boolean :tag "Snippet"))
3508 (string :tag "A line of LaTeX"))))
3510 (defcustom org-export-latex-packages-alist nil
3511 "Alist of packages to be inserted in every LaTeX header.
3512 These will be inserted after `org-export-latex-default-packages-alist'.
3513 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3514 SNIPPET-FLAG, when t, indicates that this package is also needed when
3515 turning LaTeX snippets into images for inclusion into HTML.
3516 Make sure that you only list packages here which:
3517 - you want in every file
3518 - do not conflict with the default packages in
3519 `org-export-latex-default-packages-alist'
3520 - do not conflict with the setup in `org-format-latex-header'."
3521 :group 'org-export-latex
3522 :set 'org-set-packages-alist
3523 :get 'org-get-packages-alist
3524 :type '(repeat
3525 (choice
3526 (list :tag "options/package pair"
3527 (string :tag "options")
3528 (string :tag "package")
3529 (boolean :tag "Snippet"))
3530 (string :tag "A line of LaTeX"))))
3533 (defgroup org-appearance nil
3534 "Settings for Org-mode appearance."
3535 :tag "Org Appearance"
3536 :group 'org)
3538 (defcustom org-level-color-stars-only nil
3539 "Non-nil means fontify only the stars in each headline.
3540 When nil, the entire headline is fontified.
3541 Changing it requires restart of `font-lock-mode' to become effective
3542 also in regions already fontified."
3543 :group 'org-appearance
3544 :type 'boolean)
3546 (defcustom org-hide-leading-stars nil
3547 "Non-nil means hide the first N-1 stars in a headline.
3548 This works by using the face `org-hide' for these stars. This
3549 face is white for a light background, and black for a dark
3550 background. You may have to customize the face `org-hide' to
3551 make this work.
3552 Changing it requires restart of `font-lock-mode' to become effective
3553 also in regions already fontified.
3554 You may also set this on a per-file basis by adding one of the following
3555 lines to the buffer:
3557 #+STARTUP: hidestars
3558 #+STARTUP: showstars"
3559 :group 'org-appearance
3560 :type 'boolean)
3562 (defcustom org-hidden-keywords nil
3563 "List of symbols corresponding to keywords to be hidden the org buffer.
3564 For example, a value '(title) for this list will make the document's title
3565 appear in the buffer without the initial #+TITLE: keyword."
3566 :group 'org-appearance
3567 :version "24.1"
3568 :type '(set (const :tag "#+AUTHOR" author)
3569 (const :tag "#+DATE" date)
3570 (const :tag "#+EMAIL" email)
3571 (const :tag "#+TITLE" title)))
3573 (defcustom org-custom-properties nil
3574 "List of properties (as strings) with a special meaning.
3575 The default use of these custom properties is to let the user
3576 hide them with `org-toggle-custom-properties-visibility'."
3577 :group 'org-properties
3578 :group 'org-appearance
3579 ;; :version "24.3"
3580 :type '(repeat (string :tag "Property Name")))
3582 (defcustom org-fontify-done-headline nil
3583 "Non-nil means change the face of a headline if it is marked DONE.
3584 Normally, only the TODO/DONE keyword indicates the state of a headline.
3585 When this is non-nil, the headline after the keyword is set to the
3586 `org-headline-done' as an additional indication."
3587 :group 'org-appearance
3588 :type 'boolean)
3590 (defcustom org-fontify-emphasized-text t
3591 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3592 Changing this variable requires a restart of Emacs to take effect."
3593 :group 'org-appearance
3594 :type 'boolean)
3596 (defcustom org-fontify-whole-heading-line nil
3597 "Non-nil means fontify the whole line for headings.
3598 This is useful when setting a background color for the
3599 org-level-* faces."
3600 :group 'org-appearance
3601 :type 'boolean)
3603 (defcustom org-highlight-latex-fragments-and-specials nil
3604 "Non-nil means fontify what is treated specially by the exporters."
3605 :group 'org-appearance
3606 :type 'boolean)
3608 (defcustom org-hide-emphasis-markers nil
3609 "Non-nil mean font-lock should hide the emphasis marker characters."
3610 :group 'org-appearance
3611 :type 'boolean)
3613 (defcustom org-pretty-entities nil
3614 "Non-nil means show entities as UTF8 characters.
3615 When nil, the \\name form remains in the buffer."
3616 :group 'org-appearance
3617 :version "24.1"
3618 :type 'boolean)
3620 (defcustom org-pretty-entities-include-sub-superscripts t
3621 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3622 :group 'org-appearance
3623 :version "24.1"
3624 :type 'boolean)
3626 (defvar org-emph-re nil
3627 "Regular expression for matching emphasis.
3628 After a match, the match groups contain these elements:
3629 0 The match of the full regular expression, including the characters
3630 before and after the proper match
3631 1 The character before the proper match, or empty at beginning of line
3632 2 The proper match, including the leading and trailing markers
3633 3 The leading marker like * or /, indicating the type of highlighting
3634 4 The text between the emphasis markers, not including the markers
3635 5 The character after the match, empty at the end of a line")
3636 (defvar org-verbatim-re nil
3637 "Regular expression for matching verbatim text.")
3638 (defvar org-emphasis-regexp-components) ; defined just below
3639 (defvar org-emphasis-alist) ; defined just below
3640 (defun org-set-emph-re (var val)
3641 "Set variable and compute the emphasis regular expression."
3642 (set var val)
3643 (when (and (boundp 'org-emphasis-alist)
3644 (boundp 'org-emphasis-regexp-components)
3645 org-emphasis-alist org-emphasis-regexp-components)
3646 (let* ((e org-emphasis-regexp-components)
3647 (pre (car e))
3648 (post (nth 1 e))
3649 (border (nth 2 e))
3650 (body (nth 3 e))
3651 (nl (nth 4 e))
3652 (body1 (concat body "*?"))
3653 (markers (mapconcat 'car org-emphasis-alist ""))
3654 (vmarkers (mapconcat
3655 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3656 org-emphasis-alist "")))
3657 ;; make sure special characters appear at the right position in the class
3658 (if (string-match "\\^" markers)
3659 (setq markers (concat (replace-match "" t t markers) "^")))
3660 (if (string-match "-" markers)
3661 (setq markers (concat (replace-match "" t t markers) "-")))
3662 (if (string-match "\\^" vmarkers)
3663 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3664 (if (string-match "-" vmarkers)
3665 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3666 (if (> nl 0)
3667 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3668 (int-to-string nl) "\\}")))
3669 ;; Make the regexp
3670 (setq org-emph-re
3671 (concat "\\([" pre "]\\|^\\)"
3672 "\\("
3673 "\\([" markers "]\\)"
3674 "\\("
3675 "[^" border "]\\|"
3676 "[^" border "]"
3677 body1
3678 "[^" border "]"
3679 "\\)"
3680 "\\3\\)"
3681 "\\([" post "]\\|$\\)"))
3682 (setq org-verbatim-re
3683 (concat "\\([" pre "]\\|^\\)"
3684 "\\("
3685 "\\([" vmarkers "]\\)"
3686 "\\("
3687 "[^" border "]\\|"
3688 "[^" border "]"
3689 body1
3690 "[^" border "]"
3691 "\\)"
3692 "\\3\\)"
3693 "\\([" post "]\\|$\\)")))))
3695 (defcustom org-emphasis-regexp-components
3696 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3697 "Components used to build the regular expression for emphasis.
3698 This is a list with five entries. Terminology: In an emphasis string
3699 like \" *strong word* \", we call the initial space PREMATCH, the final
3700 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3701 and \"trong wor\" is the body. The different components in this variable
3702 specify what is allowed/forbidden in each part:
3704 pre Chars allowed as prematch. Beginning of line will be allowed too.
3705 post Chars allowed as postmatch. End of line will be allowed too.
3706 border The chars *forbidden* as border characters.
3707 body-regexp A regexp like \".\" to match a body character. Don't use
3708 non-shy groups here, and don't allow newline here.
3709 newline The maximum number of newlines allowed in an emphasis exp.
3711 Use customize to modify this, or restart Emacs after changing it."
3712 :group 'org-appearance
3713 :set 'org-set-emph-re
3714 :type '(list
3715 (sexp :tag "Allowed chars in pre ")
3716 (sexp :tag "Allowed chars in post ")
3717 (sexp :tag "Forbidden chars in border ")
3718 (sexp :tag "Regexp for body ")
3719 (integer :tag "number of newlines allowed")
3720 (option (boolean :tag "Please ignore this button"))))
3722 (defcustom org-emphasis-alist
3723 `(("*" bold "<b>" "</b>")
3724 ("/" italic "<i>" "</i>")
3725 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3726 ("=" org-code "<code>" "</code>" verbatim)
3727 ("~" org-verbatim "<code>" "</code>" verbatim)
3728 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3729 "<del>" "</del>")
3731 "Special syntax for emphasized text.
3732 Text starting and ending with a special character will be emphasized, for
3733 example *bold*, _underlined_ and /italic/. This variable sets the marker
3734 characters, the face to be used by font-lock for highlighting in Org-mode
3735 Emacs buffers, and the HTML tags to be used for this.
3736 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3737 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3738 Use customize to modify this, or restart Emacs after changing it."
3739 :group 'org-appearance
3740 :set 'org-set-emph-re
3741 :type '(repeat
3742 (list
3743 (string :tag "Marker character")
3744 (choice
3745 (face :tag "Font-lock-face")
3746 (plist :tag "Face property list"))
3747 (string :tag "HTML start tag")
3748 (string :tag "HTML end tag")
3749 (option (const verbatim)))))
3751 (defvar org-protecting-blocks
3752 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3753 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3754 This is needed for font-lock setup.")
3756 ;;; Miscellaneous options
3758 (defgroup org-completion nil
3759 "Completion in Org-mode."
3760 :tag "Org Completion"
3761 :group 'org)
3763 (defcustom org-completion-use-ido nil
3764 "Non-nil means use ido completion wherever possible.
3765 Note that `ido-mode' must be active for this variable to be relevant.
3766 If you decide to turn this variable on, you might well want to turn off
3767 `org-outline-path-complete-in-steps'.
3768 See also `org-completion-use-iswitchb'."
3769 :group 'org-completion
3770 :type 'boolean)
3772 (defcustom org-completion-use-iswitchb nil
3773 "Non-nil means use iswitchb completion wherever possible.
3774 Note that `iswitchb-mode' must be active for this variable to be relevant.
3775 If you decide to turn this variable on, you might well want to turn off
3776 `org-outline-path-complete-in-steps'.
3777 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3778 :group 'org-completion
3779 :type 'boolean)
3781 (defcustom org-completion-fallback-command 'hippie-expand
3782 "The expansion command called by \\[pcomplete] in normal context.
3783 Normal means, no org-mode-specific context."
3784 :group 'org-completion
3785 :type 'function)
3787 ;;; Functions and variables from their packages
3788 ;; Declared here to avoid compiler warnings
3790 ;; XEmacs only
3791 (defvar outline-mode-menu-heading)
3792 (defvar outline-mode-menu-show)
3793 (defvar outline-mode-menu-hide)
3794 (defvar zmacs-regions) ; XEmacs regions
3796 ;; Emacs only
3797 (defvar mark-active)
3799 ;; Various packages
3800 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3801 (declare-function calendar-forward-day "cal-move" (arg))
3802 (declare-function calendar-goto-date "cal-move" (date))
3803 (declare-function calendar-goto-today "cal-move" ())
3804 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3805 (defvar calc-embedded-close-formula)
3806 (defvar calc-embedded-open-formula)
3807 (declare-function cdlatex-tab "ext:cdlatex" ())
3808 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3809 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3810 (defvar font-lock-unfontify-region-function)
3811 (declare-function iswitchb-read-buffer "iswitchb"
3812 (prompt &optional default require-match start matches-set))
3813 (defvar iswitchb-temp-buflist)
3814 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3815 (defvar org-agenda-tags-todo-honor-ignore-options)
3816 (declare-function org-agenda-skip "org-agenda" ())
3817 (declare-function
3818 org-agenda-format-item "org-agenda"
3819 (extra txt &optional category tags dotime noprefix remove-re habitp))
3820 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3821 (declare-function org-agenda-change-all-lines "org-agenda"
3822 (newhead hdmarker &optional fixface just-this))
3823 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3824 (declare-function org-agenda-maybe-redo "org-agenda" ())
3825 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3826 (beg end))
3827 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3828 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3829 "org-agenda" (&optional end))
3830 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3831 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3832 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3833 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3834 (declare-function org-indent-mode "org-indent" (&optional arg))
3835 (declare-function parse-time-string "parse-time" (string))
3836 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3837 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3838 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3839 (defvar remember-data-file)
3840 (defvar texmathp-why)
3841 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3842 (declare-function table--at-cell-p "table" (position &optional object at-column))
3844 (defvar w3m-current-url)
3845 (defvar w3m-current-title)
3847 (defvar org-latex-regexps)
3849 ;;; Autoload and prepare some org modules
3851 ;; Some table stuff that needs to be defined here, because it is used
3852 ;; by the functions setting up org-mode or checking for table context.
3854 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3855 "Detect an org-type or table-type table.")
3856 (defconst org-table-line-regexp "^[ \t]*|"
3857 "Detect an org-type table line.")
3858 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3859 "Detect an org-type table line.")
3860 (defconst org-table-hline-regexp "^[ \t]*|-"
3861 "Detect an org-type table hline.")
3862 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3863 "Detect a table-type table hline.")
3864 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3865 "Detect the first line outside a table when searching from within it.
3866 This works for both table types.")
3868 ;; Autoload the functions in org-table.el that are needed by functions here.
3870 (eval-and-compile
3871 (org-autoload "org-table"
3872 '(org-table-align org-table-begin org-table-blank-field
3873 org-table-convert org-table-convert-region org-table-copy-down
3874 org-table-copy-region org-table-create
3875 org-table-create-or-convert-from-region
3876 org-table-create-with-table.el org-table-current-dline
3877 org-table-cut-region org-table-delete-column org-table-edit-field
3878 org-table-edit-formulas org-table-end org-table-eval-formula
3879 org-table-export org-table-field-info
3880 org-table-get-stored-formulas org-table-goto-column
3881 org-table-hline-and-move org-table-import org-table-insert-column
3882 org-table-insert-hline org-table-insert-row org-table-iterate
3883 org-table-justify-field-maybe org-table-kill-row
3884 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3885 org-table-move-column org-table-move-column-left
3886 org-table-move-column-right org-table-move-row
3887 org-table-move-row-down org-table-move-row-up
3888 org-table-next-field org-table-next-row org-table-paste-rectangle
3889 org-table-previous-field org-table-recalculate
3890 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3891 org-table-toggle-coordinate-overlays
3892 org-table-toggle-formula-debugger org-table-wrap-region
3893 orgtbl-mode turn-on-orgtbl org-table-to-lisp
3894 orgtbl-to-generic orgtbl-to-tsv orgtbl-to-csv orgtbl-to-latex
3895 orgtbl-to-orgtbl orgtbl-to-html orgtbl-to-texinfo)))
3897 (defun org-at-table-p (&optional table-type)
3898 "Return t if the cursor is inside an org-type table.
3899 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3900 (if org-enable-table-editor
3901 (save-excursion
3902 (beginning-of-line 1)
3903 (looking-at (if table-type org-table-any-line-regexp
3904 org-table-line-regexp)))
3905 nil))
3906 (defsubst org-table-p () (org-at-table-p))
3908 (defun org-at-table.el-p ()
3909 "Return t if and only if we are at a table.el table."
3910 (and (org-at-table-p 'any)
3911 (save-excursion
3912 (goto-char (org-table-begin 'any))
3913 (looking-at org-table1-hline-regexp))))
3914 (defun org-table-recognize-table.el ()
3915 "If there is a table.el table nearby, recognize it and move into it."
3916 (if org-table-tab-recognizes-table.el
3917 (if (org-at-table.el-p)
3918 (progn
3919 (beginning-of-line 1)
3920 (if (looking-at org-table-dataline-regexp)
3922 (if (looking-at org-table1-hline-regexp)
3923 (progn
3924 (beginning-of-line 2)
3925 (if (looking-at org-table-any-border-regexp)
3926 (beginning-of-line -1)))))
3927 (if (re-search-forward "|" (org-table-end t) t)
3928 (progn
3929 (require 'table)
3930 (if (table--at-cell-p (point))
3932 (message "recognizing table.el table...")
3933 (table-recognize-table)
3934 (message "recognizing table.el table...done")))
3935 (error "This should not happen"))
3937 nil)
3938 nil))
3940 (defun org-at-table-hline-p ()
3941 "Return t if the cursor is inside a hline in a table."
3942 (if org-enable-table-editor
3943 (save-excursion
3944 (beginning-of-line 1)
3945 (looking-at org-table-hline-regexp))
3946 nil))
3948 (defvar org-table-clean-did-remove-column nil)
3950 (defun org-table-map-tables (function &optional quietly)
3951 "Apply FUNCTION to the start of all tables in the buffer."
3952 (save-excursion
3953 (save-restriction
3954 (widen)
3955 (goto-char (point-min))
3956 (while (re-search-forward org-table-any-line-regexp nil t)
3957 (unless quietly
3958 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
3959 (beginning-of-line 1)
3960 (when (and (looking-at org-table-line-regexp)
3961 ;; Exclude tables in src/example/verbatim/clocktable blocks
3962 (not (org-in-block-p '("src" "example"))))
3963 (save-excursion (funcall function))
3964 (or (looking-at org-table-line-regexp)
3965 (forward-char 1)))
3966 (re-search-forward org-table-any-border-regexp nil 1))))
3967 (unless quietly (message "Mapping tables: done")))
3969 ;; Declare and autoload functions from org-exp.el & Co
3971 (declare-function org-default-export-plist "org-exp")
3972 (declare-function org-infile-export-plist "org-exp")
3973 (declare-function org-get-current-options "org-exp")
3974 (eval-and-compile
3975 (org-autoload "org-exp"
3976 '(org-export org-export-visible
3977 org-insert-export-options-template
3978 org-table-clean-before-export))
3979 (org-autoload "org-ascii"
3980 '(org-export-as-ascii org-export-ascii-preprocess
3981 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3982 org-export-region-as-ascii))
3983 (org-autoload "org-latex"
3984 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3985 org-replace-region-by-latex org-export-region-as-latex
3986 org-export-as-latex org-export-as-pdf
3987 org-export-as-pdf-and-open))
3988 (org-autoload "org-html"
3989 '(org-export-as-html-and-open
3990 org-export-as-html-batch org-export-as-html-to-buffer
3991 org-replace-region-by-html org-export-region-as-html
3992 org-export-as-html))
3993 (org-autoload "org-docbook"
3994 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3995 org-replace-region-by-docbook org-export-region-as-docbook
3996 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3997 org-export-as-docbook))
3998 (org-autoload "org-icalendar"
3999 '(org-export-icalendar-this-file
4000 org-export-icalendar-all-agenda-files
4001 org-export-icalendar-combine-agenda-files))
4002 (org-autoload "org-xoxo" '(org-export-as-xoxo))
4003 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
4005 ;; Declare and autoload functions from org-agenda.el
4007 (eval-and-compile
4008 (org-autoload "org-agenda"
4009 '(org-agenda org-agenda-list org-search-view
4010 org-todo-list org-tags-view org-agenda-list-stuck-projects
4011 org-diary org-agenda-to-appt
4012 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4014 ;; Autoload org-remember
4016 (eval-and-compile
4017 (org-autoload "org-remember"
4018 '(org-remember-insinuate org-remember-annotation
4019 org-remember-apply-template org-remember org-remember-handler)))
4021 (eval-and-compile
4022 (org-autoload "org-capture"
4023 '(org-capture org-capture-insert-template-here
4024 org-capture-import-remember-templates)))
4026 ;; Autoload org-clock.el
4028 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
4029 (beg end))
4030 (declare-function org-clock-update-mode-line "org-clock" ())
4031 (declare-function org-resolve-clocks "org-clock"
4032 (&optional also-non-dangling-p prompt last-valid))
4033 (defvar org-clock-start-time)
4034 (defvar org-clock-marker (make-marker)
4035 "Marker recording the last clock-in.")
4036 (defvar org-clock-hd-marker (make-marker)
4037 "Marker recording the last clock-in, but the headline position.")
4038 (defvar org-clock-heading ""
4039 "The heading of the current clock entry.")
4040 (defun org-clock-is-active ()
4041 "Return non-nil if clock is currently running.
4042 The return value is actually the clock marker."
4043 (marker-buffer org-clock-marker))
4045 (eval-and-compile
4046 (org-autoload
4047 "org-clock"
4048 '(org-clock-in org-clock-out org-clock-cancel
4049 org-clock-goto org-clock-sum org-clock-display
4050 org-clock-remove-overlays org-clock-report
4051 org-clocktable-shift org-dblock-write:clocktable
4052 org-get-clocktable org-resolve-clocks)))
4054 (defun org-clock-update-time-maybe ()
4055 "If this is a CLOCK line, update it and return t.
4056 Otherwise, return nil."
4057 (interactive)
4058 (save-excursion
4059 (beginning-of-line 1)
4060 (skip-chars-forward " \t")
4061 (when (looking-at org-clock-string)
4062 (let ((re (concat "[ \t]*" org-clock-string
4063 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
4064 "\\([ \t]*=>.*\\)?\\)?"))
4065 ts te h m s neg)
4066 (cond
4067 ((not (looking-at re))
4068 nil)
4069 ((not (match-end 2))
4070 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4071 (> org-clock-marker (point))
4072 (<= org-clock-marker (point-at-eol)))
4073 ;; The clock is running here
4074 (setq org-clock-start-time
4075 (apply 'encode-time
4076 (org-parse-time-string (match-string 1))))
4077 (org-clock-update-mode-line)))
4079 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
4080 (end-of-line 1)
4081 (setq ts (match-string 1)
4082 te (match-string 3))
4083 (setq s (- (org-float-time
4084 (apply 'encode-time (org-parse-time-string te)))
4085 (org-float-time
4086 (apply 'encode-time (org-parse-time-string ts))))
4087 neg (< s 0)
4088 s (abs s)
4089 h (floor (/ s 3600))
4090 s (- s (* 3600 h))
4091 m (floor (/ s 60))
4092 s (- s (* 60 s)))
4093 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
4094 t))))))
4096 (defun org-check-running-clock ()
4097 "Check if the current buffer contains the running clock.
4098 If yes, offer to stop it and to save the buffer with the changes."
4099 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4100 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4101 (buffer-name))))
4102 (org-clock-out)
4103 (when (y-or-n-p "Save changed buffer?")
4104 (save-buffer))))
4106 (defun org-clocktable-try-shift (dir n)
4107 "Check if this line starts a clock table, if yes, shift the time block."
4108 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4109 (org-clocktable-shift dir n)))
4111 ;; Autoload org-timer.el
4113 (eval-and-compile
4114 (org-autoload
4115 "org-timer"
4116 '(org-timer-start org-timer org-timer-item
4117 org-timer-change-times-in-region
4118 org-timer-set-timer
4119 org-timer-reset-timers
4120 org-timer-show-remaining-time)))
4122 ;; Autoload org-feed.el
4124 (eval-and-compile
4125 (org-autoload
4126 "org-feed"
4127 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
4130 ;; Autoload org-indent.el
4132 ;; Define the variable already here, to make sure we have it.
4133 (defvar org-indent-mode nil
4134 "Non-nil if Org-Indent mode is enabled.
4135 Use the command `org-indent-mode' to change this variable.")
4137 (eval-and-compile
4138 (org-autoload
4139 "org-indent"
4140 '(org-indent-mode)))
4142 ;; Autoload org-mobile.el
4144 (eval-and-compile
4145 (org-autoload
4146 "org-mobile"
4147 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
4149 ;; Autoload archiving code
4150 ;; The stuff that is needed for cycling and tags has to be defined here.
4152 (defgroup org-archive nil
4153 "Options concerning archiving in Org-mode."
4154 :tag "Org Archive"
4155 :group 'org-structure)
4157 (defcustom org-archive-location "%s_archive::"
4158 "The location where subtrees should be archived.
4160 The value of this variable is a string, consisting of two parts,
4161 separated by a double-colon. The first part is a filename and
4162 the second part is a headline.
4164 When the filename is omitted, archiving happens in the same file.
4165 %s in the filename will be replaced by the current file
4166 name (without the directory part). Archiving to a different file
4167 is useful to keep archived entries from contributing to the
4168 Org-mode Agenda.
4170 The archived entries will be filed as subtrees of the specified
4171 headline. When the headline is omitted, the subtrees are simply
4172 filed away at the end of the file, as top-level entries. Also in
4173 the heading you can use %s to represent the file name, this can be
4174 useful when using the same archive for a number of different files.
4176 Here are a few examples:
4177 \"%s_archive::\"
4178 If the current file is Projects.org, archive in file
4179 Projects.org_archive, as top-level trees. This is the default.
4181 \"::* Archived Tasks\"
4182 Archive in the current file, under the top-level headline
4183 \"* Archived Tasks\".
4185 \"~/org/archive.org::\"
4186 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4188 \"~/org/archive.org::* From %s\"
4189 Archive in file ~/org/archive.org (absolute path), under headlines
4190 \"From FILENAME\" where file name is the current file name.
4192 \"~/org/datetree.org::datetree/* Finished Tasks\"
4193 The \"datetree/\" string is special, signifying to archive
4194 items to the datetree. Items are placed in either the CLOSED
4195 date of the item, or the current date if there is no CLOSED date.
4196 The heading will be a subentry to the current date. There doesn't
4197 need to be a heading, but there always needs to be a slash after
4198 datetree. For example, to store archived items directly in the
4199 datetree, use \"~/org/datetree.org::datetree/\".
4201 \"basement::** Finished Tasks\"
4202 Archive in file ./basement (relative path), as level 3 trees
4203 below the level 2 heading \"** Finished Tasks\".
4205 You may set this option on a per-file basis by adding to the buffer a
4206 line like
4208 #+ARCHIVE: basement::** Finished Tasks
4210 You may also define it locally for a subtree by setting an ARCHIVE property
4211 in the entry. If such a property is found in an entry, or anywhere up
4212 the hierarchy, it will be used."
4213 :group 'org-archive
4214 :type 'string)
4216 (defcustom org-archive-tag "ARCHIVE"
4217 "The tag that marks a subtree as archived.
4218 An archived subtree does not open during visibility cycling, and does
4219 not contribute to the agenda listings.
4220 After changing this, font-lock must be restarted in the relevant buffers to
4221 get the proper fontification."
4222 :group 'org-archive
4223 :group 'org-keywords
4224 :type 'string)
4226 (defcustom org-agenda-skip-archived-trees t
4227 "Non-nil means the agenda will skip any items located in archived trees.
4228 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4229 variable is no longer recommended, you should leave it at the value t.
4230 Instead, use the key `v' to cycle the archives-mode in the agenda."
4231 :group 'org-archive
4232 :group 'org-agenda-skip
4233 :type 'boolean)
4235 (defcustom org-columns-skip-archived-trees t
4236 "Non-nil means ignore archived trees when creating column view."
4237 :group 'org-archive
4238 :group 'org-properties
4239 :type 'boolean)
4241 (defcustom org-cycle-open-archived-trees nil
4242 "Non-nil means `org-cycle' will open archived trees.
4243 An archived tree is a tree marked with the tag ARCHIVE.
4244 When nil, archived trees will stay folded. You can still open them with
4245 normal outline commands like `show-all', but not with the cycling commands."
4246 :group 'org-archive
4247 :group 'org-cycle
4248 :type 'boolean)
4250 (defcustom org-sparse-tree-open-archived-trees nil
4251 "Non-nil means sparse tree construction shows matches in archived trees.
4252 When nil, matches in these trees are highlighted, but the trees are kept in
4253 collapsed state."
4254 :group 'org-archive
4255 :group 'org-sparse-trees
4256 :type 'boolean)
4258 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4259 "The default date type when building a sparse tree.
4260 When this is nil, a date is a scheduled or a deadline timestamp.
4261 Otherwise, these types are allowed:
4263 all: all timestamps
4264 active: only active timestamps (<...>)
4265 inactive: only inactive timestamps (<...)
4266 scheduled: only scheduled timestamps
4267 deadline: only deadline timestamps"
4268 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4269 (const :tag "All timestamps" all)
4270 (const :tag "Only active timestamps" active)
4271 (const :tag "Only inactive timestamps" inactive)
4272 (const :tag "Only scheduled timestamps" scheduled)
4273 (const :tag "Only deadline timestamps" deadline))
4274 ;; :version "24.3"
4275 :group 'org-sparse-trees)
4277 (defun org-cycle-hide-archived-subtrees (state)
4278 "Re-hide all archived subtrees after a visibility state change."
4279 (when (and (not org-cycle-open-archived-trees)
4280 (not (memq state '(overview folded))))
4281 (save-excursion
4282 (let* ((globalp (memq state '(contents all)))
4283 (beg (if globalp (point-min) (point)))
4284 (end (if globalp (point-max) (org-end-of-subtree t))))
4285 (org-hide-archived-subtrees beg end)
4286 (goto-char beg)
4287 (if (looking-at (concat ".*:" org-archive-tag ":"))
4288 (message "%s" (substitute-command-keys
4289 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4291 (defun org-force-cycle-archived ()
4292 "Cycle subtree even if it is archived."
4293 (interactive)
4294 (setq this-command 'org-cycle)
4295 (let ((org-cycle-open-archived-trees t))
4296 (call-interactively 'org-cycle)))
4298 (defun org-hide-archived-subtrees (beg end)
4299 "Re-hide all archived subtrees after a visibility state change."
4300 (save-excursion
4301 (let* ((re (concat ":" org-archive-tag ":")))
4302 (goto-char beg)
4303 (while (re-search-forward re end t)
4304 (when (org-at-heading-p)
4305 (org-flag-subtree t)
4306 (org-end-of-subtree t))))))
4308 (declare-function outline-end-of-heading "outline" ())
4309 (declare-function outline-flag-region "outline" (from to flag))
4310 (defun org-flag-subtree (flag)
4311 (save-excursion
4312 (org-back-to-heading t)
4313 (outline-end-of-heading)
4314 (outline-flag-region (point)
4315 (progn (org-end-of-subtree t) (point))
4316 flag)))
4318 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4320 (eval-and-compile
4321 (org-autoload "org-archive"
4322 '(org-add-archive-files org-archive-subtree
4323 org-archive-to-archive-sibling org-toggle-archive-tag
4324 org-archive-subtree-default
4325 org-archive-subtree-default-with-confirmation)))
4327 ;; Autoload Column View Code
4329 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4330 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4331 (declare-function org-columns-compute "org-colview" (property))
4333 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4334 '(org-columns-number-to-string org-columns-get-format-and-top-level
4335 org-columns-compute org-agenda-columns org-columns-remove-overlays
4336 org-columns org-insert-columns-dblock org-dblock-write:columnview))
4338 ;; Autoload ID code
4340 (declare-function org-id-store-link "org-id")
4341 (declare-function org-id-locations-load "org-id")
4342 (declare-function org-id-locations-save "org-id")
4343 (defvar org-id-track-globally)
4344 (org-autoload "org-id"
4345 '(org-id-get-create org-id-new org-id-copy org-id-get
4346 org-id-get-with-outline-path-completion
4347 org-id-get-with-outline-drilling org-id-store-link
4348 org-id-goto org-id-find org-id-store-link))
4350 ;; Autoload Plotting Code
4352 (org-autoload "org-plot"
4353 '(org-plot/gnuplot))
4355 ;;; Variables for pre-computed regular expressions, all buffer local
4357 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4358 "Matches first line of a hidden block.")
4359 (make-variable-buffer-local 'org-drawer-regexp)
4360 (defvar org-todo-regexp nil
4361 "Matches any of the TODO state keywords.")
4362 (make-variable-buffer-local 'org-todo-regexp)
4363 (defvar org-not-done-regexp nil
4364 "Matches any of the TODO state keywords except the last one.")
4365 (make-variable-buffer-local 'org-not-done-regexp)
4366 (defvar org-not-done-heading-regexp nil
4367 "Matches a TODO headline that is not done.")
4368 (make-variable-buffer-local 'org-not-done-regexp)
4369 (defvar org-todo-line-regexp nil
4370 "Matches a headline and puts TODO state into group 2 if present.")
4371 (make-variable-buffer-local 'org-todo-line-regexp)
4372 (defvar org-complex-heading-regexp nil
4373 "Matches a headline and puts everything into groups:
4374 group 1: the stars
4375 group 2: The todo keyword, maybe
4376 group 3: Priority cookie
4377 group 4: True headline
4378 group 5: Tags")
4379 (make-variable-buffer-local 'org-complex-heading-regexp)
4380 (defvar org-complex-heading-regexp-format nil
4381 "Printf format to make regexp to match an exact headline.
4382 This regexp will match the headline of any node which has the
4383 exact headline text that is put into the format, but may have any
4384 TODO state, priority and tags.")
4385 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4386 (defvar org-todo-line-tags-regexp nil
4387 "Matches a headline and puts TODO state into group 2 if present.
4388 Also put tags into group 4 if tags are present.")
4389 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4390 (defvar org-ds-keyword-length 12
4391 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4392 (make-variable-buffer-local 'org-ds-keyword-length)
4393 (defvar org-deadline-regexp nil
4394 "Matches the DEADLINE keyword.")
4395 (make-variable-buffer-local 'org-deadline-regexp)
4396 (defvar org-deadline-time-regexp nil
4397 "Matches the DEADLINE keyword together with a time stamp.")
4398 (make-variable-buffer-local 'org-deadline-time-regexp)
4399 (defvar org-deadline-line-regexp nil
4400 "Matches the DEADLINE keyword and the rest of the line.")
4401 (make-variable-buffer-local 'org-deadline-line-regexp)
4402 (defvar org-scheduled-regexp nil
4403 "Matches the SCHEDULED keyword.")
4404 (make-variable-buffer-local 'org-scheduled-regexp)
4405 (defvar org-scheduled-time-regexp nil
4406 "Matches the SCHEDULED keyword together with a time stamp.")
4407 (make-variable-buffer-local 'org-scheduled-time-regexp)
4408 (defvar org-closed-time-regexp nil
4409 "Matches the CLOSED keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-closed-time-regexp)
4412 (defvar org-keyword-time-regexp nil
4413 "Matches any of the 4 keywords, together with the time stamp.")
4414 (make-variable-buffer-local 'org-keyword-time-regexp)
4415 (defvar org-keyword-time-not-clock-regexp nil
4416 "Matches any of the 3 keywords, together with the time stamp.")
4417 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4418 (defvar org-maybe-keyword-time-regexp nil
4419 "Matches a timestamp, possibly preceded by a keyword.")
4420 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4421 (defvar org-all-time-keywords nil
4422 "List of time keywords.")
4423 (make-variable-buffer-local 'org-all-time-keywords)
4425 (defconst org-plain-time-of-day-regexp
4426 (concat
4427 "\\(\\<[012]?[0-9]"
4428 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4429 "\\(--?"
4430 "\\(\\<[012]?[0-9]"
4431 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4432 "\\)?")
4433 "Regular expression to match a plain time or time range.
4434 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4435 groups carry important information:
4436 0 the full match
4437 1 the first time, range or not
4438 8 the second time, if it is a range.")
4440 (defconst org-plain-time-extension-regexp
4441 (concat
4442 "\\(\\<[012]?[0-9]"
4443 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4444 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4445 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4446 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4447 groups carry important information:
4448 0 the full match
4449 7 hours of duration
4450 9 minutes of duration")
4452 (defconst org-stamp-time-of-day-regexp
4453 (concat
4454 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4455 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4456 "\\(--?"
4457 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4458 "Regular expression to match a timestamp time or time range.
4459 After a match, the following groups carry important information:
4460 0 the full match
4461 1 date plus weekday, for back referencing to make sure both times are on the same day
4462 2 the first time, range or not
4463 4 the second time, if it is a range.")
4465 (defconst org-startup-options
4466 '(("fold" org-startup-folded t)
4467 ("overview" org-startup-folded t)
4468 ("nofold" org-startup-folded nil)
4469 ("showall" org-startup-folded nil)
4470 ("showeverything" org-startup-folded showeverything)
4471 ("content" org-startup-folded content)
4472 ("indent" org-startup-indented t)
4473 ("noindent" org-startup-indented nil)
4474 ("hidestars" org-hide-leading-stars t)
4475 ("showstars" org-hide-leading-stars nil)
4476 ("odd" org-odd-levels-only t)
4477 ("oddeven" org-odd-levels-only nil)
4478 ("align" org-startup-align-all-tables t)
4479 ("noalign" org-startup-align-all-tables nil)
4480 ("inlineimages" org-startup-with-inline-images t)
4481 ("noinlineimages" org-startup-with-inline-images nil)
4482 ("customtime" org-display-custom-times t)
4483 ("logdone" org-log-done time)
4484 ("lognotedone" org-log-done note)
4485 ("nologdone" org-log-done nil)
4486 ("lognoteclock-out" org-log-note-clock-out t)
4487 ("nolognoteclock-out" org-log-note-clock-out nil)
4488 ("logrepeat" org-log-repeat state)
4489 ("lognoterepeat" org-log-repeat note)
4490 ("nologrepeat" org-log-repeat nil)
4491 ("logreschedule" org-log-reschedule time)
4492 ("lognotereschedule" org-log-reschedule note)
4493 ("nologreschedule" org-log-reschedule nil)
4494 ("logredeadline" org-log-redeadline time)
4495 ("lognoteredeadline" org-log-redeadline note)
4496 ("nologredeadline" org-log-redeadline nil)
4497 ("logrefile" org-log-refile time)
4498 ("lognoterefile" org-log-refile note)
4499 ("nologrefile" org-log-refile nil)
4500 ("fninline" org-footnote-define-inline t)
4501 ("nofninline" org-footnote-define-inline nil)
4502 ("fnlocal" org-footnote-section nil)
4503 ("fnauto" org-footnote-auto-label t)
4504 ("fnprompt" org-footnote-auto-label nil)
4505 ("fnconfirm" org-footnote-auto-label confirm)
4506 ("fnplain" org-footnote-auto-label plain)
4507 ("fnadjust" org-footnote-auto-adjust t)
4508 ("nofnadjust" org-footnote-auto-adjust nil)
4509 ("constcgs" constants-unit-system cgs)
4510 ("constSI" constants-unit-system SI)
4511 ("noptag" org-tag-persistent-alist nil)
4512 ("hideblocks" org-hide-block-startup t)
4513 ("nohideblocks" org-hide-block-startup nil)
4514 ("beamer" org-startup-with-beamer-mode t)
4515 ("entitiespretty" org-pretty-entities t)
4516 ("entitiesplain" org-pretty-entities nil))
4517 "Variable associated with STARTUP options for org-mode.
4518 Each element is a list of three items: the startup options (as written
4519 in the #+STARTUP line), the corresponding variable, and the value to set
4520 this variable to if the option is found. An optional forth element PUSH
4521 means to push this value onto the list in the variable.")
4523 (defun org-update-property-plist (key val props)
4524 "Update PROPS with KEY and VAL."
4525 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4526 (key (if appending (substring key 0 (- (length key) 1)) key))
4527 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4528 (previous (cdr (assoc key props))))
4529 (if appending
4530 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4531 (cons (cons key val) remainder))))
4533 (defconst org-block-regexp
4534 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4535 "Regular expression for hiding blocks.")
4536 (defconst org-heading-keyword-regexp-format
4537 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4538 "Printf format for a regexp matching an headline with some keyword.
4539 This regexp will match the headline of any node which has the
4540 exact keyword that is put into the format. The keyword isn't in
4541 any group by default, but the stars and the body are.")
4542 (defconst org-heading-keyword-maybe-regexp-format
4543 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4544 "Printf format for a regexp matching an headline, possibly with some keyword.
4545 This regexp can match any headline with the specified keyword, or
4546 without a keyword. The keyword isn't in any group by default,
4547 but the stars and the body are.")
4549 (defun org-set-regexps-and-options ()
4550 "Precompute regular expressions for current buffer."
4551 (when (derived-mode-p 'org-mode)
4552 (org-set-local 'org-todo-kwd-alist nil)
4553 (org-set-local 'org-todo-key-alist nil)
4554 (org-set-local 'org-todo-key-trigger nil)
4555 (org-set-local 'org-todo-keywords-1 nil)
4556 (org-set-local 'org-done-keywords nil)
4557 (org-set-local 'org-todo-heads nil)
4558 (org-set-local 'org-todo-sets nil)
4559 (org-set-local 'org-todo-log-states nil)
4560 (org-set-local 'org-file-properties nil)
4561 (org-set-local 'org-file-tags nil)
4562 (let ((re (org-make-options-regexp
4563 '("CATEGORY" "TODO" "COLUMNS"
4564 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4565 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4566 "OPTIONS")
4567 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4568 (splitre "[ \t]+")
4569 (scripts org-use-sub-superscripts)
4570 kwds kws0 kwsa key log value cat arch tags const links hw dws
4571 tail sep kws1 prio props ftags drawers beamer-p
4572 ext-setup-or-nil setup-contents (start 0))
4573 (save-excursion
4574 (save-restriction
4575 (widen)
4576 (goto-char (point-min))
4577 (while (or (and ext-setup-or-nil
4578 (string-match re ext-setup-or-nil start)
4579 (setq start (match-end 0)))
4580 (and (setq ext-setup-or-nil nil start 0)
4581 (re-search-forward re nil t)))
4582 (setq key (upcase (match-string 1 ext-setup-or-nil))
4583 value (org-match-string-no-properties 2 ext-setup-or-nil))
4584 (if (stringp value) (setq value (org-trim value)))
4585 (cond
4586 ((equal key "CATEGORY")
4587 (setq cat value))
4588 ((member key '("SEQ_TODO" "TODO"))
4589 (push (cons 'sequence (org-split-string value splitre)) kwds))
4590 ((equal key "TYP_TODO")
4591 (push (cons 'type (org-split-string value splitre)) kwds))
4592 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4593 ;; general TODO-like setup
4594 (push (cons (intern (downcase (match-string 1 key)))
4595 (org-split-string value splitre)) kwds))
4596 ((equal key "TAGS")
4597 (setq tags (append tags (if tags '("\\n") nil)
4598 (org-split-string value splitre))))
4599 ((equal key "COLUMNS")
4600 (org-set-local 'org-columns-default-format value))
4601 ((equal key "LINK")
4602 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4603 (push (cons (match-string 1 value)
4604 (org-trim (match-string 2 value)))
4605 links)))
4606 ((equal key "PRIORITIES")
4607 (setq prio (org-split-string value " +")))
4608 ((equal key "PROPERTY")
4609 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4610 (setq props (org-update-property-plist (match-string 1 value)
4611 (match-string 2 value)
4612 props))))
4613 ((equal key "FILETAGS")
4614 (when (string-match "\\S-" value)
4615 (setq ftags
4616 (append
4617 ftags
4618 (apply 'append
4619 (mapcar (lambda (x) (org-split-string x ":"))
4620 (org-split-string value)))))))
4621 ((equal key "DRAWERS")
4622 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4623 ((equal key "CONSTANTS")
4624 (setq const (append const (org-split-string value splitre))))
4625 ((equal key "STARTUP")
4626 (let ((opts (org-split-string value splitre))
4627 l var val)
4628 (while (setq l (pop opts))
4629 (when (setq l (assoc l org-startup-options))
4630 (setq var (nth 1 l) val (nth 2 l))
4631 (if (not (nth 3 l))
4632 (set (make-local-variable var) val)
4633 (if (not (listp (symbol-value var)))
4634 (set (make-local-variable var) nil))
4635 (set (make-local-variable var) (symbol-value var))
4636 (add-to-list var val))))))
4637 ((equal key "ARCHIVE")
4638 (setq arch value)
4639 (remove-text-properties 0 (length arch)
4640 '(face t fontified t) arch))
4641 ((equal key "LATEX_CLASS")
4642 (setq beamer-p (equal value "beamer")))
4643 ((equal key "OPTIONS")
4644 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4645 (setq scripts (read (match-string 2 value)))))
4646 ((equal key "SETUPFILE")
4647 (setq setup-contents (org-file-contents
4648 (expand-file-name
4649 (org-remove-double-quotes value))
4650 'noerror))
4651 (if (not ext-setup-or-nil)
4652 (setq ext-setup-or-nil setup-contents start 0)
4653 (setq ext-setup-or-nil
4654 (concat (substring ext-setup-or-nil 0 start)
4655 "\n" setup-contents "\n"
4656 (substring ext-setup-or-nil start)))))))
4657 ;; search for property blocks
4658 (goto-char (point-min))
4659 (while (re-search-forward org-block-regexp nil t)
4660 (when (equal "PROPERTY" (upcase (match-string 1)))
4661 (setq value (replace-regexp-in-string
4662 "[\n\r]" " " (match-string 4)))
4663 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4664 (setq props (org-update-property-plist (match-string 1 value)
4665 (match-string 2 value)
4666 props)))))))
4667 (org-set-local 'org-use-sub-superscripts scripts)
4668 (when cat
4669 (org-set-local 'org-category (intern cat))
4670 (push (cons "CATEGORY" cat) props))
4671 (when prio
4672 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4673 (setq prio (mapcar 'string-to-char prio))
4674 (org-set-local 'org-highest-priority (nth 0 prio))
4675 (org-set-local 'org-lowest-priority (nth 1 prio))
4676 (org-set-local 'org-default-priority (nth 2 prio)))
4677 (and props (org-set-local 'org-file-properties (nreverse props)))
4678 (and ftags (org-set-local 'org-file-tags
4679 (mapcar 'org-add-prop-inherited ftags)))
4680 (and drawers (org-set-local 'org-drawers drawers))
4681 (and arch (org-set-local 'org-archive-location arch))
4682 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4683 ;; Process the TODO keywords
4684 (unless kwds
4685 ;; Use the global values as if they had been given locally.
4686 (setq kwds (default-value 'org-todo-keywords))
4687 (if (stringp (car kwds))
4688 (setq kwds (list (cons org-todo-interpretation
4689 (default-value 'org-todo-keywords)))))
4690 (setq kwds (reverse kwds)))
4691 (setq kwds (nreverse kwds))
4692 (let (inter kws kw)
4693 (while (setq kws (pop kwds))
4694 (let ((kws (or
4695 (run-hook-with-args-until-success
4696 'org-todo-setup-filter-hook kws)
4697 kws)))
4698 (setq inter (pop kws) sep (member "|" kws)
4699 kws0 (delete "|" (copy-sequence kws))
4700 kwsa nil
4701 kws1 (mapcar
4702 (lambda (x)
4703 ;; 1 2
4704 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4705 (progn
4706 (setq kw (match-string 1 x)
4707 key (and (match-end 2) (match-string 2 x))
4708 log (org-extract-log-state-settings x))
4709 (push (cons kw (and key (string-to-char key))) kwsa)
4710 (and log (push log org-todo-log-states))
4712 (error "Invalid TODO keyword %s" x)))
4713 kws0)
4714 kwsa (if kwsa (append '((:startgroup))
4715 (nreverse kwsa)
4716 '((:endgroup))))
4717 hw (car kws1)
4718 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4719 tail (list inter hw (car dws) (org-last dws))))
4720 (add-to-list 'org-todo-heads hw 'append)
4721 (push kws1 org-todo-sets)
4722 (setq org-done-keywords (append org-done-keywords dws nil))
4723 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4724 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4725 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4726 (setq org-todo-sets (nreverse org-todo-sets)
4727 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4728 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4729 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4730 ;; Process the constants
4731 (when const
4732 (let (e cst)
4733 (while (setq e (pop const))
4734 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4735 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4736 (setq org-table-formula-constants-local cst)))
4738 ;; Process the tags.
4739 (when tags
4740 (let (e tgs)
4741 (while (setq e (pop tags))
4742 (cond
4743 ((equal e "{") (push '(:startgroup) tgs))
4744 ((equal e "}") (push '(:endgroup) tgs))
4745 ((equal e "\\n") (push '(:newline) tgs))
4746 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4747 (push (cons (match-string 1 e)
4748 (string-to-char (match-string 2 e)))
4749 tgs))
4750 (t (push (list e) tgs))))
4751 (org-set-local 'org-tag-alist nil)
4752 (while (setq e (pop tgs))
4753 (or (and (stringp (car e))
4754 (assoc (car e) org-tag-alist))
4755 (push e org-tag-alist)))))
4757 ;; Compute the regular expressions and other local variables.
4758 ;; Using `org-outline-regexp-bol' would complicate them much,
4759 ;; because of the fixed white space at the end of that string.
4760 (if (not org-done-keywords)
4761 (setq org-done-keywords (and org-todo-keywords-1
4762 (list (org-last org-todo-keywords-1)))))
4763 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4764 (length org-scheduled-string)
4765 (length org-clock-string)
4766 (length org-closed-string)))
4767 org-drawer-regexp
4768 (concat "^[ \t]*:\\("
4769 (mapconcat 'regexp-quote org-drawers "\\|")
4770 "\\):[ \t]*$")
4771 org-not-done-keywords
4772 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4773 org-todo-regexp
4774 (concat "\\("
4775 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4776 "\\)")
4777 org-not-done-regexp
4778 (concat "\\("
4779 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4780 "\\)")
4781 org-not-done-heading-regexp
4782 (format org-heading-keyword-regexp-format org-not-done-regexp)
4783 org-todo-line-regexp
4784 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4785 org-complex-heading-regexp
4786 (concat "^\\(\\*+\\)"
4787 "\\(?: +" org-todo-regexp "\\)?"
4788 "\\(?: +\\(\\[#.\\]\\)\\)?"
4789 "\\(?: +\\(.*?\\)\\)??"
4790 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4791 "[ \t]*$")
4792 org-complex-heading-regexp-format
4793 (concat "^\\(\\*+\\)"
4794 "\\(?: +" org-todo-regexp "\\)?"
4795 "\\(?: +\\(\\[#.\\]\\)\\)?"
4796 "\\(?: +"
4797 ;; Stats cookies can be stuck to body.
4798 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4799 "\\(%s\\)"
4800 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4801 "\\)"
4802 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4803 "[ \t]*$")
4804 org-todo-line-tags-regexp
4805 (concat "^\\(\\*+\\)"
4806 "\\(?: +" org-todo-regexp "\\)?"
4807 "\\(?: +\\(.*?\\)\\)??"
4808 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4809 "[ \t]*$")
4810 org-deadline-regexp (concat "\\<" org-deadline-string)
4811 org-deadline-time-regexp
4812 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4813 org-deadline-line-regexp
4814 (concat "\\<\\(" org-deadline-string "\\).*")
4815 org-scheduled-regexp
4816 (concat "\\<" org-scheduled-string)
4817 org-scheduled-time-regexp
4818 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4819 org-closed-time-regexp
4820 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4821 org-keyword-time-regexp
4822 (concat "\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\|" org-clock-string "\\)"
4826 " *[[<]\\([^]>]+\\)[]>]")
4827 org-keyword-time-not-clock-regexp
4828 (concat "\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4831 "\\)"
4832 " *[[<]\\([^]>]+\\)[]>]")
4833 org-maybe-keyword-time-regexp
4834 (concat "\\(\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\|" org-clock-string "\\)\\)?"
4838 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4839 org-all-time-keywords
4840 (mapcar (lambda (w) (substring w 0 -1))
4841 (list org-scheduled-string org-deadline-string
4842 org-clock-string org-closed-string))
4844 (org-compute-latex-and-specials-regexp)
4845 (org-set-font-lock-defaults))))
4847 (defun org-file-contents (file &optional noerror)
4848 "Return the contents of FILE, as a string."
4849 (if (or (not file)
4850 (not (file-readable-p file)))
4851 (if noerror
4852 (progn
4853 (message "Cannot read file \"%s\"" file)
4854 (ding) (sit-for 2)
4856 (error "Cannot read file \"%s\"" file))
4857 (with-temp-buffer
4858 (insert-file-contents file)
4859 (buffer-string))))
4861 (defun org-extract-log-state-settings (x)
4862 "Extract the log state setting from a TODO keyword string.
4863 This will extract info from a string like \"WAIT(w@/!)\"."
4864 (let (kw key log1 log2)
4865 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4866 (setq kw (match-string 1 x)
4867 key (and (match-end 2) (match-string 2 x))
4868 log1 (and (match-end 3) (match-string 3 x))
4869 log2 (and (match-end 4) (match-string 4 x)))
4870 (and (or log1 log2)
4871 (list kw
4872 (and log1 (if (equal log1 "!") 'time 'note))
4873 (and log2 (if (equal log2 "!") 'time 'note)))))))
4875 (defun org-remove-keyword-keys (list)
4876 "Remove a pair of parenthesis at the end of each string in LIST."
4877 (mapcar (lambda (x)
4878 (if (string-match "(.*)$" x)
4879 (substring x 0 (match-beginning 0))
4881 list))
4883 (defun org-assign-fast-keys (alist)
4884 "Assign fast keys to a keyword-key alist.
4885 Respect keys that are already there."
4886 (let (new e (alt ?0))
4887 (while (setq e (pop alist))
4888 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4889 (cdr e)) ;; Key already assigned.
4890 (push e new)
4891 (let ((clist (string-to-list (downcase (car e))))
4892 (used (append new alist)))
4893 (when (= (car clist) ?@)
4894 (pop clist))
4895 (while (and clist (rassoc (car clist) used))
4896 (pop clist))
4897 (unless clist
4898 (while (rassoc alt used)
4899 (incf alt)))
4900 (push (cons (car e) (or (car clist) alt)) new))))
4901 (nreverse new)))
4903 ;;; Some variables used in various places
4905 (defvar org-window-configuration nil
4906 "Used in various places to store a window configuration.")
4907 (defvar org-selected-window nil
4908 "Used in various places to store a window configuration.")
4909 (defvar org-finish-function nil
4910 "Function to be called when `C-c C-c' is used.
4911 This is for getting out of special buffers like capture.")
4914 ;; FIXME: Occasionally check by commenting these, to make sure
4915 ;; no other functions uses these, forgetting to let-bind them.
4916 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4917 (defvar org-last-state)
4918 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4920 ;; Defined somewhere in this file, but used before definition.
4921 (defvar org-entities) ;; defined in org-entities.el
4922 (defvar org-struct-menu)
4923 (defvar org-org-menu)
4924 (defvar org-tbl-menu)
4926 ;;;; Define the Org-mode
4928 ;; We use a before-change function to check if a table might need
4929 ;; an update.
4930 (defvar org-table-may-need-update t
4931 "Indicates that a table might need an update.
4932 This variable is set by `org-before-change-function'.
4933 `org-table-align' sets it back to nil.")
4934 (defun org-before-change-function (beg end)
4935 "Every change indicates that a table might need an update."
4936 (setq org-table-may-need-update t))
4937 (defvar org-mode-map)
4938 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4939 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4940 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4941 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4942 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4943 (defvar org-table-buffer-is-an nil)
4945 (defvar bidi-paragraph-direction)
4946 (defvar buffer-face-mode-face)
4948 (require 'outline)
4949 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4950 (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"))
4951 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4953 ;; Other stuff we need.
4954 (require 'time-date)
4955 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4956 (require 'easymenu)
4957 (require 'overlay)
4959 (require 'org-macs)
4960 (require 'org-entities)
4961 ;; (require 'org-compat) moved higher up in the file before it is first used
4962 (require 'org-faces)
4963 (require 'org-list)
4964 (require 'org-pcomplete)
4965 (require 'org-src)
4966 (require 'org-footnote)
4968 ;; babel
4969 (require 'ob)
4970 (require 'ob-table)
4971 (require 'ob-lob)
4972 (require 'ob-ref)
4973 (require 'ob-tangle)
4974 (require 'ob-comint)
4975 (require 'ob-keys)
4977 ;;;###autoload
4978 (define-derived-mode org-mode outline-mode "Org"
4979 "Outline-based notes management and organizer, alias
4980 \"Carsten's outline-mode for keeping track of everything.\"
4982 Org-mode develops organizational tasks around a NOTES file which
4983 contains information about projects as plain text. Org-mode is
4984 implemented on top of outline-mode, which is ideal to keep the content
4985 of large files well structured. It supports ToDo items, deadlines and
4986 time stamps, which magically appear in the diary listing of the Emacs
4987 calendar. Tables are easily created with a built-in table editor.
4988 Plain text URL-like links connect to websites, emails (VM), Usenet
4989 messages (Gnus), BBDB entries, and any files related to the project.
4990 For printing and sharing of notes, an Org-mode file (or a part of it)
4991 can be exported as a structured ASCII or HTML file.
4993 The following commands are available:
4995 \\{org-mode-map}"
4997 ;; Get rid of Outline menus, they are not needed
4998 ;; Need to do this here because define-derived-mode sets up
4999 ;; the keymap so late. Still, it is a waste to call this each time
5000 ;; we switch another buffer into org-mode.
5001 (if (featurep 'xemacs)
5002 (when (boundp 'outline-mode-menu-heading)
5003 ;; Assume this is Greg's port, it uses easymenu
5004 (easy-menu-remove outline-mode-menu-heading)
5005 (easy-menu-remove outline-mode-menu-show)
5006 (easy-menu-remove outline-mode-menu-hide))
5007 (define-key org-mode-map [menu-bar headings] 'undefined)
5008 (define-key org-mode-map [menu-bar hide] 'undefined)
5009 (define-key org-mode-map [menu-bar show] 'undefined))
5011 (org-load-modules-maybe)
5012 (easy-menu-add org-org-menu)
5013 (easy-menu-add org-tbl-menu)
5014 (org-install-agenda-files-menu)
5015 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5016 (add-to-invisibility-spec '(org-cwidth))
5017 (add-to-invisibility-spec '(org-hide-block . t))
5018 (when (featurep 'xemacs)
5019 (org-set-local 'line-move-ignore-invisible t))
5020 (org-set-local 'outline-regexp org-outline-regexp)
5021 (org-set-local 'outline-level 'org-outline-level)
5022 (setq bidi-paragraph-direction 'left-to-right)
5023 (when (and org-ellipsis
5024 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5025 (fboundp 'make-glyph-code))
5026 (unless org-display-table
5027 (setq org-display-table (make-display-table)))
5028 (set-display-table-slot
5029 org-display-table 4
5030 (vconcat (mapcar
5031 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5032 org-ellipsis)))
5033 (if (stringp org-ellipsis) org-ellipsis "..."))))
5034 (setq buffer-display-table org-display-table))
5035 (org-set-regexps-and-options)
5036 (when (and org-tag-faces (not org-tags-special-faces-re))
5037 ;; tag faces set outside customize.... force initialization.
5038 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5039 ;; Calc embedded
5040 (org-set-local 'calc-embedded-open-mode "# ")
5041 (modify-syntax-entry ?@ "w")
5042 (if org-startup-truncated (setq truncate-lines t))
5043 (org-set-local 'font-lock-unfontify-region-function
5044 'org-unfontify-region)
5045 ;; Activate before-change-function
5046 (org-set-local 'org-table-may-need-update t)
5047 (org-add-hook 'before-change-functions 'org-before-change-function nil
5048 'local)
5049 ;; Check for running clock before killing a buffer
5050 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5051 ;; Indentation.
5052 (org-set-local 'indent-line-function 'org-indent-line)
5053 (org-set-local 'indent-region-function 'org-indent-region)
5054 ;; Initialize radio targets.
5055 (org-update-radio-target-regexp)
5056 ;; Filling and auto-filling.
5057 (org-setup-filling)
5058 ;; Comments.
5059 (org-setup-comments-handling)
5060 ;; Beginning/end of defun
5061 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5062 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5063 ;; Next error for sparse trees
5064 (org-set-local 'next-error-function 'org-occur-next-match)
5065 ;; Make sure dependence stuff works reliably, even for users who set it
5066 ;; too late :-(
5067 (if org-enforce-todo-dependencies
5068 (add-hook 'org-blocker-hook
5069 'org-block-todo-from-children-or-siblings-or-parent)
5070 (remove-hook 'org-blocker-hook
5071 'org-block-todo-from-children-or-siblings-or-parent))
5072 (if org-enforce-todo-checkbox-dependencies
5073 (add-hook 'org-blocker-hook
5074 'org-block-todo-from-checkboxes)
5075 (remove-hook 'org-blocker-hook
5076 'org-block-todo-from-checkboxes))
5078 ;; Align options lines
5079 (org-set-local
5080 'align-mode-rules-list
5081 '((org-in-buffer-settings
5082 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5083 (modes . '(org-mode)))))
5085 ;; Imenu
5086 (org-set-local 'imenu-create-index-function
5087 'org-imenu-get-tree)
5089 ;; Make isearch reveal context
5090 (if (or (featurep 'xemacs)
5091 (not (boundp 'outline-isearch-open-invisible-function)))
5092 ;; Emacs 21 and XEmacs make use of the hook
5093 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5094 ;; Emacs 22 deals with this through a special variable
5095 (org-set-local 'outline-isearch-open-invisible-function
5096 (lambda (&rest ignore) (org-show-context 'isearch))))
5098 ;; Turn on org-beamer-mode?
5099 (and org-startup-with-beamer-mode (org-beamer-mode 1))
5101 ;; Setup the pcomplete hooks
5102 (set (make-local-variable 'pcomplete-command-completion-function)
5103 'org-pcomplete-initial)
5104 (set (make-local-variable 'pcomplete-command-name-function)
5105 'org-command-at-point)
5106 (set (make-local-variable 'pcomplete-default-completion-function)
5107 'ignore)
5108 (set (make-local-variable 'pcomplete-parse-arguments-function)
5109 'org-parse-arguments)
5110 (set (make-local-variable 'pcomplete-termination-string) "")
5111 (when (>= emacs-major-version 23)
5112 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5114 ;; If empty file that did not turn on org-mode automatically, make it to.
5115 (if (and org-insert-mode-line-in-empty-file
5116 (org-called-interactively-p 'any)
5117 (= (point-min) (point-max)))
5118 (insert "# -*- mode: org -*-\n\n"))
5119 (unless org-inhibit-startup
5120 (when org-startup-align-all-tables
5121 (let ((bmp (buffer-modified-p)))
5122 (org-table-map-tables 'org-table-align 'quietly)
5123 (set-buffer-modified-p bmp)))
5124 (when org-startup-with-inline-images
5125 (org-display-inline-images))
5126 (when org-startup-indented
5127 (require 'org-indent)
5128 (org-indent-mode 1))
5129 (unless org-inhibit-startup-visibility-stuff
5130 (org-set-startup-visibility)))
5131 ;; Try to set org-hide correctly
5132 (set-face-foreground
5133 'org-hide
5134 (or (face-background 'default)
5135 (face-background 'org-default)
5136 (cdr (assoc 'background-color default-frame-alist))
5137 (cdr (assoc 'background-color initial-frame-alist))
5138 (cdr (assoc 'background-color window-system-default-frame-alist))
5139 (face-foreground 'org-hide))))
5141 (when (fboundp 'abbrev-table-put)
5142 (abbrev-table-put org-mode-abbrev-table
5143 :parents (list text-mode-abbrev-table)))
5145 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5147 (defun org-current-time ()
5148 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5149 (if (> (car org-time-stamp-rounding-minutes) 1)
5150 (let ((r (car org-time-stamp-rounding-minutes))
5151 (time (decode-time)))
5152 (apply 'encode-time
5153 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5154 (nthcdr 2 time))))
5155 (current-time)))
5157 (defun org-today ()
5158 "Return today date, considering `org-extend-today-until'."
5159 (time-to-days
5160 (time-subtract (current-time)
5161 (list 0 (* 3600 org-extend-today-until) 0))))
5163 ;;;; Font-Lock stuff, including the activators
5165 (defvar org-mouse-map (make-sparse-keymap))
5166 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5167 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5168 (when org-mouse-1-follows-link
5169 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5170 (when org-tab-follows-link
5171 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5172 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5174 (require 'font-lock)
5176 (defconst org-non-link-chars "]\t\n\r<>")
5177 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5178 "shell" "elisp" "doi" "message"))
5179 (defvar org-link-types-re nil
5180 "Matches a link that has a url-like prefix like \"http:\"")
5181 (defvar org-link-re-with-space nil
5182 "Matches a link with spaces, optional angular brackets around it.")
5183 (defvar org-link-re-with-space2 nil
5184 "Matches a link with spaces, optional angular brackets around it.")
5185 (defvar org-link-re-with-space3 nil
5186 "Matches a link with spaces, only for internal part in bracket links.")
5187 (defvar org-angle-link-re nil
5188 "Matches link with angular brackets, spaces are allowed.")
5189 (defvar org-plain-link-re nil
5190 "Matches plain link, without spaces.")
5191 (defvar org-bracket-link-regexp nil
5192 "Matches a link in double brackets.")
5193 (defvar org-bracket-link-analytic-regexp nil
5194 "Regular expression used to analyze links.
5195 Here is what the match groups contain after a match:
5196 1: http:
5197 2: http
5198 3: path
5199 4: [desc]
5200 5: desc")
5201 (defvar org-bracket-link-analytic-regexp++ nil
5202 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5203 (defvar org-any-link-re nil
5204 "Regular expression matching any link.")
5206 (defcustom org-match-sexp-depth 3
5207 "Number of stacked braces for sub/superscript matching.
5208 This has to be set before loading org.el to be effective."
5209 :group 'org-export-translation ; ??????????????????????????/
5210 :type 'integer)
5212 (defun org-create-multibrace-regexp (left right n)
5213 "Create a regular expression which will match a balanced sexp.
5214 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5215 as single character strings.
5216 The regexp returned will match the entire expression including the
5217 delimiters. It will also define a single group which contains the
5218 match except for the outermost delimiters. The maximum depth of
5219 stacked delimiters is N. Escaping delimiters is not possible."
5220 (let* ((nothing (concat "[^" left right "]*?"))
5221 (or "\\|")
5222 (re nothing)
5223 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5224 (while (> n 1)
5225 (setq n (1- n)
5226 re (concat re or next)
5227 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5228 (concat left "\\(" re "\\)" right)))
5230 (defvar org-match-substring-regexp
5231 (concat
5232 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5233 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5234 "\\|"
5235 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5236 "\\|"
5237 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5238 "The regular expression matching a sub- or superscript.")
5240 (defvar org-match-substring-with-braces-regexp
5241 (concat
5242 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5243 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5244 "\\)")
5245 "The regular expression matching a sub- or superscript, forcing braces.")
5247 (defun org-make-link-regexps ()
5248 "Update the link regular expressions.
5249 This should be called after the variable `org-link-types' has changed."
5250 (setq org-link-types-re
5251 (concat
5252 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5253 org-link-re-with-space
5254 (concat
5255 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5256 "\\([^" org-non-link-chars " ]"
5257 "[^" org-non-link-chars "]*"
5258 "[^" org-non-link-chars " ]\\)>?")
5259 org-link-re-with-space2
5260 (concat
5261 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5262 "\\([^" org-non-link-chars " ]"
5263 "[^\t\n\r]*"
5264 "[^" org-non-link-chars " ]\\)>?")
5265 org-link-re-with-space3
5266 (concat
5267 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5268 "\\([^" org-non-link-chars " ]"
5269 "[^\t\n\r]*\\)")
5270 org-angle-link-re
5271 (concat
5272 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5273 "\\([^" org-non-link-chars " ]"
5274 "[^" org-non-link-chars "]*"
5275 "\\)>")
5276 org-plain-link-re
5277 (concat
5278 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5279 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5280 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5281 org-bracket-link-regexp
5282 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5283 org-bracket-link-analytic-regexp
5284 (concat
5285 "\\[\\["
5286 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5287 "\\([^]]+\\)"
5288 "\\]"
5289 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5290 "\\]")
5291 org-bracket-link-analytic-regexp++
5292 (concat
5293 "\\[\\["
5294 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5295 "\\([^]]+\\)"
5296 "\\]"
5297 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5298 "\\]")
5299 org-any-link-re
5300 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5301 org-angle-link-re "\\)\\|\\("
5302 org-plain-link-re "\\)")))
5304 (org-make-link-regexps)
5306 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5307 "Regular expression for fast time stamp matching.")
5308 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5309 "Regular expression for fast time stamp matching.")
5310 (defconst org-ts-regexp0
5311 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5312 "Regular expression matching time strings for analysis.
5313 This one does not require the space after the date, so it can be used
5314 on a string that terminates immediately after the date.")
5315 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5316 "Regular expression matching time strings for analysis.")
5317 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5318 "Regular expression matching time stamps, with groups.")
5319 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5320 "Regular expression matching time stamps (also [..]), with groups.")
5321 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5322 "Regular expression matching a time stamp range.")
5323 (defconst org-tr-regexp-both
5324 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5325 "Regular expression matching a time stamp range.")
5326 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5327 org-ts-regexp "\\)?")
5328 "Regular expression matching a time stamp or time stamp range.")
5329 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5330 org-ts-regexp-both "\\)?")
5331 "Regular expression matching a time stamp or time stamp range.
5332 The time stamps may be either active or inactive.")
5334 (defvar org-emph-face nil)
5336 (defun org-do-emphasis-faces (limit)
5337 "Run through the buffer and add overlays to emphasized strings."
5338 (let (rtn a)
5339 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5340 (if (not (= (char-after (match-beginning 3))
5341 (char-after (match-beginning 4))))
5342 (progn
5343 (setq rtn t)
5344 (setq a (assoc (match-string 3) org-emphasis-alist))
5345 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5346 'face
5347 (nth 1 a))
5348 (and (nth 4 a)
5349 (org-remove-flyspell-overlays-in
5350 (match-beginning 0) (match-end 0)))
5351 (add-text-properties (match-beginning 2) (match-end 2)
5352 '(font-lock-multiline t org-emphasis t))
5353 (when org-hide-emphasis-markers
5354 (add-text-properties (match-end 4) (match-beginning 5)
5355 '(invisible org-link))
5356 (add-text-properties (match-beginning 3) (match-end 3)
5357 '(invisible org-link)))))
5358 (backward-char 1))
5359 rtn))
5361 (defun org-emphasize (&optional char)
5362 "Insert or change an emphasis, i.e. a font like bold or italic.
5363 If there is an active region, change that region to a new emphasis.
5364 If there is no region, just insert the marker characters and position
5365 the cursor between them.
5366 CHAR should be either the marker character, or the first character of the
5367 HTML tag associated with that emphasis. If CHAR is a space, the means
5368 to remove the emphasis of the selected region.
5369 If char is not given (for example in an interactive call) it
5370 will be prompted for."
5371 (interactive)
5372 (let ((eal org-emphasis-alist) e det
5373 (erc org-emphasis-regexp-components)
5374 (prompt "")
5375 (string "") beg end move tag c s)
5376 (if (org-region-active-p)
5377 (setq beg (region-beginning) end (region-end)
5378 string (buffer-substring beg end))
5379 (setq move t))
5381 (while (setq e (pop eal))
5382 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5383 c (aref tag 0))
5384 (push (cons c (string-to-char (car e))) det)
5385 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5386 (substring tag 1)))))
5387 (setq det (nreverse det))
5388 (unless char
5389 (message "%s" (concat "Emphasis marker or tag:" prompt))
5390 (setq char (read-char-exclusive)))
5391 (setq char (or (cdr (assoc char det)) char))
5392 (if (equal char ?\ )
5393 (setq s "" move nil)
5394 (unless (assoc (char-to-string char) org-emphasis-alist)
5395 (error "No such emphasis marker: \"%c\"" char))
5396 (setq s (char-to-string char)))
5397 (while (and (> (length string) 1)
5398 (equal (substring string 0 1) (substring string -1))
5399 (assoc (substring string 0 1) org-emphasis-alist))
5400 (setq string (substring string 1 -1)))
5401 (setq string (concat s string s))
5402 (if beg (delete-region beg end))
5403 (unless (or (bolp)
5404 (string-match (concat "[" (nth 0 erc) "\n]")
5405 (char-to-string (char-before (point)))))
5406 (insert " "))
5407 (unless (or (eobp)
5408 (string-match (concat "[" (nth 1 erc) "\n]")
5409 (char-to-string (char-after (point)))))
5410 (insert " ") (backward-char 1))
5411 (insert string)
5412 (and move (backward-char 1))))
5414 (defconst org-nonsticky-props
5415 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5417 (defsubst org-rear-nonsticky-at (pos)
5418 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5420 (defun org-activate-plain-links (limit)
5421 "Run through the buffer and add overlays to links."
5422 (catch 'exit
5423 (let (f)
5424 (when (re-search-forward (concat org-plain-link-re) limit t)
5425 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5426 (setq f (get-text-property (match-beginning 0) 'face))
5427 (if (or (eq f 'org-tag)
5428 (and (listp f) (memq 'org-tag f)))
5430 (add-text-properties (match-beginning 0) (match-end 0)
5431 (list 'mouse-face 'highlight
5432 'face 'org-link
5433 'keymap org-mouse-map))
5434 (org-rear-nonsticky-at (match-end 0)))
5435 t))))
5437 (defun org-activate-code (limit)
5438 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5439 (progn
5440 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5441 (remove-text-properties (match-beginning 0) (match-end 0)
5442 '(display t invisible t intangible t))
5443 t)))
5445 (defcustom org-src-fontify-natively nil
5446 "When non-nil, fontify code in code blocks."
5447 :type 'boolean
5448 :version "24.1"
5449 :group 'org-appearance
5450 :group 'org-babel)
5452 (defcustom org-allow-promoting-top-level-subtree nil
5453 "When non-nil, allow promoting a top level subtree.
5454 The leading star of the top level headline will be replaced
5455 by a #."
5456 :type 'boolean
5457 :version "24.1"
5458 :group 'org-appearance)
5460 (defun org-fontify-meta-lines-and-blocks (limit)
5461 (condition-case nil
5462 (org-fontify-meta-lines-and-blocks-1 limit)
5463 (error (message "org-mode fontification error"))))
5465 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5466 "Fontify #+ lines and blocks, in the correct ways."
5467 (let ((case-fold-search t))
5468 (if (re-search-forward
5469 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5470 limit t)
5471 (let ((beg (match-beginning 0))
5472 (block-start (match-end 0))
5473 (block-end nil)
5474 (lang (match-string 7))
5475 (beg1 (line-beginning-position 2))
5476 (dc1 (downcase (match-string 2)))
5477 (dc3 (downcase (match-string 3)))
5478 end end1 quoting block-type ovl)
5479 (cond
5480 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5481 ;; a single line of backend-specific content
5482 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5483 (remove-text-properties (match-beginning 0) (match-end 0)
5484 '(display t invisible t intangible t))
5485 (add-text-properties (match-beginning 1) (match-end 3)
5486 '(font-lock-fontified t face org-meta-line))
5487 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5488 '(font-lock-fontified t face org-block))
5489 ; for backend-specific code
5491 ((and (match-end 4) (equal dc3 "+begin"))
5492 ;; Truly a block
5493 (setq block-type (downcase (match-string 5))
5494 quoting (member block-type org-protecting-blocks))
5495 (when (re-search-forward
5496 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5497 nil t) ;; on purpose, we look further than LIMIT
5498 (setq end (min (point-max) (match-end 0))
5499 end1 (min (point-max) (1- (match-beginning 0))))
5500 (setq block-end (match-beginning 0))
5501 (when quoting
5502 (remove-text-properties beg end
5503 '(display t invisible t intangible t)))
5504 (add-text-properties
5505 beg end
5506 '(font-lock-fontified t font-lock-multiline t))
5507 (add-text-properties beg beg1 '(face org-meta-line))
5508 (add-text-properties end1 (min (point-max) (1+ end))
5509 '(face org-meta-line)) ; for end_src
5510 (cond
5511 ((and lang (not (string= lang "")) org-src-fontify-natively)
5512 (org-src-font-lock-fontify-block lang block-start block-end)
5513 ;; remove old background overlays
5514 (mapc (lambda (ov)
5515 (if (eq (overlay-get ov 'face) 'org-block-background)
5516 (delete-overlay ov)))
5517 (overlays-at (/ (+ beg1 block-end) 2)))
5518 ;; add a background overlay
5519 (setq ovl (make-overlay beg1 block-end))
5520 (overlay-put ovl 'face 'org-block-background)
5521 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5522 (quoting
5523 (add-text-properties beg1 (min (point-max) (1+ end1))
5524 '(face org-block))) ; end of source block
5525 ((not org-fontify-quote-and-verse-blocks))
5526 ((string= block-type "quote")
5527 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5528 ((string= block-type "verse")
5529 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5530 (add-text-properties beg beg1 '(face org-block-begin-line))
5531 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5532 '(face org-block-end-line))
5534 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5535 (add-text-properties
5536 beg (match-end 3)
5537 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5538 '(font-lock-fontified t invisible t)
5539 '(font-lock-fontified t face org-document-info-keyword)))
5540 (add-text-properties
5541 (match-beginning 6) (match-end 6)
5542 (if (string-equal dc1 "+title:")
5543 '(font-lock-fontified t face org-document-title)
5544 '(font-lock-fontified t face org-document-info))))
5545 ((or (equal dc1 "+results")
5546 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5547 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5548 "+call:" "+header:" "+headers:" "+name:"))
5549 (and (match-end 4) (equal dc3 "+attr")))
5550 (add-text-properties
5551 beg (match-end 0)
5552 '(font-lock-fontified t face org-meta-line))
5554 ((member dc3 '(" " ""))
5555 (add-text-properties
5556 beg (match-end 0)
5557 '(font-lock-fontified t face font-lock-comment-face)))
5558 ((not (member (char-after beg) '(?\ ?\t)))
5559 ;; just any other in-buffer setting, but not indented
5560 (add-text-properties
5561 beg (match-end 0)
5562 '(font-lock-fontified t face org-meta-line))
5564 (t nil))))))
5566 (defun org-strip-protective-commas (beg end)
5567 "Strip protective commas between BEG and END in the current buffer."
5568 (interactive "r")
5569 (save-excursion
5570 (save-match-data
5571 (goto-char beg)
5572 (let ((front-line (save-excursion
5573 (re-search-forward
5574 "[^[:space:]]" end t)
5575 (goto-char (match-beginning 0))
5576 (current-column))))
5577 (while (re-search-forward "^[ \t]*\\(,\\)\\([*]\\|#\\)" end t)
5578 (goto-char (match-beginning 1))
5579 (when (= (current-column) front-line)
5580 (replace-match "" nil nil nil 1)))))))
5582 (defun org-activate-angle-links (limit)
5583 "Run through the buffer and add overlays to links."
5584 (if (re-search-forward org-angle-link-re limit t)
5585 (progn
5586 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5587 (add-text-properties (match-beginning 0) (match-end 0)
5588 (list 'mouse-face 'highlight
5589 'keymap org-mouse-map))
5590 (org-rear-nonsticky-at (match-end 0))
5591 t)))
5593 (defun org-activate-footnote-links (limit)
5594 "Run through the buffer and add overlays to footnotes."
5595 (let ((fn (org-footnote-next-reference-or-definition limit)))
5596 (when fn
5597 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5598 (org-remove-flyspell-overlays-in beg end)
5599 (add-text-properties beg end
5600 (list 'mouse-face 'highlight
5601 'keymap org-mouse-map
5602 'help-echo
5603 (if (= (point-at-bol) beg)
5604 "Footnote definition"
5605 "Footnote reference")
5606 'font-lock-fontified t
5607 'font-lock-multiline t
5608 'face 'org-footnote))))))
5610 (defun org-activate-bracket-links (limit)
5611 "Run through the buffer and add overlays to bracketed links."
5612 (if (re-search-forward org-bracket-link-regexp limit t)
5613 (let* ((help (concat "LINK: "
5614 (org-match-string-no-properties 1)))
5615 ;; FIXME: above we should remove the escapes.
5616 ;; but that requires another match, protecting match data,
5617 ;; a lot of overhead for font-lock.
5618 (ip (org-maybe-intangible
5619 (list 'invisible 'org-link
5620 'keymap org-mouse-map 'mouse-face 'highlight
5621 'font-lock-multiline t 'help-echo help)))
5622 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5623 'font-lock-multiline t 'help-echo help)))
5624 ;; We need to remove the invisible property here. Table narrowing
5625 ;; may have made some of this invisible.
5626 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5627 (remove-text-properties (match-beginning 0) (match-end 0)
5628 '(invisible nil))
5629 (if (match-end 3)
5630 (progn
5631 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5632 (org-rear-nonsticky-at (match-beginning 3))
5633 (add-text-properties (match-beginning 3) (match-end 3) vp)
5634 (org-rear-nonsticky-at (match-end 3))
5635 (add-text-properties (match-end 3) (match-end 0) ip)
5636 (org-rear-nonsticky-at (match-end 0)))
5637 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5638 (org-rear-nonsticky-at (match-beginning 1))
5639 (add-text-properties (match-beginning 1) (match-end 1) vp)
5640 (org-rear-nonsticky-at (match-end 1))
5641 (add-text-properties (match-end 1) (match-end 0) ip)
5642 (org-rear-nonsticky-at (match-end 0)))
5643 t)))
5645 (defun org-activate-dates (limit)
5646 "Run through the buffer and add overlays to dates."
5647 (if (re-search-forward org-tsr-regexp-both limit t)
5648 (progn
5649 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5650 (add-text-properties (match-beginning 0) (match-end 0)
5651 (list 'mouse-face 'highlight
5652 'keymap org-mouse-map))
5653 (org-rear-nonsticky-at (match-end 0))
5654 (when org-display-custom-times
5655 (if (match-end 3)
5656 (org-display-custom-time (match-beginning 3) (match-end 3)))
5657 (org-display-custom-time (match-beginning 1) (match-end 1)))
5658 t)))
5660 (defvar org-target-link-regexp nil
5661 "Regular expression matching radio targets in plain text.")
5662 (make-variable-buffer-local 'org-target-link-regexp)
5663 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5664 "Regular expression matching a link target.")
5665 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5666 "Regular expression matching a radio target.")
5667 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5668 "Regular expression matching any target.")
5670 (defun org-activate-target-links (limit)
5671 "Run through the buffer and add overlays to target matches."
5672 (when org-target-link-regexp
5673 (let ((case-fold-search t))
5674 (if (re-search-forward org-target-link-regexp limit t)
5675 (progn
5676 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5677 (add-text-properties (match-beginning 0) (match-end 0)
5678 (list 'mouse-face 'highlight
5679 'keymap org-mouse-map
5680 'help-echo "Radio target link"
5681 'org-linked-text t))
5682 (org-rear-nonsticky-at (match-end 0))
5683 t)))))
5685 (defun org-update-radio-target-regexp ()
5686 "Find all radio targets in this file and update the regular expression."
5687 (interactive)
5688 (when (memq 'radio org-activate-links)
5689 (setq org-target-link-regexp
5690 (org-make-target-link-regexp (org-all-targets 'radio)))
5691 (org-restart-font-lock)))
5693 (defun org-hide-wide-columns (limit)
5694 (let (s e)
5695 (setq s (text-property-any (point) (or limit (point-max))
5696 'org-cwidth t))
5697 (when s
5698 (setq e (next-single-property-change s 'org-cwidth))
5699 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5700 (goto-char e)
5701 t)))
5703 (defvar org-latex-and-specials-regexp nil
5704 "Regular expression for highlighting export special stuff.")
5705 (defvar org-match-substring-regexp)
5706 (defvar org-match-substring-with-braces-regexp)
5708 ;; This should be with the exporter code, but we also use if for font-locking
5709 (defconst org-export-html-special-string-regexps
5710 '(("\\\\-" . "&shy;")
5711 ("---\\([^-]\\)" . "&mdash;\\1")
5712 ("--\\([^-]\\)" . "&ndash;\\1")
5713 ("\\.\\.\\." . "&hellip;"))
5714 "Regular expressions for special string conversion.")
5717 (defun org-compute-latex-and-specials-regexp ()
5718 "Compute regular expression for stuff treated specially by exporters."
5719 (if (not org-highlight-latex-fragments-and-specials)
5720 (org-set-local 'org-latex-and-specials-regexp nil)
5721 (require 'org-exp)
5722 (let*
5723 ((matchers (plist-get org-format-latex-options :matchers))
5724 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5725 org-latex-regexps)))
5726 (org-export-allow-BIND nil)
5727 (options (org-combine-plists (org-default-export-plist)
5728 (org-infile-export-plist)))
5729 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5730 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5731 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5732 (org-export-html-expand (plist-get options :expand-quoted-html))
5733 (org-export-with-special-strings (plist-get options :special-strings))
5734 (re-sub
5735 (cond
5736 ((equal org-export-with-sub-superscripts '{})
5737 (list org-match-substring-with-braces-regexp))
5738 (org-export-with-sub-superscripts
5739 (list org-match-substring-regexp))))
5740 (re-latex
5741 (if org-export-with-LaTeX-fragments
5742 (mapcar (lambda (x) (nth 1 x)) latexs)))
5743 (re-macros
5744 (if org-export-with-TeX-macros
5745 (list (concat "\\\\"
5746 (regexp-opt
5747 (append
5749 (delq nil
5750 (mapcar 'car-safe
5751 (append org-entities-user
5752 org-entities)))
5753 (if (boundp 'org-latex-entities)
5754 (mapcar (lambda (x)
5755 (or (car-safe x) x))
5756 org-latex-entities)
5757 nil))
5758 'words))) ; FIXME
5760 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5761 (re-special (if org-export-with-special-strings
5762 (mapcar (lambda (x) (car x))
5763 org-export-html-special-string-regexps)))
5764 (re-rest
5765 (delq nil
5766 (list
5767 (if org-export-html-expand "@<[^>\n]+>")
5768 ))))
5769 (org-set-local
5770 'org-latex-and-specials-regexp
5771 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5772 re-rest) "\\|")))))
5774 (defun org-do-latex-and-special-faces (limit)
5775 "Run through the buffer and add overlays to links."
5776 (when org-latex-and-specials-regexp
5777 (let (rtn d)
5778 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5779 limit t))
5780 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5781 'face))
5782 '(org-code org-verbatim underline)))
5783 (progn
5784 (setq rtn t
5785 d (cond ((member (char-after (1+ (match-beginning 0)))
5786 '(?_ ?^)) 1)
5787 (t 0)))
5788 (font-lock-prepend-text-property
5789 (+ d (match-beginning 0)) (match-end 0)
5790 'face 'org-latex-and-export-specials)
5791 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5792 '(font-lock-multiline t)))))
5793 rtn)))
5795 (defun org-restart-font-lock ()
5796 "Restart `font-lock-mode', to force refontification."
5797 (when (and (boundp 'font-lock-mode) font-lock-mode)
5798 (font-lock-mode -1)
5799 (font-lock-mode 1)))
5801 (defun org-all-targets (&optional radio)
5802 "Return a list of all targets in this file.
5803 With optional argument RADIO, only find radio targets."
5804 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5805 rtn)
5806 (save-excursion
5807 (goto-char (point-min))
5808 (while (re-search-forward re nil t)
5809 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5810 rtn)))
5812 (defun org-make-target-link-regexp (targets)
5813 "Make regular expression matching all strings in TARGETS.
5814 The regular expression finds the targets also if there is a line break
5815 between words."
5816 (and targets
5817 (concat
5818 "\\<\\("
5819 (mapconcat
5820 (lambda (x)
5821 (setq x (regexp-quote x))
5822 (while (string-match " +" x)
5823 (setq x (replace-match "\\s-+" t t x)))
5825 targets
5826 "\\|")
5827 "\\)\\>")))
5829 (defun org-activate-tags (limit)
5830 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5831 (progn
5832 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5833 (add-text-properties (match-beginning 1) (match-end 1)
5834 (list 'mouse-face 'highlight
5835 'keymap org-mouse-map))
5836 (org-rear-nonsticky-at (match-end 1))
5837 t)))
5839 (defun org-outline-level ()
5840 "Compute the outline level of the heading at point.
5841 This function assumes that the cursor is at the beginning of a line matched
5842 by `outline-regexp'. Otherwise it returns garbage.
5843 If this is called at a normal headline, the level is the number of stars.
5844 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5845 (save-excursion
5846 (looking-at org-outline-regexp)
5847 (1- (- (match-end 0) (match-beginning 0)))))
5849 (defvar org-font-lock-keywords nil)
5851 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5852 "Regular expression matching a property line.")
5854 (defvar org-font-lock-hook nil
5855 "Functions to be called for special font lock stuff.")
5857 (defvar org-font-lock-set-keywords-hook nil
5858 "Functions that can manipulate `org-font-lock-extra-keywords'.
5859 This is called after `org-font-lock-extra-keywords' is defined, but before
5860 it is installed to be used by font lock. This can be useful if something
5861 needs to be inserted at a specific position in the font-lock sequence.")
5863 (defun org-font-lock-hook (limit)
5864 "Run `org-font-lock-hook' within LIMIT."
5865 (run-hook-with-args 'org-font-lock-hook limit))
5867 (defun org-set-font-lock-defaults ()
5868 "Set font lock defaults for the current buffer."
5869 (let* ((em org-fontify-emphasized-text)
5870 (lk org-activate-links)
5871 (org-font-lock-extra-keywords
5872 (list
5873 ;; Call the hook
5874 '(org-font-lock-hook)
5875 ;; Headlines
5876 `(,(if org-fontify-whole-heading-line
5877 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5878 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5879 (1 (org-get-level-face 1))
5880 (2 (org-get-level-face 2))
5881 (3 (org-get-level-face 3)))
5882 ;; Table lines
5883 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5884 (1 'org-table t))
5885 ;; Table internals
5886 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5887 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5888 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5889 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5890 ;; Drawers
5891 (list org-drawer-regexp '(0 'org-special-keyword t))
5892 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5893 ;; Properties
5894 (list org-property-re
5895 '(1 'org-special-keyword t)
5896 '(3 'org-property-value t))
5897 ;; Links
5898 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5899 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5900 (if (memq 'plain lk) '(org-activate-plain-links))
5901 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5902 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5903 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5904 (if (memq 'footnote lk) '(org-activate-footnote-links))
5905 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5906 '(org-hide-wide-columns (0 nil append))
5907 ;; TODO keyword
5908 (list (format org-heading-keyword-regexp-format
5909 org-todo-regexp)
5910 '(2 (org-get-todo-face 2) t))
5911 ;; DONE
5912 (if org-fontify-done-headline
5913 (list (format org-heading-keyword-regexp-format
5914 (concat
5915 "\\(?:"
5916 (mapconcat 'regexp-quote org-done-keywords "\\|")
5917 "\\)"))
5918 '(2 'org-headline-done t))
5919 nil)
5920 ;; Priorities
5921 '(org-font-lock-add-priority-faces)
5922 ;; Tags
5923 '(org-font-lock-add-tag-faces)
5924 ;; Special keywords
5925 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5926 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5927 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5928 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5929 ;; Emphasis
5930 (if em
5931 (if (featurep 'xemacs)
5932 '(org-do-emphasis-faces (0 nil append))
5933 '(org-do-emphasis-faces)))
5934 ;; Checkboxes
5935 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5936 1 'org-checkbox prepend)
5937 (if (cdr (assq 'checkbox org-list-automatic-rules))
5938 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5939 (0 (org-get-checkbox-statistics-face) t)))
5940 ;; Description list items
5941 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5942 1 'org-list-dt prepend)
5943 ;; ARCHIVEd headings
5944 (list (concat
5945 org-outline-regexp-bol
5946 "\\(.*:" org-archive-tag ":.*\\)")
5947 '(1 'org-archived prepend))
5948 ;; Specials
5949 '(org-do-latex-and-special-faces)
5950 '(org-fontify-entities)
5951 '(org-raise-scripts)
5952 ;; Code
5953 '(org-activate-code (1 'org-code t))
5954 ;; COMMENT
5955 (list (format org-heading-keyword-regexp-format
5956 (concat "\\("
5957 org-comment-string "\\|" org-quote-string
5958 "\\)"))
5959 '(2 'org-special-keyword t))
5960 ;; Blocks and meta lines
5961 '(org-fontify-meta-lines-and-blocks)
5963 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5964 (run-hooks 'org-font-lock-set-keywords-hook)
5965 ;; Now set the full font-lock-keywords
5966 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5967 (org-set-local 'font-lock-defaults
5968 '(org-font-lock-keywords t nil nil backward-paragraph))
5969 (kill-local-variable 'font-lock-keywords) nil))
5971 (defun org-toggle-pretty-entities ()
5972 "Toggle the composition display of entities as UTF8 characters."
5973 (interactive)
5974 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5975 (org-restart-font-lock)
5976 (if org-pretty-entities
5977 (message "Entities are displayed as UTF8 characters")
5978 (save-restriction
5979 (widen)
5980 (org-decompose-region (point-min) (point-max))
5981 (message "Entities are displayed plain"))))
5983 (defvar org-custom-properties-overlays nil
5984 "List of overlays used for custom properties.")
5985 (make-variable-buffer-local 'org-custom-properties-overlays)
5987 (defun org-toggle-custom-properties-visibility ()
5988 "Display or hide properties in `org-custom-properties'."
5989 (interactive)
5990 (if org-custom-properties-overlays
5991 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5992 (setq org-custom-properties-overlays nil))
5993 (unless (not org-custom-properties)
5994 (save-excursion
5995 (save-restriction
5996 (widen)
5997 (goto-char (point-min))
5998 (while (re-search-forward org-property-re nil t)
5999 (mapc (lambda(p)
6000 (when (equal p (substring (match-string 1) 1 -1))
6001 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6002 (overlay-put o 'invisible t)
6003 (overlay-put o 'org-custom-property t)
6004 (push o org-custom-properties-overlays))))
6005 org-custom-properties)))))))
6007 (defun org-fontify-entities (limit)
6008 "Find an entity to fontify."
6009 (let (ee)
6010 (when org-pretty-entities
6011 (catch 'match
6012 (while (re-search-forward
6013 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6014 limit t)
6015 (if (and (not (org-in-indented-comment-line))
6016 (setq ee (org-entity-get (match-string 1)))
6017 (= (length (nth 6 ee)) 1))
6018 (let*
6019 ((end (if (equal (match-string 2) "{}")
6020 (match-end 2)
6021 (match-end 1))))
6022 (add-text-properties
6023 (match-beginning 0) end
6024 (list 'font-lock-fontified t))
6025 (compose-region (match-beginning 0) end
6026 (nth 6 ee) nil)
6027 (backward-char 1)
6028 (throw 'match t))))
6029 nil))))
6031 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6032 "Fontify string S like in Org-mode."
6033 (with-temp-buffer
6034 (insert s)
6035 (let ((org-odd-levels-only odd-levels))
6036 (org-mode)
6037 (font-lock-fontify-buffer)
6038 (buffer-string))))
6040 (defvar org-m nil)
6041 (defvar org-l nil)
6042 (defvar org-f nil)
6043 (defun org-get-level-face (n)
6044 "Get the right face for match N in font-lock matching of headlines."
6045 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6046 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6047 (if org-cycle-level-faces
6048 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6049 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6050 (cond
6051 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6052 ((eq n 2) org-f)
6053 (t (if org-level-color-stars-only nil org-f))))
6056 (defun org-get-todo-face (kwd)
6057 "Get the right face for a TODO keyword KWD.
6058 If KWD is a number, get the corresponding match group."
6059 (if (numberp kwd) (setq kwd (match-string kwd)))
6060 (or (org-face-from-face-or-color
6061 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6062 (and (member kwd org-done-keywords) 'org-done)
6063 'org-todo))
6065 (defun org-face-from-face-or-color (context inherit face-or-color)
6066 "Create a face list that inherits INHERIT, but sets the foreground color.
6067 When FACE-OR-COLOR is not a string, just return it."
6068 (if (stringp face-or-color)
6069 (list :inherit inherit
6070 (cdr (assoc context org-faces-easy-properties))
6071 face-or-color)
6072 face-or-color))
6074 (defun org-font-lock-add-tag-faces (limit)
6075 "Add the special tag faces."
6076 (when (and org-tag-faces org-tags-special-faces-re)
6077 (while (re-search-forward org-tags-special-faces-re limit t)
6078 (add-text-properties (match-beginning 1) (match-end 1)
6079 (list 'face (org-get-tag-face 1)
6080 'font-lock-fontified t))
6081 (backward-char 1))))
6083 (defun org-font-lock-add-priority-faces (limit)
6084 "Add the special priority faces."
6085 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6086 (when (save-match-data (org-at-heading-p))
6087 (add-text-properties
6088 (match-beginning 0) (match-end 0)
6089 (list 'face (or (org-face-from-face-or-color
6090 'priority 'org-special-keyword
6091 (cdr (assoc (char-after (match-beginning 1))
6092 org-priority-faces)))
6093 'org-special-keyword)
6094 'font-lock-fontified t)))))
6096 (defun org-get-tag-face (kwd)
6097 "Get the right face for a TODO keyword KWD.
6098 If KWD is a number, get the corresponding match group."
6099 (if (numberp kwd) (setq kwd (match-string kwd)))
6100 (or (org-face-from-face-or-color
6101 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6102 'org-tag))
6104 (defun org-unfontify-region (beg end &optional maybe_loudly)
6105 "Remove fontification and activation overlays from links."
6106 (font-lock-default-unfontify-region beg end)
6107 (let* ((buffer-undo-list t)
6108 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6109 (inhibit-modification-hooks t)
6110 deactivate-mark buffer-file-name buffer-file-truename)
6111 (org-decompose-region beg end)
6112 (remove-text-properties beg end
6113 '(mouse-face t keymap t org-linked-text t
6114 invisible t intangible t
6115 org-no-flyspell t org-emphasis t))
6116 (org-remove-font-lock-display-properties beg end)))
6118 (defconst org-script-display '(((raise -0.3) (height 0.7))
6119 ((raise 0.3) (height 0.7))
6120 ((raise -0.5))
6121 ((raise 0.5)))
6122 "Display properties for showing superscripts and subscripts.")
6124 (defun org-remove-font-lock-display-properties (beg end)
6125 "Remove specific display properties that have been added by font lock.
6126 The will remove the raise properties that are used to show superscripts
6127 and subscripts."
6128 (let (next prop)
6129 (while (< beg end)
6130 (setq next (next-single-property-change beg 'display nil end)
6131 prop (get-text-property beg 'display))
6132 (if (member prop org-script-display)
6133 (put-text-property beg next 'display nil))
6134 (setq beg next))))
6136 (defun org-raise-scripts (limit)
6137 "Add raise properties to sub/superscripts."
6138 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6139 (if (re-search-forward
6140 (if (eq org-use-sub-superscripts t)
6141 org-match-substring-regexp
6142 org-match-substring-with-braces-regexp)
6143 limit t)
6144 (let* ((pos (point)) table-p comment-p
6145 (mpos (match-beginning 3))
6146 (emph-p (get-text-property mpos 'org-emphasis))
6147 (link-p (get-text-property mpos 'mouse-face))
6148 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6149 (goto-char (point-at-bol))
6150 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6151 comment-p (org-looking-at-p "[ \t]*#"))
6152 (goto-char pos)
6153 ;; FIXME: Should we go back one character here, for a_b^c
6154 ;; (goto-char (1- pos)) ;????????????????????
6155 (if (or comment-p emph-p link-p keyw-p)
6157 (put-text-property (match-beginning 3) (match-end 0)
6158 'display
6159 (if (equal (char-after (match-beginning 2)) ?^)
6160 (nth (if table-p 3 1) org-script-display)
6161 (nth (if table-p 2 0) org-script-display)))
6162 (add-text-properties (match-beginning 2) (match-end 2)
6163 (list 'invisible t
6164 'org-dwidth t 'org-dwidth-n 1))
6165 (if (and (eq (char-after (match-beginning 3)) ?{)
6166 (eq (char-before (match-end 3)) ?}))
6167 (progn
6168 (add-text-properties
6169 (match-beginning 3) (1+ (match-beginning 3))
6170 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6171 (add-text-properties
6172 (1- (match-end 3)) (match-end 3)
6173 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6174 t)))))
6176 ;;;; Visibility cycling, including org-goto and indirect buffer
6178 ;;; Cycling
6180 (defvar org-cycle-global-status nil)
6181 (make-variable-buffer-local 'org-cycle-global-status)
6182 (defvar org-cycle-subtree-status nil)
6183 (make-variable-buffer-local 'org-cycle-subtree-status)
6185 ;;;###autoload
6187 (defvar org-inlinetask-min-level)
6189 (defun org-cycle (&optional arg)
6190 "TAB-action and visibility cycling for Org-mode.
6192 This is the command invoked in Org-mode by the TAB key. Its main purpose
6193 is outline visibility cycling, but it also invokes other actions
6194 in special contexts.
6196 - When this function is called with a prefix argument, rotate the entire
6197 buffer through 3 states (global cycling)
6198 1. OVERVIEW: Show only top-level headlines.
6199 2. CONTENTS: Show all headlines of all levels, but no body text.
6200 3. SHOW ALL: Show everything.
6201 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6202 determined by the variable `org-startup-folded', and by any VISIBILITY
6203 properties in the buffer.
6204 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6205 including any drawers.
6207 - When inside a table, re-align the table and move to the next field.
6209 - When point is at the beginning of a headline, rotate the subtree started
6210 by this line through 3 different states (local cycling)
6211 1. FOLDED: Only the main headline is shown.
6212 2. CHILDREN: The main headline and the direct children are shown.
6213 From this state, you can move to one of the children
6214 and zoom in further.
6215 3. SUBTREE: Show the entire subtree, including body text.
6216 If there is no subtree, switch directly from CHILDREN to FOLDED.
6218 - When point is at the beginning of an empty headline and the variable
6219 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6220 of the headline by demoting and promoting it to likely levels. This
6221 speeds up creation document structure by pressing TAB once or several
6222 times right after creating a new headline.
6224 - When there is a numeric prefix, go up to a heading with level ARG, do
6225 a `show-subtree' and return to the previous cursor position. If ARG
6226 is negative, go up that many levels.
6228 - When point is not at the beginning of a headline, execute the global
6229 binding for TAB, which is re-indenting the line. See the option
6230 `org-cycle-emulate-tab' for details.
6232 - Special case: if point is at the beginning of the buffer and there is
6233 no headline in line 1, this function will act as if called with prefix arg
6234 (C-u TAB, same as S-TAB) also when called without prefix arg.
6235 But only if also the variable `org-cycle-global-at-bob' is t."
6236 (interactive "P")
6237 (org-load-modules-maybe)
6238 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6239 (and org-cycle-level-after-item/entry-creation
6240 (or (org-cycle-level)
6241 (org-cycle-item-indentation))))
6242 (let* ((limit-level
6243 (or org-cycle-max-level
6244 (and (boundp 'org-inlinetask-min-level)
6245 org-inlinetask-min-level
6246 (1- org-inlinetask-min-level))))
6247 (nstars (and limit-level
6248 (if org-odd-levels-only
6249 (and limit-level (1- (* limit-level 2)))
6250 limit-level)))
6251 (org-outline-regexp
6252 (if (not (derived-mode-p 'org-mode))
6253 outline-regexp
6254 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6255 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6256 (not (looking-at org-outline-regexp))))
6257 (org-cycle-hook
6258 (if bob-special
6259 (delq 'org-optimize-window-after-visibility-change
6260 (copy-sequence org-cycle-hook))
6261 org-cycle-hook))
6262 (pos (point)))
6264 (if (or bob-special (equal arg '(4)))
6265 ;; special case: use global cycling
6266 (setq arg t))
6268 (cond
6270 ((equal arg '(16))
6271 (setq last-command 'dummy)
6272 (org-set-startup-visibility)
6273 (message "Startup visibility, plus VISIBILITY properties"))
6275 ((equal arg '(64))
6276 (show-all)
6277 (message "Entire buffer visible, including drawers"))
6279 ;; Table: enter it or move to the next field.
6280 ((org-at-table-p 'any)
6281 (if (org-at-table.el-p)
6282 (message "Use C-c ' to edit table.el tables")
6283 (if arg (org-table-edit-field t)
6284 (org-table-justify-field-maybe)
6285 (call-interactively 'org-table-next-field))))
6287 ((run-hook-with-args-until-success
6288 'org-tab-after-check-for-table-hook))
6290 ;; Global cycling: delegate to `org-cycle-internal-global'.
6291 ((eq arg t) (org-cycle-internal-global))
6293 ;; Drawers: delegate to `org-flag-drawer'.
6294 ((and org-drawers org-drawer-regexp
6295 (save-excursion
6296 (beginning-of-line 1)
6297 (looking-at org-drawer-regexp)))
6298 (org-flag-drawer ; toggle block visibility
6299 (not (get-char-property (match-end 0) 'invisible))))
6301 ;; Show-subtree, ARG levels up from here.
6302 ((integerp arg)
6303 (save-excursion
6304 (org-back-to-heading)
6305 (outline-up-heading (if (< arg 0) (- arg)
6306 (- (funcall outline-level) arg)))
6307 (org-show-subtree)))
6309 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6310 ((and (featurep 'org-inlinetask)
6311 (org-inlinetask-at-task-p)
6312 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6313 (org-inlinetask-toggle-visibility))
6315 ((org-try-cdlatex-tab))
6317 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6318 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6319 (save-excursion (beginning-of-line 1)
6320 (looking-at org-outline-regexp)))
6321 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6322 (org-cycle-internal-local))
6324 ;; From there: TAB emulation and template completion.
6325 (buffer-read-only (org-back-to-heading))
6327 ((run-hook-with-args-until-success
6328 'org-tab-after-check-for-cycling-hook))
6330 ((org-try-structure-completion))
6332 ((run-hook-with-args-until-success
6333 'org-tab-before-tab-emulation-hook))
6335 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6336 (or (not (bolp))
6337 (not (looking-at org-outline-regexp))))
6338 (call-interactively (global-key-binding "\t")))
6340 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6341 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6342 (or (and (eq org-cycle-emulate-tab 'white)
6343 (= (match-end 0) (point-at-eol)))
6344 (and (eq org-cycle-emulate-tab 'whitestart)
6345 (>= (match-end 0) pos))))
6347 (eq org-cycle-emulate-tab t))
6348 (call-interactively (global-key-binding "\t")))
6350 (t (save-excursion
6351 (org-back-to-heading)
6352 (org-cycle)))))))
6354 (defun org-cycle-internal-global ()
6355 "Do the global cycling action."
6356 ;; Hack to avoid display of messages for .org attachments in Gnus
6357 (let ((ga (string-match "\\*fontification" (buffer-name))))
6358 (cond
6359 ((and (eq last-command this-command)
6360 (eq org-cycle-global-status 'overview))
6361 ;; We just created the overview - now do table of contents
6362 ;; This can be slow in very large buffers, so indicate action
6363 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6364 (unless ga (message "CONTENTS..."))
6365 (org-content)
6366 (unless ga (message "CONTENTS...done"))
6367 (setq org-cycle-global-status 'contents)
6368 (run-hook-with-args 'org-cycle-hook 'contents))
6370 ((and (eq last-command this-command)
6371 (eq org-cycle-global-status 'contents))
6372 ;; We just showed the table of contents - now show everything
6373 (run-hook-with-args 'org-pre-cycle-hook 'all)
6374 (show-all)
6375 (unless ga (message "SHOW ALL"))
6376 (setq org-cycle-global-status 'all)
6377 (run-hook-with-args 'org-cycle-hook 'all))
6380 ;; Default action: go to overview
6381 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6382 (org-overview)
6383 (unless ga (message "OVERVIEW"))
6384 (setq org-cycle-global-status 'overview)
6385 (run-hook-with-args 'org-cycle-hook 'overview)))))
6387 (defun org-cycle-internal-local ()
6388 "Do the local cycling action."
6389 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6390 ;; First, determine end of headline (EOH), end of subtree or item
6391 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6392 (save-excursion
6393 (if (org-at-item-p)
6394 (progn
6395 (beginning-of-line)
6396 (setq struct (org-list-struct))
6397 (setq eoh (point-at-eol))
6398 (setq eos (org-list-get-item-end-before-blank (point) struct))
6399 (setq has-children (org-list-has-child-p (point) struct)))
6400 (org-back-to-heading)
6401 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6402 (setq eos (save-excursion
6403 (org-end-of-subtree t)
6404 (unless (eobp)
6405 (skip-chars-forward " \t\n"))
6406 (if (eobp) (point) (1- (point)))))
6407 (setq has-children
6408 (or (save-excursion
6409 (let ((level (funcall outline-level)))
6410 (outline-next-heading)
6411 (and (org-at-heading-p t)
6412 (> (funcall outline-level) level))))
6413 (save-excursion
6414 (org-list-search-forward (org-item-beginning-re) eos t)))))
6415 ;; Determine end invisible part of buffer (EOL)
6416 (beginning-of-line 2)
6417 ;; XEmacs doesn't have `next-single-char-property-change'
6418 (if (featurep 'xemacs)
6419 (while (and (not (eobp)) ;; this is like `next-line'
6420 (get-char-property (1- (point)) 'invisible))
6421 (beginning-of-line 2))
6422 (while (and (not (eobp)) ;; this is like `next-line'
6423 (get-char-property (1- (point)) 'invisible))
6424 (goto-char (next-single-char-property-change (point) 'invisible))
6425 (and (eolp) (beginning-of-line 2))))
6426 (setq eol (point)))
6427 ;; Find out what to do next and set `this-command'
6428 (cond
6429 ((= eos eoh)
6430 ;; Nothing is hidden behind this heading
6431 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6432 (message "EMPTY ENTRY")
6433 (setq org-cycle-subtree-status nil)
6434 (save-excursion
6435 (goto-char eos)
6436 (outline-next-heading)
6437 (if (outline-invisible-p) (org-flag-heading nil))))
6438 ((and (or (>= eol eos)
6439 (not (string-match "\\S-" (buffer-substring eol eos))))
6440 (or has-children
6441 (not (setq children-skipped
6442 org-cycle-skip-children-state-if-no-children))))
6443 ;; Entire subtree is hidden in one line: children view
6444 (run-hook-with-args 'org-pre-cycle-hook 'children)
6445 (if (org-at-item-p)
6446 (org-list-set-item-visibility (point-at-bol) struct 'children)
6447 (org-show-entry)
6448 (org-with-limited-levels (show-children))
6449 ;; FIXME: This slows down the func way too much.
6450 ;; How keep drawers hidden in subtree anyway?
6451 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6452 ;; (org-cycle-hide-drawers 'subtree))
6454 ;; Fold every list in subtree to top-level items.
6455 (when (eq org-cycle-include-plain-lists 'integrate)
6456 (save-excursion
6457 (org-back-to-heading)
6458 (while (org-list-search-forward (org-item-beginning-re) eos t)
6459 (beginning-of-line 1)
6460 (let* ((struct (org-list-struct))
6461 (prevs (org-list-prevs-alist struct))
6462 (end (org-list-get-bottom-point struct)))
6463 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6464 (org-list-get-all-items (point) struct prevs))
6465 (goto-char end))))))
6466 (message "CHILDREN")
6467 (save-excursion
6468 (goto-char eos)
6469 (outline-next-heading)
6470 (if (outline-invisible-p) (org-flag-heading nil)))
6471 (setq org-cycle-subtree-status 'children)
6472 (run-hook-with-args 'org-cycle-hook 'children))
6473 ((or children-skipped
6474 (and (eq last-command this-command)
6475 (eq org-cycle-subtree-status 'children)))
6476 ;; We just showed the children, or no children are there,
6477 ;; now show everything.
6478 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6479 (outline-flag-region eoh eos nil)
6480 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6481 (setq org-cycle-subtree-status 'subtree)
6482 (run-hook-with-args 'org-cycle-hook 'subtree))
6484 ;; Default action: hide the subtree.
6485 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6486 (outline-flag-region eoh eos t)
6487 (message "FOLDED")
6488 (setq org-cycle-subtree-status 'folded)
6489 (run-hook-with-args 'org-cycle-hook 'folded)))))
6491 ;;;###autoload
6492 (defun org-global-cycle (&optional arg)
6493 "Cycle the global visibility. For details see `org-cycle'.
6494 With \\[universal-argument] prefix arg, switch to startup visibility.
6495 With a numeric prefix, show all headlines up to that level."
6496 (interactive "P")
6497 (let ((org-cycle-include-plain-lists
6498 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6499 (cond
6500 ((integerp arg)
6501 (show-all)
6502 (hide-sublevels arg)
6503 (setq org-cycle-global-status 'contents))
6504 ((equal arg '(4))
6505 (org-set-startup-visibility)
6506 (message "Startup visibility, plus VISIBILITY properties."))
6508 (org-cycle '(4))))))
6510 (defun org-set-startup-visibility ()
6511 "Set the visibility required by startup options and properties."
6512 (cond
6513 ((eq org-startup-folded t)
6514 (org-cycle '(4)))
6515 ((eq org-startup-folded 'content)
6516 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6517 (org-cycle '(4)) (org-cycle '(4)))))
6518 (unless (eq org-startup-folded 'showeverything)
6519 (if org-hide-block-startup (org-hide-block-all))
6520 (org-set-visibility-according-to-property 'no-cleanup)
6521 (org-cycle-hide-archived-subtrees 'all)
6522 (org-cycle-hide-drawers 'all)
6523 (org-cycle-show-empty-lines t)))
6525 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6526 "Switch subtree visibilities according to :VISIBILITY: property."
6527 (interactive)
6528 (let (org-show-entry-below state)
6529 (save-excursion
6530 (goto-char (point-min))
6531 (while (re-search-forward
6532 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6533 nil t)
6534 (setq state (match-string 1))
6535 (save-excursion
6536 (org-back-to-heading t)
6537 (hide-subtree)
6538 (org-reveal)
6539 (cond
6540 ((equal state '("fold" "folded"))
6541 (hide-subtree))
6542 ((equal state "children")
6543 (org-show-hidden-entry)
6544 (show-children))
6545 ((equal state "content")
6546 (save-excursion
6547 (save-restriction
6548 (org-narrow-to-subtree)
6549 (org-content))))
6550 ((member state '("all" "showall"))
6551 (show-subtree)))))
6552 (unless no-cleanup
6553 (org-cycle-hide-archived-subtrees 'all)
6554 (org-cycle-hide-drawers 'all)
6555 (org-cycle-show-empty-lines 'all)))))
6557 ;; This function uses outline-regexp instead of the more fundamental
6558 ;; org-outline-regexp so that org-cycle-global works outside of Org
6559 ;; buffers, where outline-regexp is needed.
6560 (defun org-overview ()
6561 "Switch to overview mode, showing only top-level headlines.
6562 Really, this shows all headlines with level equal or greater than the level
6563 of the first headline in the buffer. This is important, because if the
6564 first headline is not level one, then (hide-sublevels 1) gives confusing
6565 results."
6566 (interactive)
6567 (let ((level (save-excursion
6568 (goto-char (point-min))
6569 (if (re-search-forward (concat "^" outline-regexp) nil t)
6570 (progn
6571 (goto-char (match-beginning 0))
6572 (funcall outline-level))))))
6573 (and level (hide-sublevels level))))
6575 (defun org-content (&optional arg)
6576 "Show all headlines in the buffer, like a table of contents.
6577 With numerical argument N, show content up to level N."
6578 (interactive "P")
6579 (save-excursion
6580 ;; Visit all headings and show their offspring
6581 (and (integerp arg) (org-overview))
6582 (goto-char (point-max))
6583 (catch 'exit
6584 (while (and (progn (condition-case nil
6585 (outline-previous-visible-heading 1)
6586 (error (goto-char (point-min))))
6588 (looking-at org-outline-regexp))
6589 (if (integerp arg)
6590 (show-children (1- arg))
6591 (show-branches))
6592 (if (bobp) (throw 'exit nil))))))
6595 (defun org-optimize-window-after-visibility-change (state)
6596 "Adjust the window after a change in outline visibility.
6597 This function is the default value of the hook `org-cycle-hook'."
6598 (when (get-buffer-window (current-buffer))
6599 (cond
6600 ((eq state 'content) nil)
6601 ((eq state 'all) nil)
6602 ((eq state 'folded) nil)
6603 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6604 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6606 (defun org-remove-empty-overlays-at (pos)
6607 "Remove outline overlays that do not contain non-white stuff."
6608 (mapc
6609 (lambda (o)
6610 (and (eq 'outline (overlay-get o 'invisible))
6611 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6612 (overlay-end o))))
6613 (delete-overlay o)))
6614 (overlays-at pos)))
6616 (defun org-clean-visibility-after-subtree-move ()
6617 "Fix visibility issues after moving a subtree."
6618 ;; First, find a reasonable region to look at:
6619 ;; Start two siblings above, end three below
6620 (let* ((beg (save-excursion
6621 (and (org-get-last-sibling)
6622 (org-get-last-sibling))
6623 (point)))
6624 (end (save-excursion
6625 (and (org-get-next-sibling)
6626 (org-get-next-sibling)
6627 (org-get-next-sibling))
6628 (if (org-at-heading-p)
6629 (point-at-eol)
6630 (point))))
6631 (level (looking-at "\\*+"))
6632 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6633 (save-excursion
6634 (save-restriction
6635 (narrow-to-region beg end)
6636 (when re
6637 ;; Properly fold already folded siblings
6638 (goto-char (point-min))
6639 (while (re-search-forward re nil t)
6640 (if (and (not (outline-invisible-p))
6641 (save-excursion
6642 (goto-char (point-at-eol)) (outline-invisible-p)))
6643 (hide-entry))))
6644 (org-cycle-show-empty-lines 'overview)
6645 (org-cycle-hide-drawers 'overview)))))
6647 (defun org-cycle-show-empty-lines (state)
6648 "Show empty lines above all visible headlines.
6649 The region to be covered depends on STATE when called through
6650 `org-cycle-hook'. Lisp program can use t for STATE to get the
6651 entire buffer covered. Note that an empty line is only shown if there
6652 are at least `org-cycle-separator-lines' empty lines before the headline."
6653 (when (not (= org-cycle-separator-lines 0))
6654 (save-excursion
6655 (let* ((n (abs org-cycle-separator-lines))
6656 (re (cond
6657 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6658 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6659 (t (let ((ns (number-to-string (- n 2))))
6660 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6661 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6662 beg end b e)
6663 (cond
6664 ((memq state '(overview contents t))
6665 (setq beg (point-min) end (point-max)))
6666 ((memq state '(children folded))
6667 (setq beg (point) end (progn (org-end-of-subtree t t)
6668 (beginning-of-line 2)
6669 (point)))))
6670 (when beg
6671 (goto-char beg)
6672 (while (re-search-forward re end t)
6673 (unless (get-char-property (match-end 1) 'invisible)
6674 (setq e (match-end 1))
6675 (if (< org-cycle-separator-lines 0)
6676 (setq b (save-excursion
6677 (goto-char (match-beginning 0))
6678 (org-back-over-empty-lines)
6679 (if (save-excursion
6680 (goto-char (max (point-min) (1- (point))))
6681 (org-at-heading-p))
6682 (1- (point))
6683 (point))))
6684 (setq b (match-beginning 1)))
6685 (outline-flag-region b e nil)))))))
6686 ;; Never hide empty lines at the end of the file.
6687 (save-excursion
6688 (goto-char (point-max))
6689 (outline-previous-heading)
6690 (outline-end-of-heading)
6691 (if (and (looking-at "[ \t\n]+")
6692 (= (match-end 0) (point-max)))
6693 (outline-flag-region (point) (match-end 0) nil))))
6695 (defun org-show-empty-lines-in-parent ()
6696 "Move to the parent and re-show empty lines before visible headlines."
6697 (save-excursion
6698 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6699 (org-cycle-show-empty-lines context))))
6701 (defun org-files-list ()
6702 "Return `org-agenda-files' list, plus all open org-mode files.
6703 This is useful for operations that need to scan all of a user's
6704 open and agenda-wise Org files."
6705 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6706 (dolist (buf (buffer-list))
6707 (with-current-buffer buf
6708 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6709 (let ((file (expand-file-name (buffer-file-name))))
6710 (unless (member file files)
6711 (push file files))))))
6712 files))
6714 (defsubst org-entry-beginning-position ()
6715 "Return the beginning position of the current entry."
6716 (save-excursion (outline-back-to-heading t) (point)))
6718 (defsubst org-entry-end-position ()
6719 "Return the end position of the current entry."
6720 (save-excursion (outline-next-heading) (point)))
6722 (defun org-cycle-hide-drawers (state)
6723 "Re-hide all drawers after a visibility state change."
6724 (when (and (derived-mode-p 'org-mode)
6725 (not (memq state '(overview folded contents))))
6726 (save-excursion
6727 (let* ((globalp (memq state '(contents all)))
6728 (beg (if globalp (point-min) (point)))
6729 (end (if globalp (point-max)
6730 (if (eq state 'children)
6731 (save-excursion (outline-next-heading) (point))
6732 (org-end-of-subtree t)))))
6733 (goto-char beg)
6734 (while (re-search-forward org-drawer-regexp end t)
6735 (org-flag-drawer t))))))
6737 (defun org-flag-drawer (flag)
6738 "When FLAG is non-nil, hide the drawer we are within.
6739 Otherwise make it visible."
6740 (save-excursion
6741 (beginning-of-line 1)
6742 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6743 (let ((b (match-end 0)))
6744 (if (re-search-forward
6745 "^[ \t]*:END:"
6746 (save-excursion (outline-next-heading) (point)) t)
6747 (outline-flag-region b (point-at-eol) flag)
6748 (error ":END: line missing at position %s" b))))))
6750 (defun org-subtree-end-visible-p ()
6751 "Is the end of the current subtree visible?"
6752 (pos-visible-in-window-p
6753 (save-excursion (org-end-of-subtree t) (point))))
6755 (defun org-first-headline-recenter (&optional N)
6756 "Move cursor to the first headline and recenter the headline.
6757 Optional argument N means put the headline into the Nth line of the window."
6758 (goto-char (point-min))
6759 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6760 (beginning-of-line)
6761 (recenter (prefix-numeric-value N))))
6763 ;;; Saving and restoring visibility
6765 (defun org-outline-overlay-data (&optional use-markers)
6766 "Return a list of the locations of all outline overlays.
6767 These are overlays with the `invisible' property value `outline'.
6768 The return value is a list of cons cells, with start and stop
6769 positions for each overlay.
6770 If USE-MARKERS is set, return the positions as markers."
6771 (let (beg end)
6772 (save-excursion
6773 (save-restriction
6774 (widen)
6775 (delq nil
6776 (mapcar (lambda (o)
6777 (when (eq (overlay-get o 'invisible) 'outline)
6778 (setq beg (overlay-start o)
6779 end (overlay-end o))
6780 (and beg end (> end beg)
6781 (if use-markers
6782 (cons (move-marker (make-marker) beg)
6783 (move-marker (make-marker) end))
6784 (cons beg end)))))
6785 (overlays-in (point-min) (point-max))))))))
6787 (defun org-set-outline-overlay-data (data)
6788 "Create visibility overlays for all positions in DATA.
6789 DATA should have been made by `org-outline-overlay-data'."
6790 (let (o)
6791 (save-excursion
6792 (save-restriction
6793 (widen)
6794 (show-all)
6795 (mapc (lambda (c)
6796 (outline-flag-region (car c) (cdr c) t))
6797 data)))))
6799 ;;; Folding of blocks
6801 (defvar org-hide-block-overlays nil
6802 "Overlays hiding blocks.")
6803 (make-variable-buffer-local 'org-hide-block-overlays)
6805 (defun org-block-map (function &optional start end)
6806 "Call FUNCTION at the head of all source blocks in the current buffer.
6807 Optional arguments START and END can be used to limit the range."
6808 (let ((start (or start (point-min)))
6809 (end (or end (point-max))))
6810 (save-excursion
6811 (goto-char start)
6812 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6813 (save-excursion
6814 (save-match-data
6815 (goto-char (match-beginning 0))
6816 (funcall function)))))))
6818 (defun org-hide-block-toggle-all ()
6819 "Toggle the visibility of all blocks in the current buffer."
6820 (org-block-map #'org-hide-block-toggle))
6822 (defun org-hide-block-all ()
6823 "Fold all blocks in the current buffer."
6824 (interactive)
6825 (org-show-block-all)
6826 (org-block-map #'org-hide-block-toggle-maybe))
6828 (defun org-show-block-all ()
6829 "Unfold all blocks in the current buffer."
6830 (interactive)
6831 (mapc 'delete-overlay org-hide-block-overlays)
6832 (setq org-hide-block-overlays nil))
6834 (defun org-hide-block-toggle-maybe ()
6835 "Toggle visibility of block at point."
6836 (interactive)
6837 (let ((case-fold-search t))
6838 (if (save-excursion
6839 (beginning-of-line 1)
6840 (looking-at org-block-regexp))
6841 (progn (org-hide-block-toggle)
6842 t) ;; to signal that we took action
6843 nil))) ;; to signal that we did not
6845 (defun org-hide-block-toggle (&optional force)
6846 "Toggle the visibility of the current block."
6847 (interactive)
6848 (save-excursion
6849 (beginning-of-line)
6850 (if (re-search-forward org-block-regexp nil t)
6851 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6852 (end (match-end 0)) ;; end of entire body
6854 (if (memq t (mapcar (lambda (overlay)
6855 (eq (overlay-get overlay 'invisible)
6856 'org-hide-block))
6857 (overlays-at start)))
6858 (if (or (not force) (eq force 'off))
6859 (mapc (lambda (ov)
6860 (when (member ov org-hide-block-overlays)
6861 (setq org-hide-block-overlays
6862 (delq ov org-hide-block-overlays)))
6863 (when (eq (overlay-get ov 'invisible)
6864 'org-hide-block)
6865 (delete-overlay ov)))
6866 (overlays-at start)))
6867 (setq ov (make-overlay start end))
6868 (overlay-put ov 'invisible 'org-hide-block)
6869 ;; make the block accessible to isearch
6870 (overlay-put
6871 ov 'isearch-open-invisible
6872 (lambda (ov)
6873 (when (member ov org-hide-block-overlays)
6874 (setq org-hide-block-overlays
6875 (delq ov org-hide-block-overlays)))
6876 (when (eq (overlay-get ov 'invisible)
6877 'org-hide-block)
6878 (delete-overlay ov))))
6879 (push ov org-hide-block-overlays)))
6880 (error "Not looking at a source block"))))
6882 ;; org-tab-after-check-for-cycling-hook
6883 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6884 ;; Remove overlays when changing major mode
6885 (add-hook 'org-mode-hook
6886 (lambda () (org-add-hook 'change-major-mode-hook
6887 'org-show-block-all 'append 'local)))
6889 ;;; Org-goto
6891 (defvar org-goto-window-configuration nil)
6892 (defvar org-goto-marker nil)
6893 (defvar org-goto-map
6894 (let ((map (make-sparse-keymap)))
6895 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6896 (while (setq cmd (pop cmds))
6897 (substitute-key-definition cmd cmd map global-map)))
6898 (suppress-keymap map)
6899 (org-defkey map "\C-m" 'org-goto-ret)
6900 (org-defkey map [(return)] 'org-goto-ret)
6901 (org-defkey map [(left)] 'org-goto-left)
6902 (org-defkey map [(right)] 'org-goto-right)
6903 (org-defkey map [(control ?g)] 'org-goto-quit)
6904 (org-defkey map "\C-i" 'org-cycle)
6905 (org-defkey map [(tab)] 'org-cycle)
6906 (org-defkey map [(down)] 'outline-next-visible-heading)
6907 (org-defkey map [(up)] 'outline-previous-visible-heading)
6908 (if org-goto-auto-isearch
6909 (if (fboundp 'define-key-after)
6910 (define-key-after map [t] 'org-goto-local-auto-isearch)
6911 nil)
6912 (org-defkey map "q" 'org-goto-quit)
6913 (org-defkey map "n" 'outline-next-visible-heading)
6914 (org-defkey map "p" 'outline-previous-visible-heading)
6915 (org-defkey map "f" 'outline-forward-same-level)
6916 (org-defkey map "b" 'outline-backward-same-level)
6917 (org-defkey map "u" 'outline-up-heading))
6918 (org-defkey map "/" 'org-occur)
6919 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6920 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6921 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6922 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6923 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6924 map))
6926 (defconst org-goto-help
6927 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6928 RET=jump to location [Q]uit and return to previous location
6929 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6931 (defvar org-goto-start-pos) ; dynamically scoped parameter
6933 ;; FIXME: Docstring does not mention both interfaces
6934 (defun org-goto (&optional alternative-interface)
6935 "Look up a different location in the current file, keeping current visibility.
6937 When you want look-up or go to a different location in a
6938 document, the fastest way is often to fold the entire buffer and
6939 then dive into the tree. This method has the disadvantage, that
6940 the previous location will be folded, which may not be what you
6941 want.
6943 This command works around this by showing a copy of the current
6944 buffer in an indirect buffer, in overview mode. You can dive
6945 into the tree in that copy, use org-occur and incremental search
6946 to find a location. When pressing RET or `Q', the command
6947 returns to the original buffer in which the visibility is still
6948 unchanged. After RET it will also jump to the location selected
6949 in the indirect buffer and expose the headline hierarchy above.
6951 With a prefix argument, use the alternative interface: e.g. if
6952 `org-goto-interface' is 'outline use 'outline-path-completion."
6953 (interactive "P")
6954 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6955 (org-refile-use-outline-path t)
6956 (org-refile-target-verify-function nil)
6957 (interface
6958 (if (not alternative-interface)
6959 org-goto-interface
6960 (if (eq org-goto-interface 'outline)
6961 'outline-path-completion
6962 'outline)))
6963 (org-goto-start-pos (point))
6964 (selected-point
6965 (if (eq interface 'outline)
6966 (car (org-get-location (current-buffer) org-goto-help))
6967 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6968 (org-refile-check-position pa)
6969 (nth 3 pa)))))
6970 (if selected-point
6971 (progn
6972 (org-mark-ring-push org-goto-start-pos)
6973 (goto-char selected-point)
6974 (if (or (outline-invisible-p) (org-invisible-p2))
6975 (org-show-context 'org-goto)))
6976 (message "Quit"))))
6978 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6979 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6980 (defvar org-goto-local-auto-isearch-map) ; defined below
6982 (defun org-get-location (buf help)
6983 "Let the user select a location in the Org-mode buffer BUF.
6984 This function uses a recursive edit. It returns the selected position
6985 or nil."
6986 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6987 (isearch-hide-immediately nil)
6988 (isearch-search-fun-function
6989 (lambda () 'org-goto-local-search-headings))
6990 (org-goto-selected-point org-goto-exit-command)
6991 (pop-up-frames nil)
6992 (special-display-buffer-names nil)
6993 (special-display-regexps nil)
6994 (special-display-function nil))
6995 (save-excursion
6996 (save-window-excursion
6997 (delete-other-windows)
6998 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6999 (org-pop-to-buffer-same-window
7000 (condition-case nil
7001 (make-indirect-buffer (current-buffer) "*org-goto*")
7002 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7003 (with-output-to-temp-buffer "*Help*"
7004 (princ help))
7005 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7006 (setq buffer-read-only nil)
7007 (let ((org-startup-truncated t)
7008 (org-startup-folded nil)
7009 (org-startup-align-all-tables nil))
7010 (org-mode)
7011 (org-overview))
7012 (setq buffer-read-only t)
7013 (if (and (boundp 'org-goto-start-pos)
7014 (integer-or-marker-p org-goto-start-pos))
7015 (let ((org-show-hierarchy-above t)
7016 (org-show-siblings t)
7017 (org-show-following-heading t))
7018 (goto-char org-goto-start-pos)
7019 (and (outline-invisible-p) (org-show-context)))
7020 (goto-char (point-min)))
7021 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7022 (message "Select location and press RET")
7023 (use-local-map org-goto-map)
7024 (recursive-edit)
7026 (kill-buffer "*org-goto*")
7027 (cons org-goto-selected-point org-goto-exit-command)))
7029 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7030 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7031 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7032 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7034 (defun org-goto-local-search-headings (string bound noerror)
7035 "Search and make sure that any matches are in headlines."
7036 (catch 'return
7037 (while (if isearch-forward
7038 (search-forward string bound noerror)
7039 (search-backward string bound noerror))
7040 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7041 (and (member :headline context)
7042 (not (member :tags context))))
7043 (throw 'return (point))))))
7045 (defun org-goto-local-auto-isearch ()
7046 "Start isearch."
7047 (interactive)
7048 (goto-char (point-min))
7049 (let ((keys (this-command-keys)))
7050 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7051 (isearch-mode t)
7052 (isearch-process-search-char (string-to-char keys)))))
7054 (defun org-goto-ret (&optional arg)
7055 "Finish `org-goto' by going to the new location."
7056 (interactive "P")
7057 (setq org-goto-selected-point (point)
7058 org-goto-exit-command 'return)
7059 (throw 'exit nil))
7061 (defun org-goto-left ()
7062 "Finish `org-goto' by going to the new location."
7063 (interactive)
7064 (if (org-at-heading-p)
7065 (progn
7066 (beginning-of-line 1)
7067 (setq org-goto-selected-point (point)
7068 org-goto-exit-command 'left)
7069 (throw 'exit nil))
7070 (error "Not on a heading")))
7072 (defun org-goto-right ()
7073 "Finish `org-goto' by going to the new location."
7074 (interactive)
7075 (if (org-at-heading-p)
7076 (progn
7077 (setq org-goto-selected-point (point)
7078 org-goto-exit-command 'right)
7079 (throw 'exit nil))
7080 (error "Not on a heading")))
7082 (defun org-goto-quit ()
7083 "Finish `org-goto' without cursor motion."
7084 (interactive)
7085 (setq org-goto-selected-point nil)
7086 (setq org-goto-exit-command 'quit)
7087 (throw 'exit nil))
7089 ;;; Indirect buffer display of subtrees
7091 (defvar org-indirect-dedicated-frame nil
7092 "This is the frame being used for indirect tree display.")
7093 (defvar org-last-indirect-buffer nil)
7095 (defun org-tree-to-indirect-buffer (&optional arg)
7096 "Create indirect buffer and narrow it to current subtree.
7097 With a numerical prefix ARG, go up to this level and then take that tree.
7098 If ARG is negative, go up that many levels.
7100 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7101 indirect buffer previously made with this command, to avoid proliferation of
7102 indirect buffers. However, when you call the command with a \
7103 \\[universal-argument] prefix, or
7104 when `org-indirect-buffer-display' is `new-frame', the last buffer
7105 is kept so that you can work with several indirect buffers at the same time.
7106 If `org-indirect-buffer-display' is `dedicated-frame', the \
7107 \\[universal-argument] prefix also
7108 requests that a new frame be made for the new buffer, so that the dedicated
7109 frame is not changed."
7110 (interactive "P")
7111 (let ((cbuf (current-buffer))
7112 (cwin (selected-window))
7113 (pos (point))
7114 beg end level heading ibuf)
7115 (save-excursion
7116 (org-back-to-heading t)
7117 (when (numberp arg)
7118 (setq level (org-outline-level))
7119 (if (< arg 0) (setq arg (+ level arg)))
7120 (while (> (setq level (org-outline-level)) arg)
7121 (org-up-heading-safe)))
7122 (setq beg (point)
7123 heading (org-get-heading))
7124 (org-end-of-subtree t t)
7125 (if (org-at-heading-p) (backward-char 1))
7126 (setq end (point)))
7127 (if (and (buffer-live-p org-last-indirect-buffer)
7128 (not (eq org-indirect-buffer-display 'new-frame))
7129 (not arg))
7130 (kill-buffer org-last-indirect-buffer))
7131 (setq ibuf (org-get-indirect-buffer cbuf)
7132 org-last-indirect-buffer ibuf)
7133 (cond
7134 ((or (eq org-indirect-buffer-display 'new-frame)
7135 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7136 (select-frame (make-frame))
7137 (delete-other-windows)
7138 (org-pop-to-buffer-same-window ibuf)
7139 (org-set-frame-title heading))
7140 ((eq org-indirect-buffer-display 'dedicated-frame)
7141 (raise-frame
7142 (select-frame (or (and org-indirect-dedicated-frame
7143 (frame-live-p org-indirect-dedicated-frame)
7144 org-indirect-dedicated-frame)
7145 (setq org-indirect-dedicated-frame (make-frame)))))
7146 (delete-other-windows)
7147 (org-pop-to-buffer-same-window ibuf)
7148 (org-set-frame-title (concat "Indirect: " heading)))
7149 ((eq org-indirect-buffer-display 'current-window)
7150 (org-pop-to-buffer-same-window ibuf))
7151 ((eq org-indirect-buffer-display 'other-window)
7152 (pop-to-buffer ibuf))
7153 (t (error "Invalid value")))
7154 (if (featurep 'xemacs)
7155 (save-excursion (org-mode) (turn-on-font-lock)))
7156 (narrow-to-region beg end)
7157 (show-all)
7158 (goto-char pos)
7159 (run-hook-with-args 'org-cycle-hook 'all)
7160 (and (window-live-p cwin) (select-window cwin))))
7162 (defun org-get-indirect-buffer (&optional buffer)
7163 (setq buffer (or buffer (current-buffer)))
7164 (let ((n 1) (base (buffer-name buffer)) bname)
7165 (while (buffer-live-p
7166 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7167 (setq n (1+ n)))
7168 (condition-case nil
7169 (make-indirect-buffer buffer bname 'clone)
7170 (error (make-indirect-buffer buffer bname)))))
7172 (defun org-set-frame-title (title)
7173 "Set the title of the current frame to the string TITLE."
7174 ;; FIXME: how to name a single frame in XEmacs???
7175 (unless (featurep 'xemacs)
7176 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7178 ;;;; Structure editing
7180 ;;; Inserting headlines
7182 (defun org-previous-line-empty-p ()
7183 (save-excursion
7184 (and (not (bobp))
7185 (or (beginning-of-line 0) t)
7186 (save-match-data
7187 (looking-at "[ \t]*$")))))
7189 (defun org-insert-heading (&optional force-heading invisible-ok)
7190 "Insert a new heading or item with same depth at point.
7191 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7192 If point is at the beginning of a headline, insert a sibling before the
7193 current headline. If point is not at the beginning, split the line,
7194 create the new headline with the text in the current line after point
7195 \(but see also the variable `org-M-RET-may-split-line').
7197 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7198 This is important for non-interactive uses of the command."
7199 (interactive "P")
7200 (if (or (= (buffer-size) 0)
7201 (and (not (save-excursion
7202 (and (ignore-errors (org-back-to-heading invisible-ok))
7203 (org-at-heading-p))))
7204 (or force-heading (not (org-in-item-p)))))
7205 (progn
7206 (insert "\n* ")
7207 (run-hooks 'org-insert-heading-hook))
7208 (when (or force-heading (not (org-insert-item)))
7209 (let* ((empty-line-p nil)
7210 (level nil)
7211 (on-heading (org-at-heading-p))
7212 (head (save-excursion
7213 (condition-case nil
7214 (progn
7215 (org-back-to-heading invisible-ok)
7216 (when (and (not on-heading)
7217 (featurep 'org-inlinetask)
7218 (integerp org-inlinetask-min-level)
7219 (>= (length (match-string 0))
7220 org-inlinetask-min-level))
7221 ;; Find a heading level before the inline task
7222 (while (and (setq level (org-up-heading-safe))
7223 (>= level org-inlinetask-min-level)))
7224 (if (org-at-heading-p)
7225 (org-back-to-heading invisible-ok)
7226 (error "This should not happen")))
7227 (setq empty-line-p (org-previous-line-empty-p))
7228 (match-string 0))
7229 (error "*"))))
7230 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7231 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7232 pos hide-previous previous-pos)
7233 (cond
7234 ((and (org-at-heading-p) (bolp)
7235 (or (bobp)
7236 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7237 ;; insert before the current line
7238 (open-line (if blank 2 1)))
7239 ((and (bolp)
7240 (not org-insert-heading-respect-content)
7241 (or (bobp)
7242 (save-excursion
7243 (backward-char 1) (not (outline-invisible-p)))))
7244 ;; insert right here
7245 nil)
7247 ;; somewhere in the line
7248 (save-excursion
7249 (setq previous-pos (point-at-bol))
7250 (end-of-line)
7251 (setq hide-previous (outline-invisible-p)))
7252 (and org-insert-heading-respect-content (org-show-subtree))
7253 (let ((split
7254 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7255 (save-excursion
7256 (let ((p (point)))
7257 (goto-char (point-at-bol))
7258 (and (looking-at org-complex-heading-regexp)
7259 (match-beginning 4)
7260 (> p (match-beginning 4)))))))
7261 tags pos)
7262 (cond
7263 (org-insert-heading-respect-content
7264 (org-end-of-subtree nil t)
7265 (when (featurep 'org-inlinetask)
7266 (while (and (not (eobp))
7267 (looking-at "\\(\\*+\\)[ \t]+")
7268 (>= (length (match-string 1))
7269 org-inlinetask-min-level))
7270 (org-end-of-subtree nil t)))
7271 (or (bolp) (newline))
7272 (or (org-previous-line-empty-p)
7273 (and blank (newline)))
7274 (open-line 1))
7275 ((org-at-heading-p)
7276 (when hide-previous
7277 (show-children)
7278 (org-show-entry))
7279 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7280 (setq tags (and (match-end 2) (match-string 2)))
7281 (and (match-end 1)
7282 (delete-region (match-beginning 1) (match-end 1)))
7283 (setq pos (point-at-bol))
7284 (or split (end-of-line 1))
7285 (delete-horizontal-space)
7286 (if (string-match "\\`\\*+\\'"
7287 (buffer-substring (point-at-bol) (point)))
7288 (insert " "))
7289 (newline (if blank 2 1))
7290 (when tags
7291 (save-excursion
7292 (goto-char pos)
7293 (end-of-line 1)
7294 (insert " " tags)
7295 (org-set-tags nil 'align))))
7297 (or split (end-of-line 1))
7298 (newline (if blank 2 1)))))))
7299 (insert head) (just-one-space)
7300 (setq pos (point))
7301 (end-of-line 1)
7302 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7303 (when (and org-insert-heading-respect-content hide-previous)
7304 (save-excursion
7305 (goto-char previous-pos)
7306 (hide-subtree)))
7307 (run-hooks 'org-insert-heading-hook)))))
7309 (defun org-get-heading (&optional no-tags no-todo)
7310 "Return the heading of the current entry, without the stars.
7311 When NO-TAGS is non-nil, don't include tags.
7312 When NO-TODO is non-nil, don't include TODO keywords."
7313 (save-excursion
7314 (org-back-to-heading t)
7315 (cond
7316 ((and no-tags no-todo)
7317 (looking-at org-complex-heading-regexp)
7318 (match-string 4))
7319 (no-tags
7320 (looking-at (concat org-outline-regexp
7321 "\\(.*?\\)"
7322 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7323 (match-string 1))
7324 (no-todo
7325 (looking-at org-todo-line-regexp)
7326 (match-string 3))
7327 (t (looking-at org-heading-regexp)
7328 (match-string 2)))))
7330 (defun org-heading-components ()
7331 "Return the components of the current heading.
7332 This is a list with the following elements:
7333 - the level as an integer
7334 - the reduced level, different if `org-odd-levels-only' is set.
7335 - the TODO keyword, or nil
7336 - the priority character, like ?A, or nil if no priority is given
7337 - the headline text itself, or the tags string if no headline text
7338 - the tags string, or nil."
7339 (save-excursion
7340 (org-back-to-heading t)
7341 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7342 (list (length (match-string 1))
7343 (org-reduced-level (length (match-string 1)))
7344 (org-match-string-no-properties 2)
7345 (and (match-end 3) (aref (match-string 3) 2))
7346 (org-match-string-no-properties 4)
7347 (org-match-string-no-properties 5)))))
7349 (defun org-get-entry ()
7350 "Get the entry text, after heading, entire subtree."
7351 (save-excursion
7352 (org-back-to-heading t)
7353 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7355 (defun org-insert-heading-after-current ()
7356 "Insert a new heading with same level as current, after current subtree."
7357 (interactive)
7358 (org-back-to-heading)
7359 (org-insert-heading)
7360 (org-move-subtree-down)
7361 (end-of-line 1))
7363 (defun org-insert-heading-respect-content ()
7364 (interactive)
7365 (let ((org-insert-heading-respect-content t))
7366 (org-insert-heading t)))
7368 (defun org-insert-todo-heading-respect-content (&optional force-state)
7369 (interactive "P")
7370 (let ((org-insert-heading-respect-content t))
7371 (org-insert-todo-heading force-state t)))
7373 (defun org-insert-todo-heading (arg &optional force-heading)
7374 "Insert a new heading with the same level and TODO state as current heading.
7375 If the heading has no TODO state, or if the state is DONE, use the first
7376 state (TODO by default). Also with prefix arg, force first state."
7377 (interactive "P")
7378 (when (or force-heading (not (org-insert-item 'checkbox)))
7379 (org-insert-heading force-heading)
7380 (save-excursion
7381 (org-back-to-heading)
7382 (outline-previous-heading)
7383 (looking-at org-todo-line-regexp))
7384 (let*
7385 ((new-mark-x
7386 (if (or arg
7387 (not (match-beginning 2))
7388 (member (match-string 2) org-done-keywords))
7389 (car org-todo-keywords-1)
7390 (match-string 2)))
7391 (new-mark
7393 (run-hook-with-args-until-success
7394 'org-todo-get-default-hook new-mark-x nil)
7395 new-mark-x)))
7396 (beginning-of-line 1)
7397 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7398 (if org-treat-insert-todo-heading-as-state-change
7399 (org-todo new-mark)
7400 (insert new-mark " "))))
7401 (when org-provide-todo-statistics
7402 (org-update-parent-todo-statistics))))
7404 (defun org-insert-subheading (arg)
7405 "Insert a new subheading and demote it.
7406 Works for outline headings and for plain lists alike."
7407 (interactive "P")
7408 (org-insert-heading arg)
7409 (cond
7410 ((org-at-heading-p) (org-do-demote))
7411 ((org-at-item-p) (org-indent-item))))
7413 (defun org-insert-todo-subheading (arg)
7414 "Insert a new subheading with TODO keyword or checkbox and demote it.
7415 Works for outline headings and for plain lists alike."
7416 (interactive "P")
7417 (org-insert-todo-heading arg)
7418 (cond
7419 ((org-at-heading-p) (org-do-demote))
7420 ((org-at-item-p) (org-indent-item))))
7422 ;;; Promotion and Demotion
7424 (defvar org-after-demote-entry-hook nil
7425 "Hook run after an entry has been demoted.
7426 The cursor will be at the beginning of the entry.
7427 When a subtree is being demoted, the hook will be called for each node.")
7429 (defvar org-after-promote-entry-hook nil
7430 "Hook run after an entry has been promoted.
7431 The cursor will be at the beginning of the entry.
7432 When a subtree is being promoted, the hook will be called for each node.")
7434 (defun org-promote-subtree ()
7435 "Promote the entire subtree.
7436 See also `org-promote'."
7437 (interactive)
7438 (save-excursion
7439 (org-with-limited-levels (org-map-tree 'org-promote)))
7440 (org-fix-position-after-promote))
7442 (defun org-demote-subtree ()
7443 "Demote the entire subtree. See `org-demote'.
7444 See also `org-promote'."
7445 (interactive)
7446 (save-excursion
7447 (org-with-limited-levels (org-map-tree 'org-demote)))
7448 (org-fix-position-after-promote))
7451 (defun org-do-promote ()
7452 "Promote the current heading higher up the tree.
7453 If the region is active in `transient-mark-mode', promote all headings
7454 in the region."
7455 (interactive)
7456 (save-excursion
7457 (if (org-region-active-p)
7458 (org-map-region 'org-promote (region-beginning) (region-end))
7459 (org-promote)))
7460 (org-fix-position-after-promote))
7462 (defun org-do-demote ()
7463 "Demote the current heading lower down the tree.
7464 If the region is active in `transient-mark-mode', demote all headings
7465 in the region."
7466 (interactive)
7467 (save-excursion
7468 (if (org-region-active-p)
7469 (org-map-region 'org-demote (region-beginning) (region-end))
7470 (org-demote)))
7471 (org-fix-position-after-promote))
7473 (defun org-fix-position-after-promote ()
7474 "Make sure that after pro/demotion cursor position is right."
7475 (let ((pos (point)))
7476 (when (save-excursion
7477 (beginning-of-line 1)
7478 (looking-at org-todo-line-regexp)
7479 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7480 (cond ((eobp) (insert " "))
7481 ((eolp) (insert " "))
7482 ((equal (char-after) ?\ ) (forward-char 1))))))
7484 (defun org-current-level ()
7485 "Return the level of the current entry, or nil if before the first headline.
7486 The level is the number of stars at the beginning of the headline."
7487 (save-excursion
7488 (org-with-limited-levels
7489 (if (ignore-errors (org-back-to-heading t))
7490 (funcall outline-level)))))
7492 (defun org-get-previous-line-level ()
7493 "Return the outline depth of the last headline before the current line.
7494 Returns 0 for the first headline in the buffer, and nil if before the
7495 first headline."
7496 (let ((current-level (org-current-level))
7497 (prev-level (when (> (line-number-at-pos) 1)
7498 (save-excursion
7499 (beginning-of-line 0)
7500 (org-current-level)))))
7501 (cond ((null current-level) nil) ; Before first headline
7502 ((null prev-level) 0) ; At first headline
7503 (prev-level))))
7505 (defun org-reduced-level (l)
7506 "Compute the effective level of a heading.
7507 This takes into account the setting of `org-odd-levels-only'."
7508 (cond
7509 ((zerop l) 0)
7510 (org-odd-levels-only (1+ (floor (/ l 2))))
7511 (t l)))
7513 (defun org-level-increment ()
7514 "Return the number of stars that will be added or removed at a
7515 time to headlines when structure editing, based on the value of
7516 `org-odd-levels-only'."
7517 (if org-odd-levels-only 2 1))
7519 (defun org-get-valid-level (level &optional change)
7520 "Rectify a level change under the influence of `org-odd-levels-only'
7521 LEVEL is a current level, CHANGE is by how much the level should be
7522 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7523 even level numbers will become the next higher odd number."
7524 (if org-odd-levels-only
7525 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7526 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7527 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7528 (max 1 (+ level (or change 0)))))
7530 (if (boundp 'define-obsolete-function-alias)
7531 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7532 (define-obsolete-function-alias 'org-get-legal-level
7533 'org-get-valid-level)
7534 (define-obsolete-function-alias 'org-get-legal-level
7535 'org-get-valid-level "23.1")))
7537 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7538 ;; ̀org-with-limited-levels'
7539 (defun org-promote ()
7540 "Promote the current heading higher up the tree.
7541 If the region is active in `transient-mark-mode', promote all headings
7542 in the region."
7543 (org-back-to-heading t)
7544 (let* ((level (save-match-data (funcall outline-level)))
7545 (after-change-functions (remove 'flyspell-after-change-function
7546 after-change-functions))
7547 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7548 (diff (abs (- level (length up-head) -1))))
7549 (cond ((and (= level 1) org-called-with-limited-levels
7550 org-allow-promoting-top-level-subtree)
7551 (replace-match "# " nil t))
7552 ((= level 1)
7553 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7554 (t (replace-match up-head nil t)))
7555 ;; Fixup tag positioning
7556 (unless (= level 1)
7557 (and org-auto-align-tags (org-set-tags nil t))
7558 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7559 (run-hooks 'org-after-promote-entry-hook)))
7561 (defun org-demote ()
7562 "Demote the current heading lower down the tree.
7563 If the region is active in `transient-mark-mode', demote all headings
7564 in the region."
7565 (org-back-to-heading t)
7566 (let* ((level (save-match-data (funcall outline-level)))
7567 (after-change-functions (remove 'flyspell-after-change-function
7568 after-change-functions))
7569 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7570 (diff (abs (- level (length down-head) -1))))
7571 (replace-match down-head nil t)
7572 ;; Fixup tag positioning
7573 (and org-auto-align-tags (org-set-tags nil t))
7574 (if org-adapt-indentation (org-fixup-indentation diff))
7575 (run-hooks 'org-after-demote-entry-hook)))
7577 (defun org-cycle-level ()
7578 "Cycle the level of an empty headline through possible states.
7579 This goes first to child, then to parent, level, then up the hierarchy.
7580 After top level, it switches back to sibling level."
7581 (interactive)
7582 (let ((org-adapt-indentation nil))
7583 (when (org-point-at-end-of-empty-headline)
7584 (setq this-command 'org-cycle-level) ; Only needed for caching
7585 (let ((cur-level (org-current-level))
7586 (prev-level (org-get-previous-line-level)))
7587 (cond
7588 ;; If first headline in file, promote to top-level.
7589 ((= prev-level 0)
7590 (loop repeat (/ (- cur-level 1) (org-level-increment))
7591 do (org-do-promote)))
7592 ;; If same level as prev, demote one.
7593 ((= prev-level cur-level)
7594 (org-do-demote))
7595 ;; If parent is top-level, promote to top level if not already.
7596 ((= prev-level 1)
7597 (loop repeat (/ (- cur-level 1) (org-level-increment))
7598 do (org-do-promote)))
7599 ;; If top-level, return to prev-level.
7600 ((= cur-level 1)
7601 (loop repeat (/ (- prev-level 1) (org-level-increment))
7602 do (org-do-demote)))
7603 ;; If less than prev-level, promote one.
7604 ((< cur-level prev-level)
7605 (org-do-promote))
7606 ;; If deeper than prev-level, promote until higher than
7607 ;; prev-level.
7608 ((> cur-level prev-level)
7609 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7610 do (org-do-promote))))
7611 t))))
7613 (defun org-map-tree (fun)
7614 "Call FUN for every heading underneath the current one."
7615 (org-back-to-heading)
7616 (let ((level (funcall outline-level)))
7617 (save-excursion
7618 (funcall fun)
7619 (while (and (progn
7620 (outline-next-heading)
7621 (> (funcall outline-level) level))
7622 (not (eobp)))
7623 (funcall fun)))))
7625 (defun org-map-region (fun beg end)
7626 "Call FUN for every heading between BEG and END."
7627 (let ((org-ignore-region t))
7628 (save-excursion
7629 (setq end (copy-marker end))
7630 (goto-char beg)
7631 (if (and (re-search-forward org-outline-regexp-bol nil t)
7632 (< (point) end))
7633 (funcall fun))
7634 (while (and (progn
7635 (outline-next-heading)
7636 (< (point) end))
7637 (not (eobp)))
7638 (funcall fun)))))
7640 (defvar org-property-end-re) ; silence byte-compiler
7641 (defun org-fixup-indentation (diff)
7642 "Change the indentation in the current entry by DIFF.
7643 However, if any line in the current entry has no indentation, or if it
7644 would end up with no indentation after the change, nothing at all is done."
7645 (save-excursion
7646 (let ((end (save-excursion (outline-next-heading)
7647 (point-marker)))
7648 (prohibit (if (> diff 0)
7649 "^\\S-"
7650 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7651 col)
7652 (unless (save-excursion (end-of-line 1)
7653 (re-search-forward prohibit end t))
7654 (while (and (< (point) end)
7655 (re-search-forward "^[ \t]+" end t))
7656 (goto-char (match-end 0))
7657 (setq col (current-column))
7658 (if (< diff 0) (replace-match ""))
7659 (org-indent-to-column (+ diff col))))
7660 (move-marker end nil))))
7662 (defun org-convert-to-odd-levels ()
7663 "Convert an org-mode file with all levels allowed to one with odd levels.
7664 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7665 level 5 etc."
7666 (interactive)
7667 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7668 (let ((outline-level 'org-outline-level)
7669 (org-odd-levels-only nil) n)
7670 (save-excursion
7671 (goto-char (point-min))
7672 (while (re-search-forward "^\\*\\*+ " nil t)
7673 (setq n (- (length (match-string 0)) 2))
7674 (while (>= (setq n (1- n)) 0)
7675 (org-demote))
7676 (end-of-line 1))))))
7678 (defun org-convert-to-oddeven-levels ()
7679 "Convert an org-mode file with only odd levels to one with odd/even levels.
7680 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7681 file contains a section with an even level, conversion would
7682 destroy the structure of the file. An error is signaled in this
7683 case."
7684 (interactive)
7685 (goto-char (point-min))
7686 ;; First check if there are no even levels
7687 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7688 (org-show-context t)
7689 (error "Not all levels are odd in this file. Conversion not possible"))
7690 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7691 (let ((outline-regexp org-outline-regexp)
7692 (outline-level 'org-outline-level)
7693 (org-odd-levels-only nil) n)
7694 (save-excursion
7695 (goto-char (point-min))
7696 (while (re-search-forward "^\\*\\*+ " nil t)
7697 (setq n (/ (1- (length (match-string 0))) 2))
7698 (while (>= (setq n (1- n)) 0)
7699 (org-promote))
7700 (end-of-line 1))))))
7702 (defun org-tr-level (n)
7703 "Make N odd if required."
7704 (if org-odd-levels-only (1+ (/ n 2)) n))
7706 ;;; Vertical tree motion, cutting and pasting of subtrees
7708 (defun org-move-subtree-up (&optional arg)
7709 "Move the current subtree up past ARG headlines of the same level."
7710 (interactive "p")
7711 (org-move-subtree-down (- (prefix-numeric-value arg))))
7713 (defun org-move-subtree-down (&optional arg)
7714 "Move the current subtree down past ARG headlines of the same level."
7715 (interactive "p")
7716 (setq arg (prefix-numeric-value arg))
7717 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7718 'org-get-last-sibling))
7719 (ins-point (make-marker))
7720 (cnt (abs arg))
7721 (col (current-column))
7722 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7723 ;; Select the tree
7724 (org-back-to-heading)
7725 (setq beg0 (point))
7726 (save-excursion
7727 (setq ne-beg (org-back-over-empty-lines))
7728 (setq beg (point)))
7729 (save-match-data
7730 (save-excursion (outline-end-of-heading)
7731 (setq folded (outline-invisible-p)))
7732 (outline-end-of-subtree))
7733 (outline-next-heading)
7734 (setq ne-end (org-back-over-empty-lines))
7735 (setq end (point))
7736 (goto-char beg0)
7737 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7738 ;; include less whitespace
7739 (save-excursion
7740 (goto-char beg)
7741 (forward-line (- ne-beg ne-end))
7742 (setq beg (point))))
7743 ;; Find insertion point, with error handling
7744 (while (> cnt 0)
7745 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7746 (progn (goto-char beg0)
7747 (error "Cannot move past superior level or buffer limit")))
7748 (setq cnt (1- cnt)))
7749 (if (> arg 0)
7750 ;; Moving forward - still need to move over subtree
7751 (progn (org-end-of-subtree t t)
7752 (save-excursion
7753 (org-back-over-empty-lines)
7754 (or (bolp) (newline)))))
7755 (setq ne-ins (org-back-over-empty-lines))
7756 (move-marker ins-point (point))
7757 (setq txt (buffer-substring beg end))
7758 (org-save-markers-in-region beg end)
7759 (delete-region beg end)
7760 (org-remove-empty-overlays-at beg)
7761 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7762 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7763 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7764 (let ((bbb (point)))
7765 (insert-before-markers txt)
7766 (org-reinstall-markers-in-region bbb)
7767 (move-marker ins-point bbb))
7768 (or (bolp) (insert "\n"))
7769 (setq ins-end (point))
7770 (goto-char ins-point)
7771 (org-skip-whitespace)
7772 (when (and (< arg 0)
7773 (org-first-sibling-p)
7774 (> ne-ins ne-beg))
7775 ;; Move whitespace back to beginning
7776 (save-excursion
7777 (goto-char ins-end)
7778 (let ((kill-whole-line t))
7779 (kill-line (- ne-ins ne-beg)) (point)))
7780 (insert (make-string (- ne-ins ne-beg) ?\n)))
7781 (move-marker ins-point nil)
7782 (if folded
7783 (hide-subtree)
7784 (org-show-entry)
7785 (show-children)
7786 (org-cycle-hide-drawers 'children))
7787 (org-clean-visibility-after-subtree-move)
7788 ;; move back to the initial column we were at
7789 (move-to-column col)))
7791 (defvar org-subtree-clip ""
7792 "Clipboard for cut and paste of subtrees.
7793 This is actually only a copy of the kill, because we use the normal kill
7794 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7796 (defvar org-subtree-clip-folded nil
7797 "Was the last copied subtree folded?
7798 This is used to fold the tree back after pasting.")
7800 (defun org-cut-subtree (&optional n)
7801 "Cut the current subtree into the clipboard.
7802 With prefix arg N, cut this many sequential subtrees.
7803 This is a short-hand for marking the subtree and then cutting it."
7804 (interactive "p")
7805 (org-copy-subtree n 'cut))
7807 (defun org-copy-subtree (&optional n cut force-store-markers)
7808 "Cut the current subtree into the clipboard.
7809 With prefix arg N, cut this many sequential subtrees.
7810 This is a short-hand for marking the subtree and then copying it.
7811 If CUT is non-nil, actually cut the subtree.
7812 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7813 of some markers in the region, even if CUT is non-nil. This is
7814 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7815 (interactive "p")
7816 (let (beg end folded (beg0 (point)))
7817 (if (org-called-interactively-p 'any)
7818 (org-back-to-heading nil) ; take what looks like a subtree
7819 (org-back-to-heading t)) ; take what is really there
7820 (org-back-over-empty-lines)
7821 (setq beg (point))
7822 (skip-chars-forward " \t\r\n")
7823 (save-match-data
7824 (save-excursion (outline-end-of-heading)
7825 (setq folded (outline-invisible-p)))
7826 (condition-case nil
7827 (org-forward-heading-same-level (1- n) t)
7828 (error nil))
7829 (org-end-of-subtree t t))
7830 (org-back-over-empty-lines)
7831 (setq end (point))
7832 (goto-char beg0)
7833 (when (> end beg)
7834 (setq org-subtree-clip-folded folded)
7835 (when (or cut force-store-markers)
7836 (org-save-markers-in-region beg end))
7837 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7838 (setq org-subtree-clip (current-kill 0))
7839 (message "%s: Subtree(s) with %d characters"
7840 (if cut "Cut" "Copied")
7841 (length org-subtree-clip)))))
7843 (defun org-paste-subtree (&optional level tree for-yank)
7844 "Paste the clipboard as a subtree, with modification of headline level.
7845 The entire subtree is promoted or demoted in order to match a new headline
7846 level.
7848 If the cursor is at the beginning of a headline, the same level as
7849 that headline is used to paste the tree
7851 If not, the new level is derived from the *visible* headings
7852 before and after the insertion point, and taken to be the inferior headline
7853 level of the two. So if the previous visible heading is level 3 and the
7854 next is level 4 (or vice versa), level 4 will be used for insertion.
7855 This makes sure that the subtree remains an independent subtree and does
7856 not swallow low level entries.
7858 You can also force a different level, either by using a numeric prefix
7859 argument, or by inserting the heading marker by hand. For example, if the
7860 cursor is after \"*****\", then the tree will be shifted to level 5.
7862 If optional TREE is given, use this text instead of the kill ring.
7864 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7865 move back over whitespace before inserting, and move point to the end of
7866 the inserted text when done."
7867 (interactive "P")
7868 (setq tree (or tree (and kill-ring (current-kill 0))))
7869 (unless (org-kill-is-subtree-p tree)
7870 (error "%s"
7871 (substitute-command-keys
7872 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7873 (org-with-limited-levels
7874 (let* ((visp (not (outline-invisible-p)))
7875 (txt tree)
7876 (^re_ "\\(\\*+\\)[ \t]*")
7877 (old-level (if (string-match org-outline-regexp-bol txt)
7878 (- (match-end 0) (match-beginning 0) 1)
7879 -1))
7880 (force-level (cond (level (prefix-numeric-value level))
7881 ((and (looking-at "[ \t]*$")
7882 (string-match
7883 "^\\*+$" (buffer-substring
7884 (point-at-bol) (point))))
7885 (- (match-end 1) (match-beginning 1)))
7886 ((and (bolp)
7887 (looking-at org-outline-regexp))
7888 (- (match-end 0) (point) 1))))
7889 (previous-level (save-excursion
7890 (condition-case nil
7891 (progn
7892 (outline-previous-visible-heading 1)
7893 (if (looking-at ^re_)
7894 (- (match-end 0) (match-beginning 0) 1)
7896 (error 1))))
7897 (next-level (save-excursion
7898 (condition-case nil
7899 (progn
7900 (or (looking-at org-outline-regexp)
7901 (outline-next-visible-heading 1))
7902 (if (looking-at ^re_)
7903 (- (match-end 0) (match-beginning 0) 1)
7905 (error 1))))
7906 (new-level (or force-level (max previous-level next-level)))
7907 (shift (if (or (= old-level -1)
7908 (= new-level -1)
7909 (= old-level new-level))
7911 (- new-level old-level)))
7912 (delta (if (> shift 0) -1 1))
7913 (func (if (> shift 0) 'org-demote 'org-promote))
7914 (org-odd-levels-only nil)
7915 beg end newend)
7916 ;; Remove the forced level indicator
7917 (if force-level
7918 (delete-region (point-at-bol) (point)))
7919 ;; Paste
7920 (beginning-of-line (if (bolp) 1 2))
7921 (unless for-yank (org-back-over-empty-lines))
7922 (setq beg (point))
7923 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7924 (insert-before-markers txt)
7925 (unless (string-match "\n\\'" txt) (insert "\n"))
7926 (setq newend (point))
7927 (org-reinstall-markers-in-region beg)
7928 (setq end (point))
7929 (goto-char beg)
7930 (skip-chars-forward " \t\n\r")
7931 (setq beg (point))
7932 (if (and (outline-invisible-p) visp)
7933 (save-excursion (outline-show-heading)))
7934 ;; Shift if necessary
7935 (unless (= shift 0)
7936 (save-restriction
7937 (narrow-to-region beg end)
7938 (while (not (= shift 0))
7939 (org-map-region func (point-min) (point-max))
7940 (setq shift (+ delta shift)))
7941 (goto-char (point-min))
7942 (setq newend (point-max))))
7943 (when (or (org-called-interactively-p 'interactive) for-yank)
7944 (message "Clipboard pasted as level %d subtree" new-level))
7945 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7946 kill-ring
7947 (eq org-subtree-clip (current-kill 0))
7948 org-subtree-clip-folded)
7949 ;; The tree was folded before it was killed/copied
7950 (hide-subtree))
7951 (and for-yank (goto-char newend)))))
7953 (defun org-kill-is-subtree-p (&optional txt)
7954 "Check if the current kill is an outline subtree, or a set of trees.
7955 Returns nil if kill does not start with a headline, or if the first
7956 headline level is not the largest headline level in the tree.
7957 So this will actually accept several entries of equal levels as well,
7958 which is OK for `org-paste-subtree'.
7959 If optional TXT is given, check this string instead of the current kill."
7960 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7961 (re (org-get-limited-outline-regexp))
7962 (^re (concat "^" re))
7963 (start-level (and kill
7964 (string-match
7965 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7966 kill)
7967 (- (match-end 2) (match-beginning 2) 1)))
7968 (start (1+ (or (match-beginning 2) -1))))
7969 (if (not start-level)
7970 (progn
7971 nil) ;; does not even start with a heading
7972 (catch 'exit
7973 (while (setq start (string-match ^re kill (1+ start)))
7974 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7975 (throw 'exit nil)))
7976 t))))
7978 (defvar org-markers-to-move nil
7979 "Markers that should be moved with a cut-and-paste operation.
7980 Those markers are stored together with their positions relative to
7981 the start of the region.")
7983 (defun org-save-markers-in-region (beg end)
7984 "Check markers in region.
7985 If these markers are between BEG and END, record their position relative
7986 to BEG, so that after moving the block of text, we can put the markers back
7987 into place.
7988 This function gets called just before an entry or tree gets cut from the
7989 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7990 called immediately, to move the markers with the entries."
7991 (setq org-markers-to-move nil)
7992 (when (featurep 'org-clock)
7993 (org-clock-save-markers-for-cut-and-paste beg end))
7994 (when (featurep 'org-agenda)
7995 (org-agenda-save-markers-for-cut-and-paste beg end)))
7997 (defun org-check-and-save-marker (marker beg end)
7998 "Check if MARKER is between BEG and END.
7999 If yes, remember the marker and the distance to BEG."
8000 (when (and (marker-buffer marker)
8001 (equal (marker-buffer marker) (current-buffer)))
8002 (if (and (>= marker beg) (< marker end))
8003 (push (cons marker (- marker beg)) org-markers-to-move))))
8005 (defun org-reinstall-markers-in-region (beg)
8006 "Move all remembered markers to their position relative to BEG."
8007 (mapc (lambda (x)
8008 (move-marker (car x) (+ beg (cdr x))))
8009 org-markers-to-move)
8010 (setq org-markers-to-move nil))
8012 (defun org-narrow-to-subtree ()
8013 "Narrow buffer to the current subtree."
8014 (interactive)
8015 (save-excursion
8016 (save-match-data
8017 (org-with-limited-levels
8018 (narrow-to-region
8019 (progn (org-back-to-heading t) (point))
8020 (progn (org-end-of-subtree t t)
8021 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8022 (point)))))))
8024 (defun org-narrow-to-block ()
8025 "Narrow buffer to the current block."
8026 (interactive)
8027 (let* ((case-fold-search t)
8028 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8029 "^[ \t]*#\\+end_.*")))
8030 (if blockp
8031 (narrow-to-region (car blockp) (cdr blockp))
8032 (error "Not in a block"))))
8034 (eval-when-compile
8035 (defvar org-property-drawer-re))
8037 (defvar org-property-start-re) ;; defined below
8038 (defun org-clone-subtree-with-time-shift (n &optional shift)
8039 "Clone the task (subtree) at point N times.
8040 The clones will be inserted as siblings.
8042 In interactive use, the user will be prompted for the number of
8043 clones to be produced, and for a time SHIFT, which may be a
8044 repeater as used in time stamps, for example `+3d'.
8046 When a valid repeater is given and the entry contains any time
8047 stamps, the clones will become a sequence in time, with time
8048 stamps in the subtree shifted for each clone produced. If SHIFT
8049 is nil or the empty string, time stamps will be left alone. The
8050 ID property of the original subtree is removed.
8052 If the original subtree did contain time stamps with a repeater,
8053 the following will happen:
8054 - the repeater will be removed in each clone
8055 - an additional clone will be produced, with the current, unshifted
8056 date(s) in the entry.
8057 - the original entry will be placed *after* all the clones, with
8058 repeater intact.
8059 - the start days in the repeater in the original entry will be shifted
8060 to past the last clone.
8061 In this way you can spell out a number of instances of a repeating task,
8062 and still retain the repeater to cover future instances of the task."
8063 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8064 (let (beg end template task idprop
8065 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8066 (drawer-re org-drawer-regexp))
8067 (if (not (and (integerp n) (> n 0)))
8068 (error "Invalid number of replications %s" n))
8069 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8070 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8071 shift)))
8072 (error "Invalid shift specification %s" shift))
8073 (when doshift
8074 (setq shift-n (string-to-number (match-string 1 shift))
8075 shift-what (cdr (assoc (match-string 2 shift)
8076 '(("d" . day) ("w" . week)
8077 ("m" . month) ("y" . year))))))
8078 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8079 (setq nmin 1 nmax n)
8080 (org-back-to-heading t)
8081 (setq beg (point))
8082 (setq idprop (org-entry-get nil "ID"))
8083 (org-end-of-subtree t t)
8084 (or (bolp) (insert "\n"))
8085 (setq end (point))
8086 (setq template (buffer-substring beg end))
8087 (when (and doshift
8088 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8089 (delete-region beg end)
8090 (setq end beg)
8091 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8092 (goto-char end)
8093 (loop for n from nmin to nmax do
8094 ;; prepare clone
8095 (with-temp-buffer
8096 (insert template)
8097 (org-mode)
8098 (goto-char (point-min))
8099 (org-show-subtree)
8100 (and idprop (if org-clone-delete-id
8101 (org-entry-delete nil "ID")
8102 (org-id-get-create t)))
8103 (unless (= n 0)
8104 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8105 (kill-whole-line))
8106 (goto-char (point-min))
8107 (while (re-search-forward drawer-re nil t)
8108 (mapc (lambda (d)
8109 (org-remove-empty-drawer-at d (point))) org-drawers)))
8110 (goto-char (point-min))
8111 (when doshift
8112 (while (re-search-forward org-ts-regexp-both nil t)
8113 (org-timestamp-change (* n shift-n) shift-what))
8114 (unless (= n n-no-remove)
8115 (goto-char (point-min))
8116 (while (re-search-forward org-ts-regexp nil t)
8117 (save-excursion
8118 (goto-char (match-beginning 0))
8119 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8120 (delete-region (match-beginning 1) (match-end 1)))))))
8121 (setq task (buffer-string)))
8122 (insert task))
8123 (goto-char beg)))
8125 ;;; Outline Sorting
8127 (defun org-sort (with-case)
8128 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8129 Optional argument WITH-CASE means sort case-sensitively."
8130 (interactive "P")
8131 (cond
8132 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8133 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8135 (org-call-with-arg 'org-sort-entries with-case))))
8137 (defun org-sort-remove-invisible (s)
8138 (remove-text-properties 0 (length s) org-rm-props s)
8139 (while (string-match org-bracket-link-regexp s)
8140 (setq s (replace-match (if (match-end 2)
8141 (match-string 3 s)
8142 (match-string 1 s)) t t s)))
8145 (defvar org-priority-regexp) ; defined later in the file
8147 (defvar org-after-sorting-entries-or-items-hook nil
8148 "Hook that is run after a bunch of entries or items have been sorted.
8149 When children are sorted, the cursor is in the parent line when this
8150 hook gets called. When a region or a plain list is sorted, the cursor
8151 will be in the first entry of the sorted region/list.")
8153 (defun org-sort-entries
8154 (&optional with-case sorting-type getkey-func compare-func property)
8155 "Sort entries on a certain level of an outline tree.
8156 If there is an active region, the entries in the region are sorted.
8157 Else, if the cursor is before the first entry, sort the top-level items.
8158 Else, the children of the entry at point are sorted.
8160 Sorting can be alphabetically, numerically, by date/time as given by
8161 a time stamp, by a property or by priority.
8163 The command prompts for the sorting type unless it has been given to the
8164 function through the SORTING-TYPE argument, which needs to be a character,
8165 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
8166 precise meaning of each character:
8168 n Numerically, by converting the beginning of the entry/item to a number.
8169 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8170 t By date/time, either the first active time stamp in the entry, or, if
8171 none exist, by the first inactive one.
8172 s By the scheduled date/time.
8173 d By deadline date/time.
8174 c By creation time, which is assumed to be the first inactive time stamp
8175 at the beginning of a line.
8176 p By priority according to the cookie.
8177 r By the value of a property.
8179 Capital letters will reverse the sort order.
8181 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8182 called with point at the beginning of the record. It must return either
8183 a string or a number that should serve as the sorting key for that record.
8185 Comparing entries ignores case by default. However, with an optional argument
8186 WITH-CASE, the sorting considers case as well."
8187 (interactive "P")
8188 (let ((case-func (if with-case 'identity 'downcase))
8189 start beg end stars re re2
8190 txt what tmp)
8191 ;; Find beginning and end of region to sort
8192 (cond
8193 ((org-region-active-p)
8194 ;; we will sort the region
8195 (setq end (region-end)
8196 what "region")
8197 (goto-char (region-beginning))
8198 (if (not (org-at-heading-p)) (outline-next-heading))
8199 (setq start (point)))
8200 ((or (org-at-heading-p)
8201 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8202 ;; we will sort the children of the current headline
8203 (org-back-to-heading)
8204 (setq start (point)
8205 end (progn (org-end-of-subtree t t)
8206 (or (bolp) (insert "\n"))
8207 (org-back-over-empty-lines)
8208 (point))
8209 what "children")
8210 (goto-char start)
8211 (show-subtree)
8212 (outline-next-heading))
8214 ;; we will sort the top-level entries in this file
8215 (goto-char (point-min))
8216 (or (org-at-heading-p) (outline-next-heading))
8217 (setq start (point))
8218 (goto-char (point-max))
8219 (beginning-of-line 1)
8220 (when (looking-at ".*?\\S-")
8221 ;; File ends in a non-white line
8222 (end-of-line 1)
8223 (insert "\n"))
8224 (setq end (point-max))
8225 (setq what "top-level")
8226 (goto-char start)
8227 (show-all)))
8229 (setq beg (point))
8230 (if (>= beg end) (error "Nothing to sort"))
8232 (looking-at "\\(\\*+\\)")
8233 (setq stars (match-string 1)
8234 re (concat "^" (regexp-quote stars) " +")
8235 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8236 txt (buffer-substring beg end))
8237 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8238 (if (and (not (equal stars "*")) (string-match re2 txt))
8239 (error "Region to sort contains a level above the first entry"))
8241 (unless sorting-type
8242 (message
8243 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8244 [t]ime [s]cheduled [d]eadline [c]reated
8245 A/N/T/S/D/C/P/O/F means reversed:"
8246 what)
8247 (setq sorting-type (read-char-exclusive))
8249 (and (= (downcase sorting-type) ?f)
8250 (setq getkey-func
8251 (org-icompleting-read "Sort using function: "
8252 obarray 'fboundp t nil nil))
8253 (setq getkey-func (intern getkey-func)))
8255 (and (= (downcase sorting-type) ?r)
8256 (setq property
8257 (org-icompleting-read "Property: "
8258 (mapcar 'list (org-buffer-property-keys t))
8259 nil t))))
8261 (message "Sorting entries...")
8263 (save-restriction
8264 (narrow-to-region start end)
8265 (let ((dcst (downcase sorting-type))
8266 (case-fold-search nil)
8267 (now (current-time)))
8268 (sort-subr
8269 (/= dcst sorting-type)
8270 ;; This function moves to the beginning character of the "record" to
8271 ;; be sorted.
8272 (lambda nil
8273 (if (re-search-forward re nil t)
8274 (goto-char (match-beginning 0))
8275 (goto-char (point-max))))
8276 ;; This function moves to the last character of the "record" being
8277 ;; sorted.
8278 (lambda nil
8279 (save-match-data
8280 (condition-case nil
8281 (outline-forward-same-level 1)
8282 (error
8283 (goto-char (point-max))))))
8284 ;; This function returns the value that gets sorted against.
8285 (lambda nil
8286 (cond
8287 ((= dcst ?n)
8288 (if (looking-at org-complex-heading-regexp)
8289 (string-to-number (match-string 4))
8290 nil))
8291 ((= dcst ?a)
8292 (if (looking-at org-complex-heading-regexp)
8293 (funcall case-func (match-string 4))
8294 nil))
8295 ((= dcst ?t)
8296 (let ((end (save-excursion (outline-next-heading) (point))))
8297 (if (or (re-search-forward org-ts-regexp end t)
8298 (re-search-forward org-ts-regexp-both end t))
8299 (org-time-string-to-seconds (match-string 0))
8300 (org-float-time now))))
8301 ((= dcst ?c)
8302 (let ((end (save-excursion (outline-next-heading) (point))))
8303 (if (re-search-forward
8304 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8305 end t)
8306 (org-time-string-to-seconds (match-string 0))
8307 (org-float-time now))))
8308 ((= dcst ?s)
8309 (let ((end (save-excursion (outline-next-heading) (point))))
8310 (if (re-search-forward org-scheduled-time-regexp end t)
8311 (org-time-string-to-seconds (match-string 1))
8312 (org-float-time now))))
8313 ((= dcst ?d)
8314 (let ((end (save-excursion (outline-next-heading) (point))))
8315 (if (re-search-forward org-deadline-time-regexp end t)
8316 (org-time-string-to-seconds (match-string 1))
8317 (org-float-time now))))
8318 ((= dcst ?p)
8319 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8320 (string-to-char (match-string 2))
8321 org-default-priority))
8322 ((= dcst ?r)
8323 (or (org-entry-get nil property) ""))
8324 ((= dcst ?o)
8325 (if (looking-at org-complex-heading-regexp)
8326 (- 9999 (length (member (match-string 2)
8327 org-todo-keywords-1)))))
8328 ((= dcst ?f)
8329 (if getkey-func
8330 (progn
8331 (setq tmp (funcall getkey-func))
8332 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8333 tmp)
8334 (error "Invalid key function `%s'" getkey-func)))
8335 (t (error "Invalid sorting type `%c'" sorting-type))))
8337 (cond
8338 ((= dcst ?a) 'string<)
8339 ((= dcst ?f) compare-func)
8340 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8341 (run-hooks 'org-after-sorting-entries-or-items-hook)
8342 (message "Sorting entries...done")))
8344 (defun org-do-sort (table what &optional with-case sorting-type)
8345 "Sort TABLE of WHAT according to SORTING-TYPE.
8346 The user will be prompted for the SORTING-TYPE if the call to this
8347 function does not specify it. WHAT is only for the prompt, to indicate
8348 what is being sorted. The sorting key will be extracted from
8349 the car of the elements of the table.
8350 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8351 (unless sorting-type
8352 (message
8353 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
8354 what)
8355 (setq sorting-type (read-char-exclusive)))
8356 (let ((dcst (downcase sorting-type))
8357 extractfun comparefun)
8358 ;; Define the appropriate functions
8359 (cond
8360 ((= dcst ?n)
8361 (setq extractfun 'string-to-number
8362 comparefun (if (= dcst sorting-type) '< '>)))
8363 ((= dcst ?a)
8364 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8365 (lambda(x) (downcase (org-sort-remove-invisible x))))
8366 comparefun (if (= dcst sorting-type)
8367 'string<
8368 (lambda (a b) (and (not (string< a b))
8369 (not (string= a b)))))))
8370 ((= dcst ?t)
8371 (setq extractfun
8372 (lambda (x)
8373 (if (or (string-match org-ts-regexp x)
8374 (string-match org-ts-regexp-both x))
8375 (org-float-time
8376 (org-time-string-to-time (match-string 0 x)))
8378 comparefun (if (= dcst sorting-type) '< '>)))
8379 (t (error "Invalid sorting type `%c'" sorting-type)))
8381 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8382 table)
8383 (lambda (a b) (funcall comparefun (car a) (car b))))))
8386 ;;; The orgstruct minor mode
8388 ;; Define a minor mode which can be used in other modes in order to
8389 ;; integrate the org-mode structure editing commands.
8391 ;; This is really a hack, because the org-mode structure commands use
8392 ;; keys which normally belong to the major mode. Here is how it
8393 ;; works: The minor mode defines all the keys necessary to operate the
8394 ;; structure commands, but wraps the commands into a function which
8395 ;; tests if the cursor is currently at a headline or a plain list
8396 ;; item. If that is the case, the structure command is used,
8397 ;; temporarily setting many Org-mode variables like regular
8398 ;; expressions for filling etc. However, when any of those keys is
8399 ;; used at a different location, function uses `key-binding' to look
8400 ;; up if the key has an associated command in another currently active
8401 ;; keymap (minor modes, major mode, global), and executes that
8402 ;; command. There might be problems if any of the keys is otherwise
8403 ;; used as a prefix key.
8405 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8406 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8407 ;; addresses this by checking explicitly for both bindings.
8409 (defvar orgstruct-mode-map (make-sparse-keymap)
8410 "Keymap for the minor `orgstruct-mode'.")
8412 (defvar org-local-vars nil
8413 "List of local variables, for use by `orgstruct-mode'.")
8415 ;;;###autoload
8416 (define-minor-mode orgstruct-mode
8417 "Toggle the minor mode `orgstruct-mode'.
8418 This mode is for using Org-mode structure commands in other
8419 modes. The following keys behave as if Org-mode were active, if
8420 the cursor is on a headline, or on a plain list item (both as
8421 defined by Org-mode).
8423 M-up Move entry/item up
8424 M-down Move entry/item down
8425 M-left Promote
8426 M-right Demote
8427 M-S-up Move entry/item up
8428 M-S-down Move entry/item down
8429 M-S-left Promote subtree
8430 M-S-right Demote subtree
8431 M-q Fill paragraph and items like in Org-mode
8432 C-c ^ Sort entries
8433 C-c - Cycle list bullet
8434 TAB Cycle item visibility
8435 M-RET Insert new heading/item
8436 S-M-RET Insert new TODO heading / Checkbox item
8437 C-c C-c Set tags / toggle checkbox"
8438 nil " OrgStruct" nil
8439 (org-load-modules-maybe)
8440 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8442 ;;;###autoload
8443 (defun turn-on-orgstruct ()
8444 "Unconditionally turn on `orgstruct-mode'."
8445 (orgstruct-mode 1))
8447 (defvar org-fb-vars nil)
8448 (make-variable-buffer-local 'org-fb-vars)
8449 (defun orgstruct++-mode (&optional arg)
8450 "Toggle `orgstruct-mode', the enhanced version of it.
8451 In addition to setting orgstruct-mode, this also exports all
8452 indentation and autofilling variables from org-mode into the
8453 buffer. It will also recognize item context in multiline items."
8454 (interactive "P")
8455 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8456 (if (< arg 1)
8457 (progn (orgstruct-mode -1)
8458 (mapc (lambda(v)
8459 (org-set-local (car v)
8460 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8461 org-fb-vars))
8462 (orgstruct-mode 1)
8463 (setq org-fb-vars nil)
8464 (let (var val)
8465 (mapc
8466 (lambda (x)
8467 (when (string-match
8468 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8469 (symbol-name (car x)))
8470 (setq var (car x) val (nth 1 x))
8471 (push (list var `(quote ,(eval var))) org-fb-vars)
8472 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8473 org-local-vars)
8474 (org-set-local 'orgstruct-is-++ t))))
8476 (defvar orgstruct-is-++ nil
8477 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8478 (make-variable-buffer-local 'orgstruct-is-++)
8480 ;;;###autoload
8481 (defun turn-on-orgstruct++ ()
8482 "Unconditionally turn on `orgstruct++-mode'."
8483 (orgstruct++-mode 1))
8485 (defun orgstruct-error ()
8486 "Error when there is no default binding for a structure key."
8487 (interactive)
8488 (error "This key has no function outside structure elements"))
8490 (defun orgstruct-setup ()
8491 "Setup orgstruct keymaps."
8492 (let ((nfunc 0)
8493 (bindings
8494 (list
8495 '([(meta up)] org-metaup)
8496 '([(meta down)] org-metadown)
8497 '([(meta left)] org-metaleft)
8498 '([(meta right)] org-metaright)
8499 '([(meta shift up)] org-shiftmetaup)
8500 '([(meta shift down)] org-shiftmetadown)
8501 '([(meta shift left)] org-shiftmetaleft)
8502 '([(meta shift right)] org-shiftmetaright)
8503 '([?\e (up)] org-metaup)
8504 '([?\e (down)] org-metadown)
8505 '([?\e (left)] org-metaleft)
8506 '([?\e (right)] org-metaright)
8507 '([?\e (shift up)] org-shiftmetaup)
8508 '([?\e (shift down)] org-shiftmetadown)
8509 '([?\e (shift left)] org-shiftmetaleft)
8510 '([?\e (shift right)] org-shiftmetaright)
8511 '([(shift up)] org-shiftup)
8512 '([(shift down)] org-shiftdown)
8513 '([(shift left)] org-shiftleft)
8514 '([(shift right)] org-shiftright)
8515 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8516 '("\M-q" fill-paragraph)
8517 '("\C-c^" org-sort)
8518 '("\C-c-" org-cycle-list-bullet)))
8519 elt key fun cmd)
8520 (while (setq elt (pop bindings))
8521 (setq nfunc (1+ nfunc))
8522 (setq key (org-key (car elt))
8523 fun (nth 1 elt)
8524 cmd (orgstruct-make-binding fun nfunc key))
8525 (org-defkey orgstruct-mode-map key cmd))
8527 ;; Prevent an error for users who forgot to make autoloads
8528 (require 'org-element)
8530 ;; Special treatment needed for TAB and RET
8531 (org-defkey orgstruct-mode-map [(tab)]
8532 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8533 (org-defkey orgstruct-mode-map "\C-i"
8534 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8536 (org-defkey orgstruct-mode-map "\M-\C-m"
8537 (orgstruct-make-binding 'org-insert-heading 105
8538 "\M-\C-m" [(meta return)]))
8539 (org-defkey orgstruct-mode-map [(meta return)]
8540 (orgstruct-make-binding 'org-insert-heading 106
8541 [(meta return)] "\M-\C-m"))
8543 (org-defkey orgstruct-mode-map [(shift meta return)]
8544 (orgstruct-make-binding 'org-insert-todo-heading 107
8545 [(meta return)] "\M-\C-m"))
8547 (org-defkey orgstruct-mode-map "\e\C-m"
8548 (orgstruct-make-binding 'org-insert-heading 108
8549 "\e\C-m" [?\e (return)]))
8550 (org-defkey orgstruct-mode-map [?\e (return)]
8551 (orgstruct-make-binding 'org-insert-heading 109
8552 [?\e (return)] "\e\C-m"))
8553 (org-defkey orgstruct-mode-map [?\e (shift return)]
8554 (orgstruct-make-binding 'org-insert-todo-heading 110
8555 [?\e (return)] "\e\C-m"))
8557 (unless org-local-vars
8558 (setq org-local-vars (org-get-local-variables)))
8562 (defun orgstruct-make-binding (fun n &rest keys)
8563 "Create a function for binding in the structure minor mode.
8564 FUN is the command to call inside a table. N is used to create a unique
8565 command name. KEYS are keys that should be checked in for a command
8566 to execute outside of tables."
8567 (eval
8568 (list 'defun
8569 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8570 '(arg)
8571 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8572 "Outside of structure, run the binding of `"
8573 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8574 "'.")
8575 '(interactive "p")
8576 (list 'if
8577 `(org-context-p 'headline 'item
8578 (and orgstruct-is-++
8579 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8580 'item-body))
8581 (list 'org-run-like-in-org-mode (list 'quote fun))
8582 (list 'let '(orgstruct-mode)
8583 (list 'call-interactively
8584 (append '(or)
8585 (mapcar (lambda (k)
8586 (list 'key-binding k))
8587 keys)
8588 '('orgstruct-error))))))))
8590 (defun org-contextualize-keys (alist contexts)
8591 "Return valid elements in ALIST depending on CONTEXTS.
8593 `org-agenda-custom-commands' or `org-capture-templates' are the
8594 values used for ALIST, and `org-agenda-custom-commands-contexts'
8595 or `org-capture-templates-contexts' are the associated contexts
8596 definitions."
8597 (let ((contexts
8598 ;; normalize contexts
8599 (mapcar
8600 (lambda(c) (cond ((listp (cadr c))
8601 (list (car c) (car c) (cadr c)))
8602 ((string= "" (cadr c))
8603 (list (car c) (car c) (caddr c)))
8604 (t c))) contexts))
8605 (a alist) c r s)
8606 ;; loop over all commands or templates
8607 (while (setq c (pop a))
8608 (let (vrules repl)
8609 (cond
8610 ((not (assoc (car c) contexts))
8611 (push c r))
8612 ((and (assoc (car c) contexts)
8613 (setq vrules (org-contextualize-validate-key
8614 (car c) contexts)))
8615 (mapc (lambda (vr)
8616 (when (not (equal (car vr) (cadr vr)))
8617 (setq repl vr))) vrules)
8618 (if (not repl) (push c r)
8619 (push (cadr repl) s)
8620 (push
8621 (cons (car c)
8622 (cdr (or (assoc (cadr repl) alist)
8623 (error "Undefined key `%s' as contextual replacement for `%s'"
8624 (cadr repl) (car c)))))
8625 r))))))
8626 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8627 (delq
8629 (delete-dups
8630 (mapcar (lambda (x)
8631 (let ((tpl (car x)))
8632 (when (not (delq
8634 (mapcar (lambda(y)
8635 (equal y tpl)) s))) x)))
8636 (reverse r))))))
8638 (defun org-contextualize-validate-key (key contexts)
8639 "Check CONTEXTS for agenda or capture KEY."
8640 (let (r rr res)
8641 (while (setq r (pop contexts))
8642 (mapc
8643 (lambda (rr)
8644 (when
8645 (and (equal key (car r))
8646 (if (functionp rr) (funcall rr)
8647 (or (and (eq (car rr) 'in-file)
8648 (buffer-file-name)
8649 (string-match (cdr rr) (buffer-file-name)))
8650 (and (eq (car rr) 'in-mode)
8651 (string-match (cdr rr) (symbol-name major-mode)))
8652 (when (and (eq (car rr) 'not-in-file)
8653 (buffer-file-name))
8654 (not (string-match (cdr rr) (buffer-file-name))))
8655 (when (eq (car rr) 'not-in-mode)
8656 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8657 (push r res)))
8658 (car (last r))))
8659 (delete-dups (delq nil res))))
8661 (defun org-context-p (&rest contexts)
8662 "Check if local context is any of CONTEXTS.
8663 Possible values in the list of contexts are `table', `headline', and `item'."
8664 (let ((pos (point)))
8665 (goto-char (point-at-bol))
8666 (prog1 (or (and (memq 'table contexts)
8667 (looking-at "[ \t]*|"))
8668 (and (memq 'headline contexts)
8669 (looking-at org-outline-regexp))
8670 (and (memq 'item contexts)
8671 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8672 (and (memq 'item-body contexts)
8673 (org-in-item-p)))
8674 (goto-char pos))))
8676 (defun org-get-local-variables ()
8677 "Return a list of all local variables in an Org mode buffer."
8678 (let (varlist)
8679 (with-current-buffer (get-buffer-create "*Org tmp*")
8680 (erase-buffer)
8681 (org-mode)
8682 (setq varlist (buffer-local-variables)))
8683 (kill-buffer "*Org tmp*")
8684 (delq nil
8685 (mapcar
8686 (lambda (x)
8687 (setq x
8688 (if (symbolp x)
8689 (list x)
8690 (list (car x) (list 'quote (cdr x)))))
8691 (if (string-match
8692 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8693 (symbol-name (car x)))
8694 x nil))
8695 varlist))))
8697 (defun org-clone-local-variables (from-buffer &optional regexp)
8698 "Clone local variables from FROM-BUFFER.
8699 Optional argument REGEXP selects variables to clone."
8700 (mapc
8701 (lambda (pair)
8702 (and (symbolp (car pair))
8703 (or (null regexp)
8704 (string-match regexp (symbol-name (car pair))))
8705 (set (make-local-variable (car pair))
8706 (cdr pair))))
8707 (buffer-local-variables from-buffer)))
8709 ;;;###autoload
8710 (defun org-run-like-in-org-mode (cmd)
8711 "Run a command, pretending that the current buffer is in Org-mode.
8712 This will temporarily bind local variables that are typically bound in
8713 Org-mode to the values they have in Org-mode, and then interactively
8714 call CMD."
8715 (org-load-modules-maybe)
8716 (unless org-local-vars
8717 (setq org-local-vars (org-get-local-variables)))
8718 (eval (list 'let org-local-vars
8719 (list 'call-interactively (list 'quote cmd)))))
8721 ;;;; Archiving
8723 (defun org-get-category (&optional pos force-refresh)
8724 "Get the category applying to position POS."
8725 (save-match-data
8726 (if force-refresh (org-refresh-category-properties))
8727 (let ((pos (or pos (point))))
8728 (or (get-text-property pos 'org-category)
8729 (progn (org-refresh-category-properties)
8730 (get-text-property pos 'org-category))))))
8732 (defun org-refresh-category-properties ()
8733 "Refresh category text properties in the buffer."
8734 (let ((case-fold-search t)
8735 (inhibit-read-only t)
8736 (def-cat (cond
8737 ((null org-category)
8738 (if buffer-file-name
8739 (file-name-sans-extension
8740 (file-name-nondirectory buffer-file-name))
8741 "???"))
8742 ((symbolp org-category) (symbol-name org-category))
8743 (t org-category)))
8744 beg end cat pos optionp)
8745 (org-unmodified
8746 (save-excursion
8747 (save-restriction
8748 (widen)
8749 (goto-char (point-min))
8750 (put-text-property (point) (point-max) 'org-category def-cat)
8751 (while (re-search-forward
8752 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8753 (setq pos (match-end 0)
8754 optionp (equal (char-after (match-beginning 0)) ?#)
8755 cat (org-trim (match-string 2)))
8756 (if optionp
8757 (setq beg (point-at-bol) end (point-max))
8758 (org-back-to-heading t)
8759 (setq beg (point) end (org-end-of-subtree t t)))
8760 (put-text-property beg end 'org-category cat)
8761 (put-text-property beg end 'org-category-position beg)
8762 (goto-char pos)))))))
8765 ;;;; Link Stuff
8767 ;;; Link abbreviations
8769 (defun org-link-expand-abbrev (link)
8770 "Apply replacements as defined in `org-link-abbrev-alist'."
8771 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8772 (let* ((key (match-string 1 link))
8773 (as (or (assoc key org-link-abbrev-alist-local)
8774 (assoc key org-link-abbrev-alist)))
8775 (tag (and (match-end 2) (match-string 3 link)))
8776 rpl)
8777 (if (not as)
8778 link
8779 (setq rpl (cdr as))
8780 (cond
8781 ((symbolp rpl) (funcall rpl tag))
8782 ((string-match "%(\\([^)]+\\))" rpl)
8783 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8784 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8785 ((string-match "%h" rpl)
8786 (replace-match (url-hexify-string (or tag "")) t t rpl))
8787 (t (concat rpl tag)))))
8788 link))
8790 ;;; Storing and inserting links
8792 (defvar org-insert-link-history nil
8793 "Minibuffer history for links inserted with `org-insert-link'.")
8795 (defvar org-stored-links nil
8796 "Contains the links stored with `org-store-link'.")
8798 (defvar org-store-link-plist nil
8799 "Plist with info about the most recently link created with `org-store-link'.")
8801 (defvar org-link-protocols nil
8802 "Link protocols added to Org-mode using `org-add-link-type'.")
8804 (defvar org-store-link-functions nil
8805 "List of functions that are called to create and store a link.
8806 Each function will be called in turn until one returns a non-nil
8807 value. Each function should check if it is responsible for creating
8808 this link (for example by looking at the major mode).
8809 If not, it must exit and return nil.
8810 If yes, it should return a non-nil value after a calling
8811 `org-store-link-props' with a list of properties and values.
8812 Special properties are:
8814 :type The link prefix, like \"http\". This must be given.
8815 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8816 This is obligatory as well.
8817 :description Optional default description for the second pair
8818 of brackets in an Org-mode link. The user can still change
8819 this when inserting this link into an Org-mode buffer.
8821 In addition to these, any additional properties can be specified
8822 and then used in capture templates.")
8824 (defun org-add-link-type (type &optional follow export)
8825 "Add TYPE to the list of `org-link-types'.
8826 Re-compute all regular expressions depending on `org-link-types'
8828 FOLLOW and EXPORT are two functions.
8830 FOLLOW should take the link path as the single argument and do whatever
8831 is necessary to follow the link, for example find a file or display
8832 a mail message.
8834 EXPORT should format the link path for export to one of the export formats.
8835 It should be a function accepting three arguments:
8837 path the path of the link, the text after the prefix (like \"http:\")
8838 desc the description of the link, if any, or a description added by
8839 org-export-normalize-links if there is none
8840 format the export format, a symbol like `html' or `latex' or `ascii'..
8842 The function may use the FORMAT information to return different values
8843 depending on the format. The return value will be put literally into
8844 the exported file. If the return value is nil, this means Org should
8845 do what it normally does with links which do not have EXPORT defined.
8847 Org-mode has a built-in default for exporting links. If you are happy with
8848 this default, there is no need to define an export function for the link
8849 type. For a simple example of an export function, see `org-bbdb.el'."
8850 (add-to-list 'org-link-types type t)
8851 (org-make-link-regexps)
8852 (if (assoc type org-link-protocols)
8853 (setcdr (assoc type org-link-protocols) (list follow export))
8854 (push (list type follow export) org-link-protocols)))
8856 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8857 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8859 ;;;###autoload
8860 (defun org-store-link (arg)
8861 "\\<org-mode-map>Store an org-link to the current location.
8862 This link is added to `org-stored-links' and can later be inserted
8863 into an org-buffer with \\[org-insert-link].
8865 For some link types, a prefix arg is interpreted:
8866 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8867 For file links, arg negates `org-context-in-file-links'."
8868 (interactive "P")
8869 (org-load-modules-maybe)
8870 (setq org-store-link-plist nil) ; reset
8871 (org-with-limited-levels
8872 (let (link cpltxt desc description search txt custom-id agenda-link)
8873 (cond
8875 ((run-hook-with-args-until-success 'org-store-link-functions)
8876 (setq link (plist-get org-store-link-plist :link)
8877 desc (or (plist-get org-store-link-plist :description) link)))
8879 ((org-src-edit-buffer-p)
8880 (let (label gc)
8881 (while (or (not label)
8882 (save-excursion
8883 (save-restriction
8884 (widen)
8885 (goto-char (point-min))
8886 (re-search-forward
8887 (regexp-quote (format org-coderef-label-format label))
8888 nil t))))
8889 (when label (message "Label exists already") (sit-for 2))
8890 (setq label (read-string "Code line label: " label)))
8891 (end-of-line 1)
8892 (setq link (format org-coderef-label-format label))
8893 (setq gc (- 79 (length link)))
8894 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8895 (insert link)
8896 (setq link (concat "(" label ")") desc nil)))
8898 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8899 ;; We are in the agenda, link to referenced location
8900 (let ((m (or (get-text-property (point) 'org-hd-marker)
8901 (get-text-property (point) 'org-marker))))
8902 (when m
8903 (org-with-point-at m
8904 (setq agenda-link
8905 (if (org-called-interactively-p 'any)
8906 (call-interactively 'org-store-link)
8907 (org-store-link nil)))))))
8909 ((eq major-mode 'calendar-mode)
8910 (let ((cd (calendar-cursor-to-date)))
8911 (setq link
8912 (format-time-string
8913 (car org-time-stamp-formats)
8914 (apply 'encode-time
8915 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8916 nil nil nil))))
8917 (org-store-link-props :type "calendar" :date cd)))
8919 ((eq major-mode 'help-mode)
8920 (setq link (concat "help:" (save-excursion
8921 (goto-char (point-min))
8922 (looking-at "^[^ ]+")
8923 (match-string 0))))
8924 (org-store-link-props :type "help"))
8926 ((eq major-mode 'w3-mode)
8927 (setq cpltxt (if (and (buffer-name)
8928 (not (string-match "Untitled" (buffer-name))))
8929 (buffer-name)
8930 (url-view-url t))
8931 link (url-view-url t))
8932 (org-store-link-props :type "w3" :url (url-view-url t)))
8934 ((eq major-mode 'w3m-mode)
8935 (setq cpltxt (or w3m-current-title w3m-current-url)
8936 link w3m-current-url)
8937 (org-store-link-props :type "w3m" :url (url-view-url t)))
8939 ((setq search (run-hook-with-args-until-success
8940 'org-create-file-search-functions))
8941 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8942 "::" search))
8943 (setq cpltxt (or description link)))
8945 ((eq major-mode 'image-mode)
8946 (setq cpltxt (concat "file:"
8947 (abbreviate-file-name buffer-file-name))
8948 link cpltxt)
8949 (org-store-link-props :type "image" :file buffer-file-name))
8951 ((eq major-mode 'dired-mode)
8952 ;; link to the file in the current line
8953 (let ((file (dired-get-filename nil t)))
8954 (setq file (if file
8955 (abbreviate-file-name
8956 (expand-file-name (dired-get-filename nil t)))
8957 ;; otherwise, no file so use current directory.
8958 default-directory))
8959 (setq cpltxt (concat "file:" file)
8960 link cpltxt)))
8962 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8963 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8964 (cond
8965 ((org-in-regexp "<<\\(.*?\\)>>")
8966 (setq cpltxt
8967 (concat "file:"
8968 (abbreviate-file-name
8969 (buffer-file-name (buffer-base-buffer)))
8970 "::" (match-string 1))
8971 link cpltxt))
8972 ((and (featurep 'org-id)
8973 (or (eq org-link-to-org-use-id t)
8974 (and (org-called-interactively-p 'any)
8975 (or (eq org-link-to-org-use-id 'create-if-interactive)
8976 (and (eq org-link-to-org-use-id
8977 'create-if-interactive-and-no-custom-id)
8978 (not custom-id))))
8979 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8980 ;; We can make a link using the ID.
8981 (setq link (condition-case nil
8982 (prog1 (org-id-store-link)
8983 (setq desc (plist-get org-store-link-plist :description)))
8984 (error
8985 ;; probably before first headline, link to file only
8986 (concat "file:"
8987 (abbreviate-file-name
8988 (buffer-file-name (buffer-base-buffer))))))))
8990 ;; Just link to current headline
8991 (setq cpltxt (concat "file:"
8992 (abbreviate-file-name
8993 (buffer-file-name (buffer-base-buffer)))))
8994 ;; Add a context search string
8995 (when (org-xor org-context-in-file-links arg)
8996 (setq txt (cond
8997 ((org-at-heading-p) nil)
8998 ((org-region-active-p)
8999 (buffer-substring (region-beginning) (region-end)))))
9000 (when (or (null txt) (string-match "\\S-" txt))
9001 (setq cpltxt
9002 (concat cpltxt "::"
9003 (condition-case nil
9004 (org-make-org-heading-search-string txt)
9005 (error "")))
9006 desc (or (nth 4 (ignore-errors
9007 (org-heading-components))) "NONE"))))
9008 (if (string-match "::\\'" cpltxt)
9009 (setq cpltxt (substring cpltxt 0 -2)))
9010 (setq link cpltxt))))
9012 ((buffer-file-name (buffer-base-buffer))
9013 ;; Just link to this file here.
9014 (setq cpltxt (concat "file:"
9015 (abbreviate-file-name
9016 (buffer-file-name (buffer-base-buffer)))))
9017 ;; Add a context string
9018 (when (org-xor org-context-in-file-links arg)
9019 (setq txt (if (org-region-active-p)
9020 (buffer-substring (region-beginning) (region-end))
9021 (buffer-substring (point-at-bol) (point-at-eol))))
9022 ;; Only use search option if there is some text.
9023 (when (string-match "\\S-" txt)
9024 (setq cpltxt
9025 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9026 desc "NONE")))
9027 (setq link cpltxt))
9029 ((org-called-interactively-p 'interactive)
9030 (error "Cannot link to a buffer which is not visiting a file"))
9032 (t (setq link nil)))
9034 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9035 (setq link (or link cpltxt)
9036 desc (or desc cpltxt))
9037 (if (equal desc "NONE") (setq desc nil))
9039 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9040 (progn
9041 (setq org-stored-links
9042 (cons (list link desc) org-stored-links))
9043 (message "Stored: %s" (or desc link))
9044 (when custom-id
9045 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9046 "::#" custom-id))
9047 (setq org-stored-links
9048 (cons (list link desc) org-stored-links))))
9049 (or agenda-link (and link (org-make-link-string link desc)))))))
9051 (defun org-store-link-props (&rest plist)
9052 "Store link properties, extract names and addresses."
9053 (let (x adr)
9054 (when (setq x (plist-get plist :from))
9055 (setq adr (mail-extract-address-components x))
9056 (setq plist (plist-put plist :fromname (car adr)))
9057 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9058 (when (setq x (plist-get plist :to))
9059 (setq adr (mail-extract-address-components x))
9060 (setq plist (plist-put plist :toname (car adr)))
9061 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9062 (let ((from (plist-get plist :from))
9063 (to (plist-get plist :to)))
9064 (when (and from to org-from-is-user-regexp)
9065 (setq plist
9066 (plist-put plist :fromto
9067 (if (string-match org-from-is-user-regexp from)
9068 (concat "to %t")
9069 (concat "from %f"))))))
9070 (setq org-store-link-plist plist))
9072 (defun org-add-link-props (&rest plist)
9073 "Add these properties to the link property list."
9074 (let (key value)
9075 (while plist
9076 (setq key (pop plist) value (pop plist))
9077 (setq org-store-link-plist
9078 (plist-put org-store-link-plist key value)))))
9080 (defun org-email-link-description (&optional fmt)
9081 "Return the description part of an email link.
9082 This takes information from `org-store-link-plist' and formats it
9083 according to FMT (default from `org-email-link-description-format')."
9084 (setq fmt (or fmt org-email-link-description-format))
9085 (let* ((p org-store-link-plist)
9086 (to (plist-get p :toaddress))
9087 (from (plist-get p :fromaddress))
9088 (table
9089 (list
9090 (cons "%c" (plist-get p :fromto))
9091 (cons "%F" (plist-get p :from))
9092 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9093 (cons "%T" (plist-get p :to))
9094 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9095 (cons "%s" (plist-get p :subject))
9096 (cons "%d" (plist-get p :date))
9097 (cons "%m" (plist-get p :message-id)))))
9098 (when (string-match "%c" fmt)
9099 ;; Check if the user wrote this message
9100 (if (and org-from-is-user-regexp from to
9101 (save-match-data (string-match org-from-is-user-regexp from)))
9102 (setq fmt (replace-match "to %t" t t fmt))
9103 (setq fmt (replace-match "from %f" t t fmt))))
9104 (org-replace-escapes fmt table)))
9106 (defun org-make-org-heading-search-string (&optional string heading)
9107 "Make search string for STRING or current headline."
9108 (interactive)
9109 (let ((s (or string (org-get-heading)))
9110 (lines org-context-in-file-links))
9111 (unless (and string (not heading))
9112 ;; We are using a headline, clean up garbage in there.
9113 (if (string-match org-todo-regexp s)
9114 (setq s (replace-match "" t t s)))
9115 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9116 (setq s (replace-match "" t t s)))
9117 (setq s (org-trim s))
9118 (if (string-match (concat "^\\(" org-quote-string "\\|"
9119 org-comment-string "\\)") s)
9120 (setq s (replace-match "" t t s)))
9121 (while (string-match org-ts-regexp s)
9122 (setq s (replace-match "" t t s))))
9123 (or string (setq s (concat "*" s))) ; Add * for headlines
9124 (when (and string (integerp lines) (> lines 0))
9125 (let ((slines (org-split-string s "\n")))
9126 (when (< lines (length slines))
9127 (setq s (mapconcat
9128 'identity
9129 (reverse (nthcdr (- (length slines) lines)
9130 (reverse slines))) "\n")))))
9131 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9133 (defun org-make-link-string (link &optional description)
9134 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9135 (unless (string-match "\\S-" link)
9136 (error "Empty link"))
9137 (when (and description
9138 (stringp description)
9139 (not (string-match "\\S-" description)))
9140 (setq description nil))
9141 (when (stringp description)
9142 ;; Remove brackets from the description, they are fatal.
9143 (while (string-match "\\[" description)
9144 (setq description (replace-match "{" t t description)))
9145 (while (string-match "\\]" description)
9146 (setq description (replace-match "}" t t description))))
9147 (when (equal link description)
9148 ;; No description needed, it is identical
9149 (setq description nil))
9150 (when (and (not description)
9151 (not (string-match (org-image-file-name-regexp) link))
9152 (not (equal link (org-link-escape link))))
9153 (setq description (org-extract-attributes link)))
9154 (setq link
9155 (cond ((string-match (org-image-file-name-regexp) link) link)
9156 ((string-match org-link-types-re link)
9157 (concat (match-string 1 link)
9158 (org-link-escape (substring link (match-end 1)))))
9159 (t (org-link-escape link))))
9160 (concat "[[" link "]"
9161 (if description (concat "[" description "]") "")
9162 "]"))
9164 (defconst org-link-escape-chars
9165 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9166 "List of characters that should be escaped in link.
9167 This is the list that is used for internal purposes.")
9169 (defconst org-link-escape-chars-browser
9170 '(?\ )
9171 "List of escapes for characters that are problematic in links.
9172 This is the list that is used before handing over to the browser.")
9174 (defun org-link-escape (text &optional table merge)
9175 "Return percent escaped representation of TEXT.
9176 TEXT is a string with the text to escape.
9177 Optional argument TABLE is a list with characters that should be
9178 escaped. When nil, `org-link-escape-chars' is used.
9179 If optional argument MERGE is set, merge TABLE into
9180 `org-link-escape-chars'."
9181 (cond
9182 ((and table merge)
9183 (mapc (lambda (defchr)
9184 (unless (member defchr table)
9185 (setq table (cons defchr table)))) org-link-escape-chars))
9186 ((null table)
9187 (setq table org-link-escape-chars)))
9188 (mapconcat
9189 (lambda (char)
9190 (if (or (member char table)
9191 (and (or (< char 32) (= char 37) (> char 126))
9192 org-url-hexify-p))
9193 (mapconcat (lambda (sequence-element)
9194 (format "%%%.2X" sequence-element))
9195 (or (encode-coding-char char 'utf-8)
9196 (error "Unable to percent escape character: %s"
9197 (char-to-string char))) "")
9198 (char-to-string char))) text ""))
9200 (defun org-link-unescape (str)
9201 "Unhex hexified Unicode strings as returned from the JavaScript function
9202 encodeURIComponent. E.g. `%C3%B6' is the german Umlaut `ö'."
9203 (unless (and (null str) (string= "" str))
9204 (let ((pos 0) (case-fold-search t) unhexed)
9205 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9206 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9207 (setq str (replace-match unhexed t t str))
9208 (setq pos (+ pos (length unhexed))))))
9209 str)
9211 (defun org-link-unescape-compound (hex)
9212 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German Umlaut `ö'.
9213 Note: this function also decodes single byte encodings like
9214 `%E1' (\"á\") if not followed by another `%[A-F0-9]{2}' group."
9215 (save-match-data
9216 (let* ((bytes (cdr (split-string hex "%")))
9217 (ret "")
9218 (eat 0)
9219 (sum 0))
9220 (while bytes
9221 (let* ((val (string-to-number (pop bytes) 16))
9222 (shift-xor
9223 (if (= 0 eat)
9224 (cond
9225 ((>= val 252) (cons 6 252))
9226 ((>= val 248) (cons 5 248))
9227 ((>= val 240) (cons 4 240))
9228 ((>= val 224) (cons 3 224))
9229 ((>= val 192) (cons 2 192))
9230 (t (cons 0 0)))
9231 (cons 6 128))))
9232 (if (>= val 192) (setq eat (car shift-xor)))
9233 (setq val (logxor val (cdr shift-xor)))
9234 (setq sum (+ (lsh sum (car shift-xor)) val))
9235 (if (> eat 0) (setq eat (- eat 1)))
9236 (cond
9237 ((= 0 eat) ;multi byte
9238 (setq ret (concat ret (org-char-to-string sum)))
9239 (setq sum 0))
9240 ((not bytes) ; single byte(s)
9241 (setq ret (org-link-unescape-single-byte-sequence hex))))
9242 )) ;; end (while bytes
9243 ret )))
9245 (defun org-link-unescape-single-byte-sequence (hex)
9246 "Unhexify hex-encoded single byte character sequences."
9247 (mapconcat (lambda (byte)
9248 (char-to-string (string-to-number byte 16)))
9249 (cdr (split-string hex "%")) ""))
9251 (defun org-xor (a b)
9252 "Exclusive or."
9253 (if a (not b) b))
9255 (defun org-fixup-message-id-for-http (s)
9256 "Replace special characters in a message id, so it can be used in an http query."
9257 (when (string-match "%" s)
9258 (setq s (mapconcat (lambda (c)
9259 (if (eq c ?%)
9260 "%25"
9261 (char-to-string c)))
9262 s "")))
9263 (while (string-match "<" s)
9264 (setq s (replace-match "%3C" t t s)))
9265 (while (string-match ">" s)
9266 (setq s (replace-match "%3E" t t s)))
9267 (while (string-match "@" s)
9268 (setq s (replace-match "%40" t t s)))
9271 (defun org-link-prettify (link)
9272 "Return a human-readable representation of LINK.
9273 The car of LINK must be a raw link the cdr of LINK must be either
9274 a link description or nil."
9275 (let ((desc (or (cadr link) "<no description>")))
9276 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9277 "<" (car link) ">")))
9279 ;;;###autoload
9280 (defun org-insert-link-global ()
9281 "Insert a link like Org-mode does.
9282 This command can be called in any mode to insert a link in Org-mode syntax."
9283 (interactive)
9284 (org-load-modules-maybe)
9285 (org-run-like-in-org-mode 'org-insert-link))
9287 (defun org-insert-all-links (&optional keep)
9288 "Insert all links in `org-stored-links'."
9289 (interactive "P")
9290 (let ((links (copy-sequence org-stored-links)) l)
9291 (while (setq l (if keep (pop links) (pop org-stored-links)))
9292 (insert "- ")
9293 (org-insert-link nil (car l) (cadr l))
9294 (insert "\n"))))
9296 (defun org-link-fontify-links-to-this-file ()
9297 "Fontify links to the current file in `org-stored-links'."
9298 (let ((f (buffer-file-name)) a b)
9299 (setq a (mapcar (lambda(l)
9300 (let ((ll (car l)))
9301 (when (and (string-match "^file:\\(.+\\)::" ll)
9302 (equal f (expand-file-name (match-string 1 ll))))
9303 ll)))
9304 org-stored-links))
9305 (when (featurep 'org-id)
9306 (setq b (mapcar (lambda(l)
9307 (let ((ll (car l)))
9308 (when (and (string-match "^id:\\(.+\\)$" ll)
9309 (equal f (expand-file-name
9310 (or (org-id-find-id-file
9311 (match-string 1 ll)) ""))))
9312 ll)))
9313 org-stored-links)))
9314 (mapcar (lambda(l)
9315 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9316 (delq nil (append a b)))))
9318 (defvar org-link-links-in-this-file nil)
9319 (defun org-insert-link (&optional complete-file link-location default-description)
9320 "Insert a link. At the prompt, enter the link.
9322 Completion can be used to insert any of the link protocol prefixes like
9323 http or ftp in use.
9325 The history can be used to select a link previously stored with
9326 `org-store-link'. When the empty string is entered (i.e. if you just
9327 press RET at the prompt), the link defaults to the most recently
9328 stored link. As SPC triggers completion in the minibuffer, you need to
9329 use M-SPC or C-q SPC to force the insertion of a space character.
9331 You will also be prompted for a description, and if one is given, it will
9332 be displayed in the buffer instead of the link.
9334 If there is already a link at point, this command will allow you to edit link
9335 and description parts.
9337 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9338 be selected using completion. The path to the file will be relative to the
9339 current directory if the file is in the current directory or a subdirectory.
9340 Otherwise, the link will be the absolute path as completed in the minibuffer
9341 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9342 option `org-link-file-path-type'.
9344 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9345 the current directory or below.
9347 With three \\[universal-argument] prefixes, negate the meaning of
9348 `org-keep-stored-link-after-insertion'.
9350 If `org-make-link-description-function' is non-nil, this function will be
9351 called with the link target, and the result will be the default
9352 link description.
9354 If the LINK-LOCATION parameter is non-nil, this value will be
9355 used as the link location instead of reading one interactively.
9357 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9358 be used as the default description."
9359 (interactive "P")
9360 (let* ((wcf (current-window-configuration))
9361 (region (if (org-region-active-p)
9362 (buffer-substring (region-beginning) (region-end))))
9363 (remove (and region (list (region-beginning) (region-end))))
9364 (desc region)
9365 tmphist ; byte-compile incorrectly complains about this
9366 (link link-location)
9367 (abbrevs org-link-abbrev-alist-local)
9368 entry file all-prefixes auto-desc)
9369 (cond
9370 (link-location) ; specified by arg, just use it.
9371 ((org-in-regexp org-bracket-link-regexp 1)
9372 ;; We do have a link at point, and we are going to edit it.
9373 (setq remove (list (match-beginning 0) (match-end 0)))
9374 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9375 (setq link (read-string "Link: "
9376 (org-link-unescape
9377 (org-match-string-no-properties 1)))))
9378 ((or (org-in-regexp org-angle-link-re)
9379 (org-in-regexp org-plain-link-re))
9380 ;; Convert to bracket link
9381 (setq remove (list (match-beginning 0) (match-end 0))
9382 link (read-string "Link: "
9383 (org-remove-angle-brackets (match-string 0)))))
9384 ((member complete-file '((4) (16)))
9385 ;; Completing read for file names.
9386 (setq link (org-file-complete-link complete-file)))
9388 ;; Read link, with completion for stored links.
9389 (org-link-fontify-links-to-this-file)
9390 (org-switch-to-buffer-other-window "*Org Links*")
9391 (with-current-buffer "*Org Links*"
9392 (erase-buffer)
9393 (insert "Insert a link.
9394 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9395 (when org-stored-links
9396 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9397 (insert (mapconcat 'org-link-prettify
9398 (reverse org-stored-links) "\n")))
9399 (goto-char (point-min)))
9400 (let ((cw (selected-window)))
9401 (select-window (get-buffer-window "*Org Links*" 'visible))
9402 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9403 (unless (pos-visible-in-window-p (point-max))
9404 (org-fit-window-to-buffer))
9405 (and (window-live-p cw) (select-window cw)))
9406 ;; Fake a link history, containing the stored links.
9407 (setq tmphist (append (mapcar 'car org-stored-links)
9408 org-insert-link-history))
9409 (setq all-prefixes (append (mapcar 'car abbrevs)
9410 (mapcar 'car org-link-abbrev-alist)
9411 org-link-types))
9412 (unwind-protect
9413 (progn
9414 (setq link
9415 (let ((org-completion-use-ido nil)
9416 (org-completion-use-iswitchb nil))
9417 (org-completing-read
9418 "Link: "
9419 (append
9420 (mapcar (lambda (x) (list (concat x ":")))
9421 all-prefixes)
9422 (mapcar 'car org-stored-links)
9423 (mapcar 'cadr org-stored-links))
9424 nil nil nil
9425 'tmphist
9426 (caar org-stored-links))))
9427 (if (not (string-match "\\S-" link))
9428 (error "No link selected"))
9429 (mapc (lambda(l)
9430 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9431 org-stored-links)
9432 (if (or (member link all-prefixes)
9433 (and (equal ":" (substring link -1))
9434 (member (substring link 0 -1) all-prefixes)
9435 (setq link (substring link 0 -1))))
9436 (setq link (org-link-try-special-completion link))))
9437 (set-window-configuration wcf)
9438 (kill-buffer "*Org Links*"))
9439 (setq entry (assoc link org-stored-links))
9440 (or entry (push link org-insert-link-history))
9441 (setq desc (or desc (nth 1 entry)))))
9443 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9444 (not org-keep-stored-link-after-insertion))
9445 (setq org-stored-links (delq (assoc link org-stored-links)
9446 org-stored-links)))
9448 (if (string-match org-plain-link-re link)
9449 ;; URL-like link, normalize the use of angular brackets.
9450 (setq link (org-remove-angle-brackets link)))
9452 ;; Check if we are linking to the current file with a search option
9453 ;; If yes, simplify the link by using only the search option.
9454 (when (and buffer-file-name
9455 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9456 (let* ((path (match-string 1 link))
9457 (case-fold-search nil)
9458 (search (match-string 2 link)))
9459 (save-match-data
9460 (if (equal (file-truename buffer-file-name) (file-truename path))
9461 ;; We are linking to this same file, with a search option
9462 (setq link search)))))
9464 ;; Check if we can/should use a relative path. If yes, simplify the link
9465 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9466 (let* ((type (match-string 1 link))
9467 (path (match-string 2 link))
9468 (origpath path)
9469 (case-fold-search nil))
9470 (cond
9471 ((or (eq org-link-file-path-type 'absolute)
9472 (equal complete-file '(16)))
9473 (setq path (abbreviate-file-name (expand-file-name path))))
9474 ((eq org-link-file-path-type 'noabbrev)
9475 (setq path (expand-file-name path)))
9476 ((eq org-link-file-path-type 'relative)
9477 (setq path (file-relative-name path)))
9479 (save-match-data
9480 (if (string-match (concat "^" (regexp-quote
9481 (expand-file-name
9482 (file-name-as-directory
9483 default-directory))))
9484 (expand-file-name path))
9485 ;; We are linking a file with relative path name.
9486 (setq path (substring (expand-file-name path)
9487 (match-end 0)))
9488 (setq path (abbreviate-file-name (expand-file-name path)))))))
9489 (setq link (concat type path))
9490 (if (equal desc origpath)
9491 (setq desc path))))
9493 (if org-make-link-description-function
9494 (setq desc (funcall org-make-link-description-function link desc))
9495 (if default-description (setq desc default-description)
9496 (setq desc (or (and auto-desc desc)
9497 (read-string "Description: " desc)))))
9499 (unless (string-match "\\S-" desc) (setq desc nil))
9500 (if remove (apply 'delete-region remove))
9501 (insert (org-make-link-string link desc))))
9503 (defun org-link-try-special-completion (type)
9504 "If there is completion support for link type TYPE, offer it."
9505 (let ((fun (intern (concat "org-" type "-complete-link"))))
9506 (if (functionp fun)
9507 (funcall fun)
9508 (read-string "Link (no completion support): " (concat type ":")))))
9510 (defun org-file-complete-link (&optional arg)
9511 "Create a file link using completion."
9512 (let (file link)
9513 (setq file (read-file-name "File: "))
9514 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9515 (pwd1 (file-name-as-directory (abbreviate-file-name
9516 (expand-file-name ".")))))
9517 (cond
9518 ((equal arg '(16))
9519 (setq link (concat
9520 "file:"
9521 (abbreviate-file-name (expand-file-name file)))))
9522 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9523 (setq link (concat "file:" (match-string 1 file))))
9524 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9525 (expand-file-name file))
9526 (setq link (concat
9527 "file:" (match-string 1 (expand-file-name file)))))
9528 (t (setq link (concat "file:" file)))))
9529 link))
9531 (defun org-completing-read (&rest args)
9532 "Completing-read with SPACE being a normal character."
9533 (let ((enable-recursive-minibuffers t)
9534 (minibuffer-local-completion-map
9535 (copy-keymap minibuffer-local-completion-map)))
9536 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9537 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9538 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9539 (apply 'org-icompleting-read args)))
9541 (defun org-completing-read-no-i (&rest args)
9542 (let (org-completion-use-ido org-completion-use-iswitchb)
9543 (apply 'org-completing-read args)))
9545 (defun org-iswitchb-completing-read (prompt choices &rest args)
9546 "Use iswitch as a completing-read replacement to choose from choices.
9547 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9548 from."
9549 (let* ((iswitchb-use-virtual-buffers nil)
9550 (iswitchb-make-buflist-hook
9551 (lambda ()
9552 (setq iswitchb-temp-buflist choices))))
9553 (iswitchb-read-buffer prompt)))
9555 (defun org-icompleting-read (&rest args)
9556 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9557 (org-without-partial-completion
9558 (if (and org-completion-use-ido
9559 (fboundp 'ido-completing-read)
9560 (boundp 'ido-mode) ido-mode
9561 (listp (second args)))
9562 (let ((ido-enter-matching-directory nil))
9563 (apply 'ido-completing-read (concat (car args))
9564 (if (consp (car (nth 1 args)))
9565 (mapcar 'car (nth 1 args))
9566 (nth 1 args))
9567 (cddr args)))
9568 (if (and org-completion-use-iswitchb
9569 (boundp 'iswitchb-mode) iswitchb-mode
9570 (listp (second args)))
9571 (apply 'org-iswitchb-completing-read (concat (car args))
9572 (if (consp (car (nth 1 args)))
9573 (mapcar 'car (nth 1 args))
9574 (nth 1 args))
9575 (cddr args))
9576 (apply 'completing-read args)))))
9578 (defun org-extract-attributes (s)
9579 "Extract the attributes cookie from a string and set as text property."
9580 (let (a attr (start 0) key value)
9581 (save-match-data
9582 (when (string-match "{{\\([^}]+\\)}}$" s)
9583 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9584 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9585 (setq key (match-string 1 a) value (match-string 2 a)
9586 start (match-end 0)
9587 attr (plist-put attr (intern key) value))))
9588 (org-add-props s nil 'org-attr attr))
9591 (defun org-extract-attributes-from-string (tag)
9592 (let (key value attr)
9593 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9594 (setq key (match-string 1 tag) value (match-string 2 tag)
9595 tag (replace-match "" t t tag)
9596 attr (plist-put attr (intern key) value)))
9597 (cons tag attr)))
9599 (defun org-attributes-to-string (plist)
9600 "Format a property list into an HTML attribute list."
9601 (let ((s "") key value)
9602 (while plist
9603 (setq key (pop plist) value (pop plist))
9604 (and value
9605 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9608 ;;; Opening/following a link
9610 (defvar org-link-search-failed nil)
9612 (defvar org-open-link-functions nil
9613 "Hook for functions finding a plain text link.
9614 These functions must take a single argument, the link content.
9615 They will be called for links that look like [[link text][description]]
9616 when LINK TEXT does not have a protocol like \"http:\" and does not look
9617 like a filename (e.g. \"./blue.png\").
9619 These functions will be called *before* Org attempts to resolve the
9620 link by doing text searches in the current buffer - so if you want a
9621 link \"[[target]]\" to still find \"<<target>>\", your function should
9622 handle this as a special case.
9624 When the function does handle the link, it must return a non-nil value.
9625 If it decides that it is not responsible for this link, it must return
9626 nil to indicate that that Org-mode can continue with other options
9627 like exact and fuzzy text search.")
9629 (defun org-next-link ()
9630 "Move forward to the next link.
9631 If the link is in hidden text, expose it."
9632 (interactive)
9633 (when (and org-link-search-failed (eq this-command last-command))
9634 (goto-char (point-min))
9635 (message "Link search wrapped back to beginning of buffer"))
9636 (setq org-link-search-failed nil)
9637 (let* ((pos (point))
9638 (ct (org-context))
9639 (a (assoc :link ct)))
9640 (if a (goto-char (nth 2 a)))
9641 (if (re-search-forward org-any-link-re nil t)
9642 (progn
9643 (goto-char (match-beginning 0))
9644 (if (outline-invisible-p) (org-show-context)))
9645 (goto-char pos)
9646 (setq org-link-search-failed t)
9647 (error "No further link found"))))
9649 (defun org-previous-link ()
9650 "Move backward to the previous link.
9651 If the link is in hidden text, expose it."
9652 (interactive)
9653 (when (and org-link-search-failed (eq this-command last-command))
9654 (goto-char (point-max))
9655 (message "Link search wrapped back to end of buffer"))
9656 (setq org-link-search-failed nil)
9657 (let* ((pos (point))
9658 (ct (org-context))
9659 (a (assoc :link ct)))
9660 (if a (goto-char (nth 1 a)))
9661 (if (re-search-backward org-any-link-re nil t)
9662 (progn
9663 (goto-char (match-beginning 0))
9664 (if (outline-invisible-p) (org-show-context)))
9665 (goto-char pos)
9666 (setq org-link-search-failed t)
9667 (error "No further link found"))))
9669 (defun org-translate-link (s)
9670 "Translate a link string if a translation function has been defined."
9671 (if (and org-link-translation-function
9672 (fboundp org-link-translation-function)
9673 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9674 (progn
9675 (setq s (funcall org-link-translation-function
9676 (match-string 1 s) (match-string 2 s)))
9677 (concat (car s) ":" (cdr s)))
9680 (defun org-translate-link-from-planner (type path)
9681 "Translate a link from Emacs Planner syntax so that Org can follow it.
9682 This is still an experimental function, your mileage may vary."
9683 (cond
9684 ((member type '("http" "https" "news" "ftp"))
9685 ;; standard Internet links are the same.
9686 nil)
9687 ((and (equal type "irc") (string-match "^//" path))
9688 ;; Planner has two / at the beginning of an irc link, we have 1.
9689 ;; We should have zero, actually....
9690 (setq path (substring path 1)))
9691 ((and (equal type "lisp") (string-match "^/" path))
9692 ;; Planner has a slash, we do not.
9693 (setq type "elisp" path (substring path 1)))
9694 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9695 ;; A typical message link. Planner has the id after the final slash,
9696 ;; we separate it with a hash mark
9697 (setq path (concat (match-string 1 path) "#"
9698 (org-remove-angle-brackets (match-string 2 path)))))
9700 (cons type path))
9702 (defun org-find-file-at-mouse (ev)
9703 "Open file link or URL at mouse."
9704 (interactive "e")
9705 (mouse-set-point ev)
9706 (org-open-at-point 'in-emacs))
9708 (defun org-open-at-mouse (ev)
9709 "Open file link or URL at mouse.
9710 See the docstring of `org-open-file' for details."
9711 (interactive "e")
9712 (mouse-set-point ev)
9713 (if (eq major-mode 'org-agenda-mode)
9714 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9715 (org-open-at-point))
9717 (defvar org-window-config-before-follow-link nil
9718 "The window configuration before following a link.
9719 This is saved in case the need arises to restore it.")
9721 (defvar org-open-link-marker (make-marker)
9722 "Marker pointing to the location where `org-open-at-point; was called.")
9724 ;;;###autoload
9725 (defun org-open-at-point-global ()
9726 "Follow a link like Org-mode does.
9727 This command can be called in any mode to follow a link that has
9728 Org-mode syntax."
9729 (interactive)
9730 (org-run-like-in-org-mode 'org-open-at-point))
9732 ;;;###autoload
9733 (defun org-open-link-from-string (s &optional arg reference-buffer)
9734 "Open a link in the string S, as if it was in Org-mode."
9735 (interactive "sLink: \nP")
9736 (let ((reference-buffer (or reference-buffer (current-buffer))))
9737 (with-temp-buffer
9738 (let ((org-inhibit-startup (not reference-buffer)))
9739 (org-mode)
9740 (insert s)
9741 (goto-char (point-min))
9742 (when reference-buffer
9743 (setq org-link-abbrev-alist-local
9744 (with-current-buffer reference-buffer
9745 org-link-abbrev-alist-local)))
9746 (org-open-at-point arg reference-buffer)))))
9748 (defvar org-open-at-point-functions nil
9749 "Hook that is run when following a link at point.
9751 Functions in this hook must return t if they identify and follow
9752 a link at point. If they don't find anything interesting at point,
9753 they must return nil.")
9755 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9756 (defun org-open-at-point (&optional arg reference-buffer)
9757 "Open link at or after point.
9758 If there is no link at point, this function will search forward up to
9759 the end of the current line.
9760 Normally, files will be opened by an appropriate application. If the
9761 optional prefix argument ARG is non-nil, Emacs will visit the file.
9762 With a double prefix argument, try to open outside of Emacs, in the
9763 application the system uses for this file type."
9764 (interactive "P")
9765 ;; if in a code block, then open the block's results
9766 (unless (call-interactively #'org-babel-open-src-block-result)
9767 (org-load-modules-maybe)
9768 (move-marker org-open-link-marker (point))
9769 (setq org-window-config-before-follow-link (current-window-configuration))
9770 (org-remove-occur-highlights nil nil t)
9771 (cond
9772 ((and (org-at-heading-p)
9773 (not (org-at-timestamp-p t))
9774 (not (org-in-regexp
9775 (concat org-plain-link-re "\\|"
9776 org-bracket-link-regexp "\\|"
9777 org-angle-link-re "\\|"
9778 "[ \t]:[^ \t\n]+:[ \t]*$")))
9779 (not (get-text-property (point) 'org-linked-text)))
9780 (or (org-offer-links-in-entry arg)
9781 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9782 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9783 ((and (org-at-timestamp-p t)
9784 (not (org-in-regexp org-bracket-link-regexp)))
9785 (org-follow-timestamp-link))
9786 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9787 (not (org-in-regexp org-bracket-link-regexp)))
9788 (org-footnote-action))
9790 (let (type path link line search (pos (point)))
9791 (catch 'match
9792 (save-excursion
9793 (skip-chars-forward "^]\n\r")
9794 (when (org-in-regexp org-bracket-link-regexp 1)
9795 (setq link (org-extract-attributes
9796 (org-link-unescape (org-match-string-no-properties 1))))
9797 (while (string-match " *\n *" link)
9798 (setq link (replace-match " " t t link)))
9799 (setq link (org-link-expand-abbrev link))
9800 (cond
9801 ((or (file-name-absolute-p link)
9802 (string-match "^\\.\\.?/" link))
9803 (setq type "file" path link))
9804 ((string-match org-link-re-with-space3 link)
9805 (setq type (match-string 1 link) path (match-string 2 link)))
9806 ((string-match "^help:+\\(.+\\)" link)
9807 (setq type "help" path (match-string 1 link)))
9808 (t (setq type "thisfile" path link)))
9809 (throw 'match t)))
9811 (when (get-text-property (point) 'org-linked-text)
9812 (setq type "thisfile"
9813 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9814 (1+ (point)) (point))
9815 path (buffer-substring
9816 (or (previous-single-property-change pos 'org-linked-text)
9817 (point-min))
9818 (or (next-single-property-change pos 'org-linked-text)
9819 (point-max))))
9820 (throw 'match t))
9822 (save-excursion
9823 (when (or (org-in-regexp org-angle-link-re)
9824 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9825 (save-match-data (not (looking-back "\\[\\[")))))
9826 (setq type (match-string 1)
9827 path (org-link-unescape (match-string 2)))
9828 (throw 'match t)))
9829 (save-excursion
9830 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9831 (setq type "tags"
9832 path (match-string 1))
9833 (while (string-match ":" path)
9834 (setq path (replace-match "+" t t path)))
9835 (throw 'match t)))
9836 (when (org-in-regexp "<\\([^><\n]+\\)>")
9837 (setq type "tree-match"
9838 path (match-string 1))
9839 (throw 'match t)))
9840 (unless path
9841 (error "No link found"))
9843 ;; switch back to reference buffer
9844 ;; needed when if called in a temporary buffer through
9845 ;; org-open-link-from-string
9846 (with-current-buffer (or reference-buffer (current-buffer))
9848 ;; Remove any trailing spaces in path
9849 (if (string-match " +\\'" path)
9850 (setq path (replace-match "" t t path)))
9851 (if (and org-link-translation-function
9852 (fboundp org-link-translation-function))
9853 ;; Check if we need to translate the link
9854 (let ((tmp (funcall org-link-translation-function type path)))
9855 (setq type (car tmp) path (cdr tmp))))
9857 (cond
9859 ((assoc type org-link-protocols)
9860 (funcall (nth 1 (assoc type org-link-protocols)) path))
9862 ((equal type "help")
9863 (let ((f-or-v (intern path)))
9864 (cond ((fboundp f-or-v)
9865 (describe-function f-or-v))
9866 ((boundp f-or-v)
9867 (describe-variable f-or-v))
9868 (t (error "Not a known function or variable")))))
9870 ((equal type "mailto")
9871 (let ((cmd (car org-link-mailto-program))
9872 (args (cdr org-link-mailto-program)) args1
9873 (address path) (subject "") a)
9874 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9875 (setq address (match-string 1 path)
9876 subject (org-link-escape (match-string 2 path))))
9877 (while args
9878 (cond
9879 ((not (stringp (car args))) (push (pop args) args1))
9880 (t (setq a (pop args))
9881 (if (string-match "%a" a)
9882 (setq a (replace-match address t t a)))
9883 (if (string-match "%s" a)
9884 (setq a (replace-match subject t t a)))
9885 (push a args1))))
9886 (apply cmd (nreverse args1))))
9888 ((member type '("http" "https" "ftp" "news"))
9889 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9890 (org-link-escape
9891 path org-link-escape-chars-browser)
9892 path))))
9894 ((string= type "doi")
9895 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9896 (org-link-escape
9897 path org-link-escape-chars-browser)
9898 path))))
9900 ((member type '("message"))
9901 (browse-url (concat type ":" path)))
9903 ((string= type "tags")
9904 (org-tags-view arg path))
9906 ((string= type "tree-match")
9907 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9909 ((string= type "file")
9910 (if (string-match "::\\([0-9]+\\)\\'" path)
9911 (setq line (string-to-number (match-string 1 path))
9912 path (substring path 0 (match-beginning 0)))
9913 (if (string-match "::\\(.+\\)\\'" path)
9914 (setq search (match-string 1 path)
9915 path (substring path 0 (match-beginning 0)))))
9916 (if (string-match "[*?{]" (file-name-nondirectory path))
9917 (dired path)
9918 (org-open-file path arg line search)))
9920 ((string= type "shell")
9921 (let ((buf (generate-new-buffer "*Org Shell Output"))
9922 (cmd path))
9923 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9924 (string-match org-confirm-shell-link-not-regexp cmd))
9925 (not org-confirm-shell-link-function)
9926 (funcall org-confirm-shell-link-function
9927 (format "Execute \"%s\" in shell? "
9928 (org-add-props cmd nil
9929 'face 'org-warning))))
9930 (progn
9931 (message "Executing %s" cmd)
9932 (shell-command cmd buf)
9933 (if (featurep 'midnight)
9934 (setq clean-buffer-list-kill-buffer-names
9935 (cons buf clean-buffer-list-kill-buffer-names))))
9936 (error "Abort"))))
9938 ((string= type "elisp")
9939 (let ((cmd path))
9940 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9941 (string-match org-confirm-elisp-link-not-regexp cmd))
9942 (not org-confirm-elisp-link-function)
9943 (funcall org-confirm-elisp-link-function
9944 (format "Execute \"%s\" as elisp? "
9945 (org-add-props cmd nil
9946 'face 'org-warning))))
9947 (message "%s => %s" cmd
9948 (if (equal (string-to-char cmd) ?\()
9949 (eval (read cmd))
9950 (call-interactively (read cmd))))
9951 (error "Abort"))))
9953 ((and (string= type "thisfile")
9954 (run-hook-with-args-until-success
9955 'org-open-link-functions path)))
9957 ((string= type "thisfile")
9958 (if arg
9959 (switch-to-buffer-other-window
9960 (org-get-buffer-for-internal-link (current-buffer)))
9961 (org-mark-ring-push))
9962 (let ((cmd `(org-link-search
9963 ,path
9964 ,(cond ((equal arg '(4)) ''occur)
9965 ((equal arg '(16)) ''org-occur))
9966 ,pos)))
9967 (condition-case nil (let ((org-link-search-inhibit-query t))
9968 (eval cmd))
9969 (error (progn (widen) (eval cmd))))))
9971 (t (browse-url-at-point)))))))
9972 (move-marker org-open-link-marker nil)
9973 (run-hook-with-args 'org-follow-link-hook)))
9975 (defun org-offer-links-in-entry (&optional nth zero)
9976 "Offer links in the current entry and follow the selected link.
9977 If there is only one link, follow it immediately as well.
9978 If NTH is an integer, immediately pick the NTH link found.
9979 If ZERO is a string, check also this string for a link, and if
9980 there is one, offer it as link number zero."
9981 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
9982 "\\(" org-angle-link-re "\\)\\|"
9983 "\\(" org-plain-link-re "\\)"))
9984 (cnt ?0)
9985 (in-emacs (if (integerp nth) nil nth))
9986 have-zero end links link c)
9987 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
9988 (push (match-string 0 zero) links)
9989 (setq cnt (1- cnt) have-zero t))
9990 (save-excursion
9991 (org-back-to-heading t)
9992 (setq end (save-excursion (outline-next-heading) (point)))
9993 (while (re-search-forward re end t)
9994 (push (match-string 0) links))
9995 (setq links (org-uniquify (reverse links))))
9997 (cond
9998 ((null links)
9999 (message "No links"))
10000 ((equal (length links) 1)
10001 (setq link (list (car links))))
10002 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10003 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10004 (t ; we have to select a link
10005 (save-excursion
10006 (save-window-excursion
10007 (delete-other-windows)
10008 (with-output-to-temp-buffer "*Select Link*"
10009 (mapc (lambda (l)
10010 (if (not (string-match org-bracket-link-regexp l))
10011 (princ (format "[%c] %s\n" (incf cnt)
10012 (org-remove-angle-brackets l)))
10013 (if (match-end 3)
10014 (princ (format "[%c] %s (%s)\n" (incf cnt)
10015 (match-string 3 l) (match-string 1 l)))
10016 (princ (format "[%c] %s\n" (incf cnt)
10017 (match-string 1 l))))))
10018 links))
10019 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10020 (message "Select link to open, RET to open all:")
10021 (setq c (read-char-exclusive))
10022 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10023 (when (equal c ?q) (error "Abort"))
10024 (if (equal c ?\C-m)
10025 (setq link links)
10026 (setq nth (- c ?0))
10027 (if have-zero (setq nth (1+ nth)))
10028 (unless (and (integerp nth) (>= (length links) nth))
10029 (error "Invalid link selection"))
10030 (setq link (list (nth (1- nth) links))))))
10031 (if link
10032 (let ((buf (current-buffer)))
10033 (dolist (l link)
10034 (org-open-link-from-string l in-emacs buf))
10036 nil)))
10038 ;; Add special file links that specify the way of opening
10040 (org-add-link-type "file+sys" 'org-open-file-with-system)
10041 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10042 (defun org-open-file-with-system (path)
10043 "Open file at PATH using the system way of opening it."
10044 (org-open-file path 'system))
10045 (defun org-open-file-with-emacs (path)
10046 "Open file at PATH in Emacs."
10047 (org-open-file path 'emacs))
10048 (defun org-remove-file-link-modifiers ()
10049 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10050 (goto-char (point-min))
10051 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10052 (org-if-unprotected
10053 (replace-match "file:" t t))))
10054 (eval-after-load "org-exp"
10055 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10056 'org-remove-file-link-modifiers))
10058 ;;;; Time estimates
10060 (defun org-get-effort (&optional pom)
10061 "Get the effort estimate for the current entry."
10062 (org-entry-get pom org-effort-property))
10064 ;;; File search
10066 (defvar org-create-file-search-functions nil
10067 "List of functions to construct the right search string for a file link.
10068 These functions are called in turn with point at the location to
10069 which the link should point.
10071 A function in the hook should first test if it would like to
10072 handle this file type, for example by checking the `major-mode'
10073 or the file extension. If it decides not to handle this file, it
10074 should just return nil to give other functions a chance. If it
10075 does handle the file, it must return the search string to be used
10076 when following the link. The search string will be part of the
10077 file link, given after a double colon, and `org-open-at-point'
10078 will automatically search for it. If special measures must be
10079 taken to make the search successful, another function should be
10080 added to the companion hook `org-execute-file-search-functions',
10081 which see.
10083 A function in this hook may also use `setq' to set the variable
10084 `description' to provide a suggestion for the descriptive text to
10085 be used for this link when it gets inserted into an Org-mode
10086 buffer with \\[org-insert-link].")
10088 (defvar org-execute-file-search-functions nil
10089 "List of functions to execute a file search triggered by a link.
10091 Functions added to this hook must accept a single argument, the
10092 search string that was part of the file link, the part after the
10093 double colon. The function must first check if it would like to
10094 handle this search, for example by checking the `major-mode' or
10095 the file extension. If it decides not to handle this search, it
10096 should just return nil to give other functions a chance. If it
10097 does handle the search, it must return a non-nil value to keep
10098 other functions from trying.
10100 Each function can access the current prefix argument through the
10101 variable `current-prefix-argument'. Note that a single prefix is
10102 used to force opening a link in Emacs, so it may be good to only
10103 use a numeric or double prefix to guide the search function.
10105 In case this is needed, a function in this hook can also restore
10106 the window configuration before `org-open-at-point' was called using:
10108 (set-window-configuration org-window-config-before-follow-link)")
10110 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10111 (defun org-link-search (s &optional type avoid-pos stealth)
10112 "Search for a link search option.
10113 If S is surrounded by forward slashes, it is interpreted as a
10114 regular expression. In org-mode files, this will create an `org-occur'
10115 sparse tree. In ordinary files, `occur' will be used to list matches.
10116 If the current buffer is in `dired-mode', grep will be used to search
10117 in all files. If AVOID-POS is given, ignore matches near that position.
10119 When optional argument STEALTH is non-nil, do not modify
10120 visibility around point, thus ignoring
10121 `org-show-hierarchy-above', `org-show-following-heading' and
10122 `org-show-siblings' variables."
10123 (let ((case-fold-search t)
10124 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10125 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10126 (append '(("") (" ") ("\t") ("\n"))
10127 org-emphasis-alist)
10128 "\\|") "\\)"))
10129 (pos (point))
10130 (pre nil) (post nil)
10131 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10132 (cond
10133 ;; First check if there are any special search functions
10134 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10135 ;; Now try the builtin stuff
10136 ((and (equal (string-to-char s0) ?#)
10137 (> (length s0) 1)
10138 (save-excursion
10139 (goto-char (point-min))
10140 (and
10141 (re-search-forward
10142 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10143 (setq type 'dedicated
10144 pos (match-beginning 0))))
10145 ;; There is an exact target for this
10146 (goto-char pos)
10147 (org-back-to-heading t)))
10148 ((save-excursion
10149 (goto-char (point-min))
10150 (and
10151 (re-search-forward
10152 (concat "<<" (regexp-quote s0) ">>") nil t)
10153 (setq type 'dedicated
10154 pos (match-beginning 0))))
10155 ;; There is an exact target for this
10156 (goto-char pos))
10157 ((save-excursion
10158 (goto-char (point-min))
10159 (and
10160 (re-search-forward
10161 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10162 (setq type 'dedicated pos (match-beginning 0))))
10163 ;; Found an invisible target.
10164 (goto-char pos))
10165 ((save-excursion
10166 (goto-char (point-min))
10167 (and
10168 (re-search-forward
10169 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10170 (setq type 'dedicated pos (match-beginning 0))))
10171 ;; Found an element with a matching #+name affiliated keyword.
10172 (goto-char pos))
10173 ((and (string-match "^(\\(.*\\))$" s0)
10174 (save-excursion
10175 (goto-char (point-min))
10176 (and
10177 (re-search-forward
10178 (concat "[^[]" (regexp-quote
10179 (format org-coderef-label-format
10180 (match-string 1 s0))))
10181 nil t)
10182 (setq type 'dedicated
10183 pos (1+ (match-beginning 0))))))
10184 ;; There is a coderef target for this
10185 (goto-char pos))
10186 ((string-match "^/\\(.*\\)/$" s)
10187 ;; A regular expression
10188 (cond
10189 ((derived-mode-p 'org-mode)
10190 (org-occur (match-string 1 s)))
10191 ;;((eq major-mode 'dired-mode)
10192 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10193 (t (org-do-occur (match-string 1 s)))))
10194 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10195 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10196 (goto-char (point-min))
10197 (cond
10198 ((let (case-fold-search)
10199 (re-search-forward (format org-complex-heading-regexp-format
10200 (regexp-quote s))
10201 nil t))
10202 ;; OK, found a match
10203 (setq type 'dedicated)
10204 (goto-char (match-beginning 0)))
10205 ((and (not org-link-search-inhibit-query)
10206 (eq org-link-search-must-match-exact-headline 'query-to-create)
10207 (y-or-n-p "No match - create this as a new heading? "))
10208 (goto-char (point-max))
10209 (or (bolp) (newline))
10210 (insert "* " s "\n")
10211 (beginning-of-line 0))
10213 (goto-char pos)
10214 (error "No match"))))
10216 ;; A normal search string
10217 (when (equal (string-to-char s) ?*)
10218 ;; Anchor on headlines, post may include tags.
10219 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10220 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10221 s (substring s 1)))
10222 (remove-text-properties
10223 0 (length s)
10224 '(face nil mouse-face nil keymap nil fontified nil) s)
10225 ;; Make a series of regular expressions to find a match
10226 (setq words (org-split-string s "[ \n\r\t]+")
10228 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10229 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10230 "\\)" markers)
10231 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10232 re2a (concat "[ \t\r\n]" re2a_)
10233 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10234 re4 (concat "[^a-zA-Z_]" re4_)
10236 re1 (concat pre re2 post)
10237 re3 (concat pre (if pre re4_ re4) post)
10238 re5 (concat pre ".*" re4)
10239 re2 (concat pre re2)
10240 re2a (concat pre (if pre re2a_ re2a))
10241 re4 (concat pre (if pre re4_ re4))
10242 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10243 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10244 re5 "\\)"
10246 (cond
10247 ((eq type 'org-occur) (org-occur reall))
10248 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10249 (t (goto-char (point-min))
10250 (setq type 'fuzzy)
10251 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10252 (org-search-not-self 1 re1 nil t)
10253 (org-search-not-self 1 re2 nil t)
10254 (org-search-not-self 1 re2a nil t)
10255 (org-search-not-self 1 re3 nil t)
10256 (org-search-not-self 1 re4 nil t)
10257 (org-search-not-self 1 re5 nil t)
10259 (goto-char (match-beginning 1))
10260 (goto-char pos)
10261 (error "No match"))))))
10262 (and (derived-mode-p 'org-mode)
10263 (not stealth)
10264 (org-show-context 'link-search))
10265 type))
10267 (defun org-search-not-self (group &rest args)
10268 "Execute `re-search-forward', but only accept matches that do not
10269 enclose the position of `org-open-link-marker'."
10270 (let ((m org-open-link-marker))
10271 (catch 'exit
10272 (while (apply 're-search-forward args)
10273 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10274 (goto-char (match-end group))
10275 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10276 (> (match-beginning 0) (marker-position m))
10277 (< (match-end 0) (marker-position m)))
10278 (save-match-data
10279 (or (not (org-in-regexp
10280 org-bracket-link-analytic-regexp 1))
10281 (not (match-end 4)) ; no description
10282 (and (<= (match-beginning 4) (point))
10283 (>= (match-end 4) (point))))))
10284 (throw 'exit (point))))))))
10286 (defun org-get-buffer-for-internal-link (buffer)
10287 "Return a buffer to be used for displaying the link target of internal links."
10288 (cond
10289 ((not org-display-internal-link-with-indirect-buffer)
10290 buffer)
10291 ((string-match "(Clone)$" (buffer-name buffer))
10292 (message "Buffer is already a clone, not making another one")
10293 ;; we also do not modify visibility in this case
10294 buffer)
10295 (t ; make a new indirect buffer for displaying the link
10296 (let* ((bn (buffer-name buffer))
10297 (ibn (concat bn "(Clone)"))
10298 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10299 (with-current-buffer ib (org-overview))
10300 ib))))
10302 (defun org-do-occur (regexp &optional cleanup)
10303 "Call the Emacs command `occur'.
10304 If CLEANUP is non-nil, remove the printout of the regular expression
10305 in the *Occur* buffer. This is useful if the regex is long and not useful
10306 to read."
10307 (occur regexp)
10308 (when cleanup
10309 (let ((cwin (selected-window)) win beg end)
10310 (when (setq win (get-buffer-window "*Occur*"))
10311 (select-window win))
10312 (goto-char (point-min))
10313 (when (re-search-forward "match[a-z]+" nil t)
10314 (setq beg (match-end 0))
10315 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10316 (setq end (1- (match-beginning 0)))))
10317 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10318 (goto-char (point-min))
10319 (select-window cwin))))
10321 ;;; The mark ring for links jumps
10323 (defvar org-mark-ring nil
10324 "Mark ring for positions before jumps in Org-mode.")
10325 (defvar org-mark-ring-last-goto nil
10326 "Last position in the mark ring used to go back.")
10327 ;; Fill and close the ring
10328 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10329 (loop for i from 1 to org-mark-ring-length do
10330 (push (make-marker) org-mark-ring))
10331 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10332 org-mark-ring)
10334 (defun org-mark-ring-push (&optional pos buffer)
10335 "Put the current position or POS into the mark ring and rotate it."
10336 (interactive)
10337 (setq pos (or pos (point)))
10338 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10339 (move-marker (car org-mark-ring)
10340 (or pos (point))
10341 (or buffer (current-buffer)))
10342 (message "%s"
10343 (substitute-command-keys
10344 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10346 (defun org-mark-ring-goto (&optional n)
10347 "Jump to the previous position in the mark ring.
10348 With prefix arg N, jump back that many stored positions. When
10349 called several times in succession, walk through the entire ring.
10350 Org-mode commands jumping to a different position in the current file,
10351 or to another Org-mode file, automatically push the old position
10352 onto the ring."
10353 (interactive "p")
10354 (let (p m)
10355 (if (eq last-command this-command)
10356 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10357 (setq p org-mark-ring))
10358 (setq org-mark-ring-last-goto p)
10359 (setq m (car p))
10360 (org-pop-to-buffer-same-window (marker-buffer m))
10361 (goto-char m)
10362 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10364 (defun org-remove-angle-brackets (s)
10365 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10366 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10368 (defun org-add-angle-brackets (s)
10369 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10370 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10372 (defun org-remove-double-quotes (s)
10373 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10374 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10377 ;;; Following specific links
10379 (defun org-follow-timestamp-link ()
10380 (cond
10381 ((org-at-date-range-p t)
10382 (let ((org-agenda-start-on-weekday)
10383 (t1 (match-string 1))
10384 (t2 (match-string 2)))
10385 (setq t1 (time-to-days (org-time-string-to-time t1))
10386 t2 (time-to-days (org-time-string-to-time t2)))
10387 (org-agenda-list nil t1 (1+ (- t2 t1)))))
10388 ((org-at-timestamp-p t)
10389 (org-agenda-list nil (time-to-days (org-time-string-to-time
10390 (substring (match-string 1) 0 10)))
10392 (t (error "This should not happen"))))
10395 ;;; Following file links
10396 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10397 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10398 (declare-function mailcap-mime-info
10399 "mailcap" (string &optional request no-decode))
10400 (defvar org-wait nil)
10401 (defun org-open-file (path &optional in-emacs line search)
10402 "Open the file at PATH.
10403 First, this expands any special file name abbreviations. Then the
10404 configuration variable `org-file-apps' is checked if it contains an
10405 entry for this file type, and if yes, the corresponding command is launched.
10407 If no application is found, Emacs simply visits the file.
10409 With optional prefix argument IN-EMACS, Emacs will visit the file.
10410 With a double \\[universal-argument] \\[universal-argument] \
10411 prefix arg, Org tries to avoid opening in Emacs
10412 and to use an external application to visit the file.
10414 Optional LINE specifies a line to go to, optional SEARCH a string
10415 to search for. If LINE or SEARCH is given, the file will be
10416 opened in Emacs, unless an entry from org-file-apps that makes
10417 use of groups in a regexp matches.
10419 If you want to change the way frames are used when following a
10420 link, please customize `org-link-frame-setup'.
10422 If the file does not exist, an error is thrown."
10423 (let* ((file (if (equal path "")
10424 buffer-file-name
10425 (substitute-in-file-name (expand-file-name path))))
10426 (file-apps (append org-file-apps (org-default-apps)))
10427 (apps (org-remove-if
10428 'org-file-apps-entry-match-against-dlink-p file-apps))
10429 (apps-dlink (org-remove-if-not
10430 'org-file-apps-entry-match-against-dlink-p file-apps))
10431 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10432 (dirp (if remp nil (file-directory-p file)))
10433 (file (if (and dirp org-open-directory-means-index-dot-org)
10434 (concat (file-name-as-directory file) "index.org")
10435 file))
10436 (a-m-a-p (assq 'auto-mode apps))
10437 (dfile (downcase file))
10438 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10439 (link (cond ((and (eq line nil)
10440 (eq search nil))
10441 file)
10442 (line
10443 (concat file "::" (number-to-string line)))
10444 (search
10445 (concat file "::" search))))
10446 (dlink (downcase link))
10447 (old-buffer (current-buffer))
10448 (old-pos (point))
10449 (old-mode major-mode)
10450 ext cmd link-match-data)
10451 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10452 (setq ext (match-string 1 dfile))
10453 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10454 (setq ext (match-string 1 dfile))))
10455 (cond
10456 ((member in-emacs '((16) system))
10457 (setq cmd (cdr (assoc 'system apps))))
10458 (in-emacs (setq cmd 'emacs))
10460 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10461 (and dirp (cdr (assoc 'directory apps)))
10462 ; first, try matching against apps-dlink
10463 ; if we get a match here, store the match data for later
10464 (let ((match (assoc-default dlink apps-dlink
10465 'string-match)))
10466 (if match
10467 (progn (setq link-match-data (match-data))
10468 match)
10469 (progn (setq in-emacs (or in-emacs line search))
10470 nil))) ; if we have no match in apps-dlink,
10471 ; always open the file in emacs if line or search
10472 ; is given (for backwards compatibility)
10473 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10474 'string-match)
10475 (cdr (assoc ext apps))
10476 (cdr (assoc t apps))))))
10477 (when (eq cmd 'system)
10478 (setq cmd (cdr (assoc 'system apps))))
10479 (when (eq cmd 'default)
10480 (setq cmd (cdr (assoc t apps))))
10481 (when (eq cmd 'mailcap)
10482 (require 'mailcap)
10483 (mailcap-parse-mailcaps)
10484 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10485 (command (mailcap-mime-info mime-type)))
10486 (if (stringp command)
10487 (setq cmd command)
10488 (setq cmd 'emacs))))
10489 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10490 (not (file-exists-p file))
10491 (not org-open-non-existing-files))
10492 (error "No such file: %s" file))
10493 (cond
10494 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10495 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10496 (while (string-match "['\"]%s['\"]" cmd)
10497 (setq cmd (replace-match "%s" t t cmd)))
10498 (while (string-match "%s" cmd)
10499 (setq cmd (replace-match
10500 (save-match-data
10501 (shell-quote-argument
10502 (convert-standard-filename file)))
10503 t t cmd)))
10505 ;; Replace "%1", "%2" etc. in command with group matches from regex
10506 (save-match-data
10507 (let ((match-index 1)
10508 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10509 (set-match-data link-match-data)
10510 (while (<= match-index number-of-groups)
10511 (let ((regex (concat "%" (number-to-string match-index)))
10512 (replace-with (match-string match-index dlink)))
10513 (while (string-match regex cmd)
10514 (setq cmd (replace-match replace-with t t cmd))))
10515 (setq match-index (+ match-index 1)))))
10517 (save-window-excursion
10518 (start-process-shell-command cmd nil cmd)
10519 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
10521 ((or (stringp cmd)
10522 (eq cmd 'emacs))
10523 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10524 (widen)
10525 (if line (org-goto-line line)
10526 (if search (org-link-search search))))
10527 ((consp cmd)
10528 (let ((file (convert-standard-filename file)))
10529 (save-match-data
10530 (set-match-data link-match-data)
10531 (eval cmd))))
10532 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10533 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10534 (or (not (equal old-buffer (current-buffer)))
10535 (not (equal old-pos (point))))
10536 (org-mark-ring-push old-pos old-buffer))))
10538 (defun org-file-apps-entry-match-against-dlink-p (entry)
10539 "This function returns non-nil if `entry' uses a regular
10540 expression which should be matched against the whole link by
10541 org-open-file.
10543 It assumes that is the case when the entry uses a regular
10544 expression which has at least one grouping construct and the
10545 action is either a lisp form or a command string containing
10546 '%1', i.e. using at least one subexpression match as a
10547 parameter."
10548 (let ((selector (car entry))
10549 (action (cdr entry)))
10550 (if (stringp selector)
10551 (and (> (regexp-opt-depth selector) 0)
10552 (or (and (stringp action)
10553 (string-match "%[0-9]" action))
10554 (consp action)))
10555 nil)))
10557 (defun org-default-apps ()
10558 "Return the default applications for this operating system."
10559 (cond
10560 ((eq system-type 'darwin)
10561 org-file-apps-defaults-macosx)
10562 ((eq system-type 'windows-nt)
10563 org-file-apps-defaults-windowsnt)
10564 (t org-file-apps-defaults-gnu)))
10566 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10567 "Convert extensions to regular expressions in the cars of LIST.
10568 Also, weed out any non-string entries, because the return value is used
10569 only for regexp matching.
10570 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10571 point to the symbol `emacs', indicating that the file should
10572 be opened in Emacs."
10573 (append
10574 (delq nil
10575 (mapcar (lambda (x)
10576 (if (not (stringp (car x)))
10578 (if (string-match "\\W" (car x))
10580 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10581 list))
10582 (if add-auto-mode
10583 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10585 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10586 (defun org-file-remote-p (file)
10587 "Test whether FILE specifies a location on a remote system.
10588 Return non-nil if the location is indeed remote.
10590 For example, the filename \"/user@host:/foo\" specifies a location
10591 on the system \"/user@host:\"."
10592 (cond ((fboundp 'file-remote-p)
10593 (file-remote-p file))
10594 ((fboundp 'tramp-handle-file-remote-p)
10595 (tramp-handle-file-remote-p file))
10596 ((and (boundp 'ange-ftp-name-format)
10597 (string-match (car ange-ftp-name-format) file))
10598 t)))
10601 ;;;; Refiling
10603 (defun org-get-org-file ()
10604 "Read a filename, with default directory `org-directory'."
10605 (let ((default (or org-default-notes-file remember-data-file)))
10606 (read-file-name (format "File name [%s]: " default)
10607 (file-name-as-directory org-directory)
10608 default)))
10610 (defun org-notes-order-reversed-p ()
10611 "Check if the current file should receive notes in reversed order."
10612 (cond
10613 ((not org-reverse-note-order) nil)
10614 ((eq t org-reverse-note-order) t)
10615 ((not (listp org-reverse-note-order)) nil)
10616 (t (catch 'exit
10617 (let ((all org-reverse-note-order)
10618 entry)
10619 (while (setq entry (pop all))
10620 (if (string-match (car entry) buffer-file-name)
10621 (throw 'exit (cdr entry))))
10622 nil)))))
10624 (defvar org-refile-target-table nil
10625 "The list of refile targets, created by `org-refile'.")
10627 (defvar org-agenda-new-buffers nil
10628 "Buffers created to visit agenda files.")
10630 (defvar org-refile-cache nil
10631 "Cache for refile targets.")
10633 (defvar org-refile-markers nil
10634 "All the markers used for caching refile locations.")
10636 (defun org-refile-marker (pos)
10637 "Get a new refile marker, but only if caching is in use."
10638 (if (not org-refile-use-cache)
10640 (let ((m (make-marker)))
10641 (move-marker m pos)
10642 (push m org-refile-markers)
10643 m)))
10645 (defun org-refile-cache-clear ()
10646 "Clear the refile cache and disable all the markers."
10647 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10648 (setq org-refile-markers nil)
10649 (setq org-refile-cache nil)
10650 (message "Refile cache has been cleared"))
10652 (defun org-refile-cache-check-set (set)
10653 "Check if all the markers in the cache still have live buffers."
10654 (let (marker)
10655 (catch 'exit
10656 (while (and set (setq marker (nth 3 (pop set))))
10657 ;; if org-refile-use-outline-path is 'file, marker may be nil
10658 (when (and marker (null (marker-buffer marker)))
10659 (message "not found") (sit-for 3)
10660 (throw 'exit nil)))
10661 t)))
10663 (defun org-refile-cache-put (set &rest identifiers)
10664 "Push the refile targets SET into the cache, under IDENTIFIERS."
10665 (let* ((key (sha1 (prin1-to-string identifiers)))
10666 (entry (assoc key org-refile-cache)))
10667 (if entry
10668 (setcdr entry set)
10669 (push (cons key set) org-refile-cache))))
10671 (defun org-refile-cache-get (&rest identifiers)
10672 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10673 (cond
10674 ((not org-refile-cache) nil)
10675 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10677 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10678 org-refile-cache))))
10679 (and set (org-refile-cache-check-set set) set)))))
10681 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10682 "Produce a table with refile targets."
10683 (let ((case-fold-search nil)
10684 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10685 (entries (or org-refile-targets '((nil . (:level . 1)))))
10686 targets tgs txt re files f desc descre fast-path-p level pos0)
10687 (message "Getting targets...")
10688 (with-current-buffer (or default-buffer (current-buffer))
10689 (while (setq entry (pop entries))
10690 (setq files (car entry) desc (cdr entry))
10691 (setq fast-path-p nil)
10692 (cond
10693 ((null files) (setq files (list (current-buffer))))
10694 ((eq files 'org-agenda-files)
10695 (setq files (org-agenda-files 'unrestricted)))
10696 ((and (symbolp files) (fboundp files))
10697 (setq files (funcall files)))
10698 ((and (symbolp files) (boundp files))
10699 (setq files (symbol-value files))))
10700 (if (stringp files) (setq files (list files)))
10701 (cond
10702 ((eq (car desc) :tag)
10703 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10704 ((eq (car desc) :todo)
10705 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10706 ((eq (car desc) :regexp)
10707 (setq descre (cdr desc)))
10708 ((eq (car desc) :level)
10709 (setq descre (concat "^\\*\\{" (number-to-string
10710 (if org-odd-levels-only
10711 (1- (* 2 (cdr desc)))
10712 (cdr desc)))
10713 "\\}[ \t]")))
10714 ((eq (car desc) :maxlevel)
10715 (setq fast-path-p t)
10716 (setq descre (concat "^\\*\\{1," (number-to-string
10717 (if org-odd-levels-only
10718 (1- (* 2 (cdr desc)))
10719 (cdr desc)))
10720 "\\}[ \t]")))
10721 (t (error "Bad refiling target description %s" desc)))
10722 (while (setq f (pop files))
10723 (with-current-buffer
10724 (if (bufferp f) f (org-get-agenda-file-buffer f))
10726 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10727 (progn
10728 (if (bufferp f) (setq f (buffer-file-name
10729 (buffer-base-buffer f))))
10730 (setq f (and f (expand-file-name f)))
10731 (if (eq org-refile-use-outline-path 'file)
10732 (push (list (file-name-nondirectory f) f nil nil) tgs))
10733 (save-excursion
10734 (save-restriction
10735 (widen)
10736 (goto-char (point-min))
10737 (while (re-search-forward descre nil t)
10738 (goto-char (setq pos0 (point-at-bol)))
10739 (catch 'next
10740 (when org-refile-target-verify-function
10741 (save-match-data
10742 (or (funcall org-refile-target-verify-function)
10743 (throw 'next t))))
10744 (when (and (looking-at org-complex-heading-regexp)
10745 (not (member (match-string 4) excluded-entries))
10746 (match-string 4))
10747 (setq level (org-reduced-level
10748 (- (match-end 1) (match-beginning 1)))
10749 txt (org-link-display-format (match-string 4))
10750 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10751 re (format org-complex-heading-regexp-format
10752 (regexp-quote (match-string 4))))
10753 (when org-refile-use-outline-path
10754 (setq txt (mapconcat
10755 'org-protect-slash
10756 (append
10757 (if (eq org-refile-use-outline-path
10758 'file)
10759 (list (file-name-nondirectory
10760 (buffer-file-name
10761 (buffer-base-buffer))))
10762 (if (eq org-refile-use-outline-path
10763 'full-file-path)
10764 (list (buffer-file-name
10765 (buffer-base-buffer)))))
10766 (org-get-outline-path fast-path-p
10767 level txt)
10768 (list txt))
10769 "/")))
10770 (push (list txt f re (org-refile-marker (point)))
10771 tgs)))
10772 (when (= (point) pos0)
10773 ;; verification function has not moved point
10774 (goto-char (point-at-eol))))))))
10775 (when org-refile-use-cache
10776 (org-refile-cache-put tgs (buffer-file-name) descre))
10777 (setq targets (append tgs targets))
10778 ))))
10779 (message "Getting targets...done")
10780 (nreverse targets)))
10782 (defun org-protect-slash (s)
10783 (while (string-match "/" s)
10784 (setq s (replace-match "\\" t t s)))
10787 (defvar org-olpa (make-vector 20 nil))
10789 (defun org-get-outline-path (&optional fastp level heading)
10790 "Return the outline path to the current entry, as a list.
10792 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10793 routine which makes outline path derivations for an entire file,
10794 avoiding backtracing. Refile target collection makes use of that."
10795 (if fastp
10796 (progn
10797 (if (> level 19)
10798 (error "Outline path failure, more than 19 levels"))
10799 (loop for i from level upto 19 do
10800 (aset org-olpa i nil))
10801 (prog1
10802 (delq nil (append org-olpa nil))
10803 (aset org-olpa level heading)))
10804 (let (rtn case-fold-search)
10805 (save-excursion
10806 (save-restriction
10807 (widen)
10808 (while (org-up-heading-safe)
10809 (when (looking-at org-complex-heading-regexp)
10810 (push (org-match-string-no-properties 4) rtn)))
10811 rtn)))))
10813 (defun org-format-outline-path (path &optional width prefix)
10814 "Format the outline path PATH for display.
10815 Width is the maximum number of characters that is available.
10816 Prefix is a prefix to be included in the returned string,
10817 such as the file name."
10818 (setq width (or width 79))
10819 (if prefix (setq width (- width (length prefix))))
10820 (if (not path)
10821 (or prefix "")
10822 (let* ((nsteps (length path))
10823 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10824 (maxwidth (if (<= total-width width)
10825 10000 ;; everything fits
10826 ;; we need to shorten the level headings
10827 (/ (- width nsteps) nsteps)))
10828 (org-odd-levels-only nil)
10829 (n 0)
10830 (total (1+ (length prefix))))
10831 (setq maxwidth (max maxwidth 10))
10832 (concat prefix
10833 (mapconcat
10834 (lambda (h)
10835 (setq n (1+ n))
10836 (if (and (= n nsteps) (< maxwidth 10000))
10837 (setq maxwidth (- total-width total)))
10838 (if (< (length h) maxwidth)
10839 (progn (setq total (+ total (length h) 1)) h)
10840 (setq h (substring h 0 (- maxwidth 2))
10841 total (+ total maxwidth 1))
10842 (if (string-match "[ \t]+\\'" h)
10843 (setq h (substring h 0 (match-beginning 0))))
10844 (setq h (concat h "..")))
10845 (org-add-props h nil 'face
10846 (nth (% (1- n) org-n-level-faces)
10847 org-level-faces))
10849 path "/")))))
10851 (defun org-display-outline-path (&optional file current)
10852 "Display the current outline path in the echo area."
10853 (interactive "P")
10854 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10855 (case-fold-search nil)
10856 (path (and (derived-mode-p 'org-mode) (org-get-outline-path))))
10857 (if current (setq path (append path
10858 (save-excursion
10859 (org-back-to-heading t)
10860 (if (looking-at org-complex-heading-regexp)
10861 (list (match-string 4)))))))
10862 (message "%s"
10863 (org-format-outline-path
10864 path
10865 (1- (frame-width))
10866 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
10868 (defvar org-refile-history nil
10869 "History for refiling operations.")
10871 (defvar org-after-refile-insert-hook nil
10872 "Hook run after `org-refile' has inserted its stuff at the new location.
10873 Note that this is still *before* the stuff will be removed from
10874 the *old* location.")
10876 (defvar org-capture-last-stored-marker)
10877 (defun org-refile (&optional goto default-buffer rfloc)
10878 "Move the entry or entries at point to another heading.
10879 The list of target headings is compiled using the information in
10880 `org-refile-targets', which see.
10882 At the target location, the entry is filed as a subitem of the target
10883 heading. Depending on `org-reverse-note-order', the new subitem will
10884 either be the first or the last subitem.
10886 If there is an active region, all entries in that region will be moved.
10887 However, the region must fulfill the requirement that the first heading
10888 is the first one sets the top-level of the moved text - at most siblings
10889 below it are allowed.
10891 With prefix arg GOTO, the command will only visit the target location
10892 and not actually move anything.
10894 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10895 go to the location where the last refiling operation has put the subtree.
10896 With a prefix argument of `2', refile to the running clock.
10898 RFLOC can be a refile location obtained in a different way.
10900 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10902 If you are using target caching (see `org-refile-use-cache'),
10903 you have to clear the target cache in order to find new targets.
10904 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10905 prefix argument (`C-u C-u C-u C-c C-w')."
10907 (interactive "P")
10908 (if (member goto '(0 (64)))
10909 (org-refile-cache-clear)
10910 (let* ((cbuf (current-buffer))
10911 (regionp (org-region-active-p))
10912 (region-start (and regionp (region-beginning)))
10913 (region-end (and regionp (region-end)))
10914 (region-length (and regionp (- region-end region-start)))
10915 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10916 pos it nbuf file re level reversed)
10917 (setq last-command nil)
10918 (when regionp
10919 (goto-char region-start)
10920 (or (bolp) (goto-char (point-at-bol)))
10921 (setq region-start (point))
10922 (unless (or (org-kill-is-subtree-p
10923 (buffer-substring region-start region-end))
10924 (prog1 org-refile-active-region-within-subtree
10925 (org-toggle-heading)))
10926 (error "The region is not a (sequence of) subtree(s)")))
10927 (if (equal goto '(16))
10928 (org-refile-goto-last-stored)
10929 (when (or
10930 (and (equal goto 2)
10931 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10932 (prog1
10933 (setq it (list (or org-clock-heading "running clock")
10934 (buffer-file-name
10935 (marker-buffer org-clock-hd-marker))
10937 (marker-position org-clock-hd-marker)))
10938 (setq goto nil)))
10939 (setq it (or rfloc
10940 (let (heading-text)
10941 (save-excursion
10942 (unless goto
10943 (org-back-to-heading t)
10944 (setq heading-text
10945 (nth 4 (org-heading-components))))
10946 (org-refile-get-location
10947 (cond (goto "Goto")
10948 (regionp "Refile region to")
10949 (t (concat "Refile subtree \""
10950 heading-text "\" to")))
10951 default-buffer
10952 (and (not (equal '(4) goto))
10953 org-refile-allow-creating-parent-nodes)
10954 goto))))))
10955 (setq file (nth 1 it)
10956 re (nth 2 it)
10957 pos (nth 3 it))
10958 (if (and (not goto)
10960 (equal (buffer-file-name) file)
10961 (if regionp
10962 (and (>= pos region-start)
10963 (<= pos region-end))
10964 (and (>= pos (point))
10965 (< pos (save-excursion
10966 (org-end-of-subtree t t))))))
10967 (error "Cannot refile to position inside the tree or region"))
10969 (setq nbuf (or (find-buffer-visiting file)
10970 (find-file-noselect file)))
10971 (if goto
10972 (progn
10973 (org-pop-to-buffer-same-window nbuf)
10974 (goto-char pos)
10975 (org-show-context 'org-goto))
10976 (if regionp
10977 (progn
10978 (org-kill-new (buffer-substring region-start region-end))
10979 (org-save-markers-in-region region-start region-end))
10980 (org-copy-subtree 1 nil t))
10981 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
10982 (find-file-noselect file)))
10983 (setq reversed (org-notes-order-reversed-p))
10984 (save-excursion
10985 (save-restriction
10986 (widen)
10987 (if pos
10988 (progn
10989 (goto-char pos)
10990 (looking-at org-outline-regexp)
10991 (setq level (org-get-valid-level (funcall outline-level) 1))
10992 (goto-char
10993 (if reversed
10994 (or (outline-next-heading) (point-max))
10995 (or (save-excursion (org-get-next-sibling))
10996 (org-end-of-subtree t t)
10997 (point-max)))))
10998 (setq level 1)
10999 (if (not reversed)
11000 (goto-char (point-max))
11001 (goto-char (point-min))
11002 (or (outline-next-heading) (goto-char (point-max)))))
11003 (if (not (bolp)) (newline))
11004 (org-paste-subtree level)
11005 (when org-log-refile
11006 (org-add-log-setup 'refile nil nil 'findpos
11007 org-log-refile)
11008 (unless (eq org-log-refile 'note)
11009 (save-excursion (org-add-log-note))))
11010 (and org-auto-align-tags
11011 (let ((org-loop-over-headlines-in-active-region nil))
11012 (org-set-tags nil t)))
11013 (bookmark-set "org-refile-last-stored")
11014 ;; If we are refiling for capture, make sure that the
11015 ;; last-capture pointers point here
11016 (when (org-bound-and-true-p org-refile-for-capture)
11017 (bookmark-set "org-capture-last-stored-marker")
11018 (move-marker org-capture-last-stored-marker (point)))
11019 (if (fboundp 'deactivate-mark) (deactivate-mark))
11020 (run-hooks 'org-after-refile-insert-hook))))
11021 (if regionp
11022 (delete-region (point) (+ (point) region-length))
11023 (org-cut-subtree))
11024 (when (featurep 'org-inlinetask)
11025 (org-inlinetask-remove-END-maybe))
11026 (setq org-markers-to-move nil)
11027 (message "Refiled to \"%s\" in file %s" (car it) file)))))))
11029 (defun org-refile-goto-last-stored ()
11030 "Go to the location where the last refile was stored."
11031 (interactive)
11032 (bookmark-jump "org-refile-last-stored")
11033 (message "This is the location of the last refile"))
11035 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11036 no-exclude)
11037 "Prompt the user for a refile location, using PROMPT.
11038 PROMPT should not be suffixed with a colon and a space, because
11039 this function appends the default value from
11040 `org-refile-history' automatically, if that is not empty.
11041 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11042 this is used for the GOTO interface."
11043 (let ((org-refile-targets org-refile-targets)
11044 (org-refile-use-outline-path org-refile-use-outline-path)
11045 excluded-entries)
11046 (when (and (derived-mode-p 'org-mode)
11047 (not org-refile-use-cache)
11048 (not no-exclude))
11049 (org-map-tree
11050 (lambda()
11051 (setq excluded-entries
11052 (append excluded-entries (list (org-get-heading t t)))))))
11053 (setq org-refile-target-table
11054 (org-refile-get-targets default-buffer excluded-entries)))
11055 (unless org-refile-target-table
11056 (error "No refile targets"))
11057 (let* ((prompt (concat prompt
11058 (and (car org-refile-history)
11059 (concat " (default " (car org-refile-history) ")"))
11060 ": "))
11061 (cbuf (current-buffer))
11062 (partial-completion-mode nil)
11063 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11064 (cfunc (if (and org-refile-use-outline-path
11065 org-outline-path-complete-in-steps)
11066 'org-olpath-completing-read
11067 'org-icompleting-read))
11068 (extra (if org-refile-use-outline-path "/" ""))
11069 (filename (and cfn (expand-file-name cfn)))
11070 (tbl (mapcar
11071 (lambda (x)
11072 (if (and (not (member org-refile-use-outline-path
11073 '(file full-file-path)))
11074 (not (equal filename (nth 1 x))))
11075 (cons (concat (car x) extra " ("
11076 (file-name-nondirectory (nth 1 x)) ")")
11077 (cdr x))
11078 (cons (concat (car x) extra) (cdr x))))
11079 org-refile-target-table))
11080 (completion-ignore-case t)
11081 pa answ parent-target child parent old-hist)
11082 (setq old-hist org-refile-history)
11083 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11084 nil 'org-refile-history (car org-refile-history)))
11085 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11086 (org-refile-check-position pa)
11087 (if pa
11088 (progn
11089 (when (or (not org-refile-history)
11090 (not (eq old-hist org-refile-history))
11091 (not (equal (car pa) (car org-refile-history))))
11092 (setq org-refile-history
11093 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11094 org-refile-history
11095 (cdr org-refile-history))))
11096 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11097 (pop org-refile-history)))
11099 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11100 (progn
11101 (setq parent (match-string 1 answ)
11102 child (match-string 2 answ))
11103 (setq parent-target (or (assoc parent tbl)
11104 (assoc (concat parent "/") tbl)))
11105 (when (and parent-target
11106 (or (eq new-nodes t)
11107 (and (eq new-nodes 'confirm)
11108 (y-or-n-p (format "Create new node \"%s\"? "
11109 child)))))
11110 (org-refile-new-child parent-target child)))
11111 (error "Invalid target location")))))
11113 (declare-function org-string-nw-p "org-macs.el" (s))
11114 (defun org-refile-check-position (refile-pointer)
11115 "Check if the refile pointer matches the readline to which it points."
11116 (let* ((file (nth 1 refile-pointer))
11117 (re (nth 2 refile-pointer))
11118 (pos (nth 3 refile-pointer))
11119 buffer)
11120 (when (org-string-nw-p re)
11121 (setq buffer (if (markerp pos)
11122 (marker-buffer pos)
11123 (or (find-buffer-visiting file)
11124 (find-file-noselect file))))
11125 (with-current-buffer buffer
11126 (save-excursion
11127 (save-restriction
11128 (widen)
11129 (goto-char pos)
11130 (beginning-of-line 1)
11131 (unless (org-looking-at-p re)
11132 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11134 (defun org-refile-new-child (parent-target child)
11135 "Use refile target PARENT-TARGET to add new CHILD below it."
11136 (unless parent-target
11137 (error "Cannot find parent for new node"))
11138 (let ((file (nth 1 parent-target))
11139 (pos (nth 3 parent-target))
11140 level)
11141 (with-current-buffer (or (find-buffer-visiting file)
11142 (find-file-noselect file))
11143 (save-excursion
11144 (save-restriction
11145 (widen)
11146 (if pos
11147 (goto-char pos)
11148 (goto-char (point-max))
11149 (if (not (bolp)) (newline)))
11150 (when (looking-at org-outline-regexp)
11151 (setq level (funcall outline-level))
11152 (org-end-of-subtree t t))
11153 (org-back-over-empty-lines)
11154 (insert "\n" (make-string
11155 (if pos (org-get-valid-level level 1) 1) ?*)
11156 " " child "\n")
11157 (beginning-of-line 0)
11158 (list (concat (car parent-target) "/" child) file "" (point)))))))
11160 (defun org-olpath-completing-read (prompt collection &rest args)
11161 "Read an outline path like a file name."
11162 (let ((thetable collection)
11163 (org-completion-use-ido nil) ; does not work with ido.
11164 (org-completion-use-iswitchb nil)) ; or iswitchb
11165 (apply
11166 'org-icompleting-read prompt
11167 (lambda (string predicate &optional flag)
11168 (let (rtn r f (l (length string)))
11169 (cond
11170 ((eq flag nil)
11171 ;; try completion
11172 (try-completion string thetable))
11173 ((eq flag t)
11174 ;; all-completions
11175 (setq rtn (all-completions string thetable predicate))
11176 (mapcar
11177 (lambda (x)
11178 (setq r (substring x l))
11179 (if (string-match " ([^)]*)$" x)
11180 (setq f (match-string 0 x))
11181 (setq f ""))
11182 (if (string-match "/" r)
11183 (concat string (substring r 0 (match-end 0)) f)
11185 rtn))
11186 ((eq flag 'lambda)
11187 ;; exact match?
11188 (assoc string thetable)))))
11189 args)))
11191 ;;;; Dynamic blocks
11193 (defun org-find-dblock (name)
11194 "Find the first dynamic block with name NAME in the buffer.
11195 If not found, stay at current position and return nil."
11196 (let ((case-fold-search t) pos)
11197 (save-excursion
11198 (goto-char (point-min))
11199 (setq pos (and (re-search-forward
11200 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11201 (match-beginning 0))))
11202 (if pos (goto-char pos))
11203 pos))
11205 (defconst org-dblock-start-re
11206 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11207 "Matches the start line of a dynamic block, with parameters.")
11209 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11210 "Matches the end of a dynamic block.")
11212 (defun org-create-dblock (plist)
11213 "Create a dynamic block section, with parameters taken from PLIST.
11214 PLIST must contain a :name entry which is used as name of the block."
11215 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11216 (end-of-line 1)
11217 (newline))
11218 (let ((col (current-column))
11219 (name (plist-get plist :name)))
11220 (insert "#+BEGIN: " name)
11221 (while plist
11222 (if (eq (car plist) :name)
11223 (setq plist (cddr plist))
11224 (insert " " (prin1-to-string (pop plist)))))
11225 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11226 (beginning-of-line -2)))
11228 (defun org-prepare-dblock ()
11229 "Prepare dynamic block for refresh.
11230 This empties the block, puts the cursor at the insert position and returns
11231 the property list including an extra property :name with the block name."
11232 (unless (looking-at org-dblock-start-re)
11233 (error "Not at a dynamic block"))
11234 (let* ((begdel (1+ (match-end 0)))
11235 (name (org-no-properties (match-string 1)))
11236 (params (append (list :name name)
11237 (read (concat "(" (match-string 3) ")")))))
11238 (save-excursion
11239 (beginning-of-line 1)
11240 (skip-chars-forward " \t")
11241 (setq params (plist-put params :indentation-column (current-column))))
11242 (unless (re-search-forward org-dblock-end-re nil t)
11243 (error "Dynamic block not terminated"))
11244 (setq params
11245 (append params
11246 (list :content (buffer-substring
11247 begdel (match-beginning 0)))))
11248 (delete-region begdel (match-beginning 0))
11249 (goto-char begdel)
11250 (open-line 1)
11251 params))
11253 (defun org-map-dblocks (&optional command)
11254 "Apply COMMAND to all dynamic blocks in the current buffer.
11255 If COMMAND is not given, use `org-update-dblock'."
11256 (let ((cmd (or command 'org-update-dblock)))
11257 (save-excursion
11258 (goto-char (point-min))
11259 (while (re-search-forward org-dblock-start-re nil t)
11260 (goto-char (match-beginning 0))
11261 (save-excursion
11262 (condition-case nil
11263 (funcall cmd)
11264 (error (message "Error during update of dynamic block"))))
11265 (unless (re-search-forward org-dblock-end-re nil t)
11266 (error "Dynamic block not terminated"))))))
11268 (defun org-dblock-update (&optional arg)
11269 "User command for updating dynamic blocks.
11270 Update the dynamic block at point. With prefix ARG, update all dynamic
11271 blocks in the buffer."
11272 (interactive "P")
11273 (if arg
11274 (org-update-all-dblocks)
11275 (or (looking-at org-dblock-start-re)
11276 (org-beginning-of-dblock))
11277 (org-update-dblock)))
11279 (defun org-update-dblock ()
11280 "Update the dynamic block at point.
11281 This means to empty the block, parse for parameters and then call
11282 the correct writing function."
11283 (interactive)
11284 (save-window-excursion
11285 (let* ((pos (point))
11286 (line (org-current-line))
11287 (params (org-prepare-dblock))
11288 (name (plist-get params :name))
11289 (indent (plist-get params :indentation-column))
11290 (cmd (intern (concat "org-dblock-write:" name))))
11291 (message "Updating dynamic block `%s' at line %d..." name line)
11292 (funcall cmd params)
11293 (message "Updating dynamic block `%s' at line %d...done" name line)
11294 (goto-char pos)
11295 (when (and indent (> indent 0))
11296 (setq indent (make-string indent ?\ ))
11297 (save-excursion
11298 (org-beginning-of-dblock)
11299 (forward-line 1)
11300 (while (not (looking-at org-dblock-end-re))
11301 (insert indent)
11302 (beginning-of-line 2))
11303 (when (looking-at org-dblock-end-re)
11304 (and (looking-at "[ \t]+")
11305 (replace-match ""))
11306 (insert indent)))))))
11308 (defun org-beginning-of-dblock ()
11309 "Find the beginning of the dynamic block at point.
11310 Error if there is no such block at point."
11311 (let ((pos (point))
11312 beg)
11313 (end-of-line 1)
11314 (if (and (re-search-backward org-dblock-start-re nil t)
11315 (setq beg (match-beginning 0))
11316 (re-search-forward org-dblock-end-re nil t)
11317 (> (match-end 0) pos))
11318 (goto-char beg)
11319 (goto-char pos)
11320 (error "Not in a dynamic block"))))
11322 ;;;###autoload
11323 (defun org-update-all-dblocks ()
11324 "Update all dynamic blocks in the buffer.
11325 This function can be used in a hook."
11326 (interactive)
11327 (when (derived-mode-p 'org-mode)
11328 (org-map-dblocks 'org-update-dblock)))
11331 ;;;; Completion
11333 (defconst org-additional-option-like-keywords
11334 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11335 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11336 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11337 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11338 "BEGIN:" "END:"
11339 "ORGTBL" "TBLFM:" "TBLNAME:"
11340 "BEGIN_EXAMPLE" "END_EXAMPLE"
11341 "BEGIN_VERBATIM" "END_VERBATIM"
11342 "BEGIN_QUOTE" "END_QUOTE"
11343 "BEGIN_VERSE" "END_VERSE"
11344 "BEGIN_CENTER" "END_CENTER"
11345 "BEGIN_SRC" "END_SRC"
11346 "BEGIN_RESULT" "END_RESULT"
11347 "BEGIN_lstlisting" "END_lstlisting"
11348 "NAME:" "RESULTS:"
11349 "HEADER:" "HEADERS:"
11350 "COLUMNS:" "PROPERTY:"
11351 "CAPTION:" "LABEL:"
11352 "SETUPFILE:"
11353 "INCLUDE:"
11354 "BIND:"
11355 "MACRO:"))
11357 (defconst org-options-keywords
11358 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11359 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11360 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11361 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11362 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11363 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11364 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11366 (defconst org-additional-option-like-keywords-for-flyspell
11367 (delete-dups
11368 (split-string
11369 (mapconcat (lambda(k)
11370 (replace-regexp-in-string
11371 "_\\|:" " "
11372 (concat k " " (downcase k) " " (upcase k))))
11373 (append org-options-keywords org-additional-option-like-keywords)
11374 " ")
11375 " +" t)))
11377 (defcustom org-structure-template-alist
11379 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11380 "<src lang=\"?\">\n\n</src>")
11381 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11382 "<example>\n?\n</example>")
11383 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11384 "<quote>\n?\n</quote>")
11385 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11386 "<verse>\n?\n</verse>")
11387 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11388 "<center>\n?\n</center>")
11389 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11390 "<literal style=\"latex\">\n?\n</literal>")
11391 ("L" "#+LaTeX: "
11392 "<literal style=\"latex\">?</literal>")
11393 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11394 "<literal style=\"html\">\n?\n</literal>")
11395 ("H" "#+HTML: "
11396 "<literal style=\"html\">?</literal>")
11397 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11398 ("A" "#+ASCII: ")
11399 ("i" "#+INDEX: ?"
11400 "#+INDEX: ?")
11401 ("I" "#+INCLUDE: %file ?"
11402 "<include file=%file markup=\"?\">")
11404 "Structure completion elements.
11405 This is a list of abbreviation keys and values. The value gets inserted
11406 if you type `<' followed by the key and then press the completion key,
11407 usually `M-TAB'. %file will be replaced by a file name after prompting
11408 for the file using completion. The cursor will be placed at the position
11409 of the `?` in the template.
11410 There are two templates for each key, the first uses the original Org syntax,
11411 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11412 the default when the /org-mtags.el/ module has been loaded. See also the
11413 variable `org-mtags-prefer-muse-templates'."
11414 :group 'org-completion
11415 :type '(repeat
11416 (string :tag "Key")
11417 (string :tag "Template")
11418 (string :tag "Muse Template")))
11420 (defun org-try-structure-completion ()
11421 "Try to complete a structure template before point.
11422 This looks for strings like \"<e\" on an otherwise empty line and
11423 expands them."
11424 (let ((l (buffer-substring (point-at-bol) (point)))
11426 (when (and (looking-at "[ \t]*$")
11427 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11428 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11429 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11430 (match-beginning 1)) a)
11431 t)))
11433 (defun org-complete-expand-structure-template (start cell)
11434 "Expand a structure template."
11435 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11436 (rpl (nth (if musep 2 1) cell))
11437 (ind ""))
11438 (delete-region start (point))
11439 (when (string-match "\\`#\\+" rpl)
11440 (cond
11441 ((bolp))
11442 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11443 (setq ind (buffer-substring (point-at-bol) (point))))
11444 (t (newline))))
11445 (setq start (point))
11446 (if (string-match "%file" rpl)
11447 (setq rpl (replace-match
11448 (concat
11449 "\""
11450 (save-match-data
11451 (abbreviate-file-name (read-file-name "Include file: ")))
11452 "\"")
11453 t t rpl)))
11454 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11455 (concat "\n" ind)))
11456 (insert rpl)
11457 (if (re-search-backward "\\?" start t) (delete-char 1))))
11459 ;;;; TODO, DEADLINE, Comments
11461 (defun org-toggle-comment ()
11462 "Change the COMMENT state of an entry."
11463 (interactive)
11464 (save-excursion
11465 (org-back-to-heading)
11466 (let (case-fold-search)
11467 (cond
11468 ((looking-at (format org-heading-keyword-regexp-format
11469 org-comment-string))
11470 (goto-char (match-end 1))
11471 (looking-at (concat " +" org-comment-string))
11472 (replace-match "" t t)
11473 (when (eolp) (insert " ")))
11474 ((looking-at org-outline-regexp)
11475 (goto-char (match-end 0))
11476 (insert org-comment-string " "))))))
11478 (defvar org-last-todo-state-is-todo nil
11479 "This is non-nil when the last TODO state change led to a TODO state.
11480 If the last change removed the TODO tag or switched to DONE, then
11481 this is nil.")
11483 (defvar org-setting-tags nil) ; dynamically skipped
11485 (defvar org-todo-setup-filter-hook nil
11486 "Hook for functions that pre-filter todo specs.
11487 Each function takes a todo spec and returns either nil or the spec
11488 transformed into canonical form." )
11490 (defvar org-todo-get-default-hook nil
11491 "Hook for functions that get a default item for todo.
11492 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11493 nil or a string to be used for the todo mark." )
11495 (defvar org-agenda-headline-snapshot-before-repeat)
11497 (defun org-current-effective-time ()
11498 "Return current time adjusted for `org-extend-today-until' variable."
11499 (let* ((ct (org-current-time))
11500 (dct (decode-time ct))
11501 (ct1
11502 (if (and org-use-effective-time
11503 (< (nth 2 dct) org-extend-today-until))
11504 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
11505 ct)))
11506 ct1))
11508 (defun org-todo-yesterday (&optional arg)
11509 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11510 (interactive "P")
11511 (if (eq major-mode 'org-agenda-mode)
11512 (apply 'org-agenda-todo-yesterday arg)
11513 (let* ((hour (third (decode-time
11514 (org-current-time))))
11515 (org-extend-today-until (1+ hour)))
11516 (org-todo arg))))
11518 (defun org-todo (&optional arg)
11519 "Change the TODO state of an item.
11520 The state of an item is given by a keyword at the start of the heading,
11521 like
11522 *** TODO Write paper
11523 *** DONE Call mom
11525 The different keywords are specified in the variable `org-todo-keywords'.
11526 By default the available states are \"TODO\" and \"DONE\".
11527 So for this example: when the item starts with TODO, it is changed to DONE.
11528 When it starts with DONE, the DONE is removed. And when neither TODO nor
11529 DONE are present, add TODO at the beginning of the heading.
11531 With \\[universal-argument] prefix arg, use completion to determine the new \
11532 state.
11533 With numeric prefix arg, switch to that state.
11534 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11535 keywords (nextset).
11536 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11537 With a numeric prefix arg of 0, inhibit note taking for the change.
11539 For calling through lisp, arg is also interpreted in the following way:
11540 'none -> empty state
11541 \"\"(empty string) -> switch to empty state
11542 'done -> switch to DONE
11543 'nextset -> switch to the next set of keywords
11544 'previousset -> switch to the previous set of keywords
11545 \"WAITING\" -> switch to the specified keyword, but only if it
11546 really is a member of `org-todo-keywords'."
11547 (interactive "P")
11548 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11549 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11550 'region-start-level 'region))
11551 org-loop-over-headlines-in-active-region)
11552 (org-map-entries
11553 `(org-todo ,arg)
11554 org-loop-over-headlines-in-active-region
11555 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11556 (if (equal arg '(16)) (setq arg 'nextset))
11557 (let ((org-blocker-hook org-blocker-hook)
11558 (case-fold-search nil))
11559 (when (equal arg '(64))
11560 (setq arg nil org-blocker-hook nil))
11561 (when (and org-blocker-hook
11562 (or org-inhibit-blocking
11563 (org-entry-get nil "NOBLOCKING")))
11564 (setq org-blocker-hook nil))
11565 (save-excursion
11566 (catch 'exit
11567 (org-back-to-heading t)
11568 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11569 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11570 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11571 (let* ((match-data (match-data))
11572 (startpos (point-at-bol))
11573 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11574 (org-log-done org-log-done)
11575 (org-log-repeat org-log-repeat)
11576 (org-todo-log-states org-todo-log-states)
11577 (org-inhibit-logging
11578 (if (equal arg 0)
11579 (progn (setq arg nil) 'note) org-inhibit-logging))
11580 (this (match-string 1))
11581 (hl-pos (match-beginning 0))
11582 (head (org-get-todo-sequence-head this))
11583 (ass (assoc head org-todo-kwd-alist))
11584 (interpret (nth 1 ass))
11585 (done-word (nth 3 ass))
11586 (final-done-word (nth 4 ass))
11587 (org-last-state (or this ""))
11588 (completion-ignore-case t)
11589 (member (member this org-todo-keywords-1))
11590 (tail (cdr member))
11591 (org-state (cond
11592 ((and org-todo-key-trigger
11593 (or (and (equal arg '(4))
11594 (eq org-use-fast-todo-selection 'prefix))
11595 (and (not arg) org-use-fast-todo-selection
11596 (not (eq org-use-fast-todo-selection
11597 'prefix)))))
11598 ;; Use fast selection
11599 (org-fast-todo-selection))
11600 ((and (equal arg '(4))
11601 (or (not org-use-fast-todo-selection)
11602 (not org-todo-key-trigger)))
11603 ;; Read a state with completion
11604 (org-icompleting-read
11605 "State: " (mapcar (lambda(x) (list x))
11606 org-todo-keywords-1)
11607 nil t))
11608 ((eq arg 'right)
11609 (if this
11610 (if tail (car tail) nil)
11611 (car org-todo-keywords-1)))
11612 ((eq arg 'left)
11613 (if (equal member org-todo-keywords-1)
11615 (if this
11616 (nth (- (length org-todo-keywords-1)
11617 (length tail) 2)
11618 org-todo-keywords-1)
11619 (org-last org-todo-keywords-1))))
11620 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11621 (setq arg nil))) ; hack to fall back to cycling
11622 (arg
11623 ;; user or caller requests a specific state
11624 (cond
11625 ((equal arg "") nil)
11626 ((eq arg 'none) nil)
11627 ((eq arg 'done) (or done-word (car org-done-keywords)))
11628 ((eq arg 'nextset)
11629 (or (car (cdr (member head org-todo-heads)))
11630 (car org-todo-heads)))
11631 ((eq arg 'previousset)
11632 (let ((org-todo-heads (reverse org-todo-heads)))
11633 (or (car (cdr (member head org-todo-heads)))
11634 (car org-todo-heads))))
11635 ((car (member arg org-todo-keywords-1)))
11636 ((stringp arg)
11637 (error "State `%s' not valid in this file" arg))
11638 ((nth (1- (prefix-numeric-value arg))
11639 org-todo-keywords-1))))
11640 ((null member) (or head (car org-todo-keywords-1)))
11641 ((equal this final-done-word) nil) ;; -> make empty
11642 ((null tail) nil) ;; -> first entry
11643 ((memq interpret '(type priority))
11644 (if (eq this-command last-command)
11645 (car tail)
11646 (if (> (length tail) 0)
11647 (or done-word (car org-done-keywords))
11648 nil)))
11650 (car tail))))
11651 (org-state (or
11652 (run-hook-with-args-until-success
11653 'org-todo-get-default-hook org-state org-last-state)
11654 org-state))
11655 (next (if org-state (concat " " org-state " ") " "))
11656 (change-plist (list :type 'todo-state-change :from this :to org-state
11657 :position startpos))
11658 dolog now-done-p)
11659 (when org-blocker-hook
11660 (setq org-last-todo-state-is-todo
11661 (not (member this org-done-keywords)))
11662 (unless (save-excursion
11663 (save-match-data
11664 (org-with-wide-buffer
11665 (run-hook-with-args-until-failure
11666 'org-blocker-hook change-plist))))
11667 (if (org-called-interactively-p 'interactive)
11668 (error "TODO state change from %s to %s blocked" this org-state)
11669 ;; fail silently
11670 (message "TODO state change from %s to %s blocked" this org-state)
11671 (throw 'exit nil))))
11672 (store-match-data match-data)
11673 (replace-match next t t)
11674 (unless (pos-visible-in-window-p hl-pos)
11675 (message "TODO state changed to %s" (org-trim next)))
11676 (unless head
11677 (setq head (org-get-todo-sequence-head org-state)
11678 ass (assoc head org-todo-kwd-alist)
11679 interpret (nth 1 ass)
11680 done-word (nth 3 ass)
11681 final-done-word (nth 4 ass)))
11682 (when (memq arg '(nextset previousset))
11683 (message "Keyword-Set %d/%d: %s"
11684 (- (length org-todo-sets) -1
11685 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11686 (length org-todo-sets)
11687 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11688 (setq org-last-todo-state-is-todo
11689 (not (member org-state org-done-keywords)))
11690 (setq now-done-p (and (member org-state org-done-keywords)
11691 (not (member this org-done-keywords))))
11692 (and logging (org-local-logging logging))
11693 (when (and (or org-todo-log-states org-log-done)
11694 (not (eq org-inhibit-logging t))
11695 (not (memq arg '(nextset previousset))))
11696 ;; we need to look at recording a time and note
11697 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11698 (nth 2 (assoc this org-todo-log-states))))
11699 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11700 (setq dolog 'time))
11701 (when (and org-state
11702 (member org-state org-not-done-keywords)
11703 (not (member this org-not-done-keywords)))
11704 ;; This is now a todo state and was not one before
11705 ;; If there was a CLOSED time stamp, get rid of it.
11706 (org-add-planning-info nil nil 'closed))
11707 (when (and now-done-p org-log-done)
11708 ;; It is now done, and it was not done before
11709 (org-add-planning-info 'closed (org-current-effective-time))
11710 (if (and (not dolog) (eq 'note org-log-done))
11711 (org-add-log-setup 'done org-state this 'findpos 'note)))
11712 (when (and org-state dolog)
11713 ;; This is a non-nil state, and we need to log it
11714 (org-add-log-setup 'state org-state this 'findpos dolog)))
11715 ;; Fixup tag positioning
11716 (org-todo-trigger-tag-changes org-state)
11717 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11718 (when org-provide-todo-statistics
11719 (org-update-parent-todo-statistics))
11720 (run-hooks 'org-after-todo-state-change-hook)
11721 (if (and arg (not (member org-state org-done-keywords)))
11722 (setq head (org-get-todo-sequence-head org-state)))
11723 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11724 ;; Do we need to trigger a repeat?
11725 (when now-done-p
11726 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11727 ;; This is for the agenda, take a snapshot of the headline.
11728 (save-match-data
11729 (setq org-agenda-headline-snapshot-before-repeat
11730 (org-get-heading))))
11731 (org-auto-repeat-maybe org-state))
11732 ;; Fixup cursor location if close to the keyword
11733 (if (and (outline-on-heading-p)
11734 (not (bolp))
11735 (save-excursion (beginning-of-line 1)
11736 (looking-at org-todo-line-regexp))
11737 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11738 (progn
11739 (goto-char (or (match-end 2) (match-end 1)))
11740 (and (looking-at " ") (just-one-space))))
11741 (when org-trigger-hook
11742 (save-excursion
11743 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11745 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11746 "Block turning an entry into a TODO, using the hierarchy.
11747 This checks whether the current task should be blocked from state
11748 changes. Such blocking occurs when:
11750 1. The task has children which are not all in a completed state.
11752 2. A task has a parent with the property :ORDERED:, and there
11753 are siblings prior to the current task with incomplete
11754 status.
11756 3. The parent of the task is blocked because it has siblings that should
11757 be done first, or is child of a block grandparent TODO entry."
11759 (if (not org-enforce-todo-dependencies)
11760 t ; if locally turned off don't block
11761 (catch 'dont-block
11762 ;; If this is not a todo state change, or if this entry is already DONE,
11763 ;; do not block
11764 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11765 (member (plist-get change-plist :from)
11766 (cons 'done org-done-keywords))
11767 (member (plist-get change-plist :to)
11768 (cons 'todo org-not-done-keywords))
11769 (not (plist-get change-plist :to)))
11770 (throw 'dont-block t))
11771 ;; If this task has children, and any are undone, it's blocked
11772 (save-excursion
11773 (org-back-to-heading t)
11774 (let ((this-level (funcall outline-level)))
11775 (outline-next-heading)
11776 (let ((child-level (funcall outline-level)))
11777 (while (and (not (eobp))
11778 (> child-level this-level))
11779 ;; this todo has children, check whether they are all
11780 ;; completed
11781 (if (and (not (org-entry-is-done-p))
11782 (org-entry-is-todo-p))
11783 (throw 'dont-block nil))
11784 (outline-next-heading)
11785 (setq child-level (funcall outline-level))))))
11786 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11787 ;; any previous siblings are undone, it's blocked
11788 (save-excursion
11789 (org-back-to-heading t)
11790 (let* ((pos (point))
11791 (parent-pos (and (org-up-heading-safe) (point))))
11792 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11793 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11794 (forward-line 1)
11795 (re-search-forward org-not-done-heading-regexp pos t))
11796 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11797 ;; Search further up the hierarchy, to see if an ancestor is blocked
11798 (while t
11799 (goto-char parent-pos)
11800 (if (not (looking-at org-not-done-heading-regexp))
11801 (throw 'dont-block t)) ; do not block, parent is not a TODO
11802 (setq pos (point))
11803 (setq parent-pos (and (org-up-heading-safe) (point)))
11804 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11805 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11806 (forward-line 1)
11807 (re-search-forward org-not-done-heading-regexp pos t))
11808 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11810 (defcustom org-track-ordered-property-with-tag nil
11811 "Should the ORDERED property also be shown as a tag?
11812 The ORDERED property decides if an entry should require subtasks to be
11813 completed in sequence. Since a property is not very visible, setting
11814 this option means that toggling the ORDERED property with the command
11815 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11816 not relevant for the behavior, but it makes things more visible.
11818 Note that toggling the tag with tags commands will not change the property
11819 and therefore not influence behavior!
11821 This can be t, meaning the tag ORDERED should be used, It can also be a
11822 string to select a different tag for this task."
11823 :group 'org-todo
11824 :type '(choice
11825 (const :tag "No tracking" nil)
11826 (const :tag "Track with ORDERED tag" t)
11827 (string :tag "Use other tag")))
11829 (defun org-toggle-ordered-property ()
11830 "Toggle the ORDERED property of the current entry.
11831 For better visibility, you can track the value of this property with a tag.
11832 See variable `org-track-ordered-property-with-tag'."
11833 (interactive)
11834 (let* ((t1 org-track-ordered-property-with-tag)
11835 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11836 (save-excursion
11837 (org-back-to-heading)
11838 (if (org-entry-get nil "ORDERED")
11839 (progn
11840 (org-delete-property "ORDERED")
11841 (and tag (org-toggle-tag tag 'off))
11842 (message "Subtasks can be completed in arbitrary order"))
11843 (org-entry-put nil "ORDERED" "t")
11844 (and tag (org-toggle-tag tag 'on))
11845 (message "Subtasks must be completed in sequence")))))
11847 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11848 (defun org-block-todo-from-checkboxes (change-plist)
11849 "Block turning an entry into a TODO, using checkboxes.
11850 This checks whether the current task should be blocked from state
11851 changes because there are unchecked boxes in this entry."
11852 (if (not org-enforce-todo-checkbox-dependencies)
11853 t ; if locally turned off don't block
11854 (catch 'dont-block
11855 ;; If this is not a todo state change, or if this entry is already DONE,
11856 ;; do not block
11857 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11858 (member (plist-get change-plist :from)
11859 (cons 'done org-done-keywords))
11860 (member (plist-get change-plist :to)
11861 (cons 'todo org-not-done-keywords))
11862 (not (plist-get change-plist :to)))
11863 (throw 'dont-block t))
11864 ;; If this task has checkboxes that are not checked, it's blocked
11865 (save-excursion
11866 (org-back-to-heading t)
11867 (let ((beg (point)) end)
11868 (outline-next-heading)
11869 (setq end (point))
11870 (goto-char beg)
11871 (if (org-list-search-forward
11872 (concat (org-item-beginning-re)
11873 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11874 "\\[[- ]\\]")
11875 end t)
11876 (progn
11877 (if (boundp 'org-blocked-by-checkboxes)
11878 (setq org-blocked-by-checkboxes t))
11879 (throw 'dont-block nil)))))
11880 t))) ; do not block
11882 (defun org-entry-blocked-p ()
11883 "Is the current entry blocked?"
11884 (if (org-entry-get nil "NOBLOCKING")
11885 nil ;; Never block this entry
11886 (not
11887 (run-hook-with-args-until-failure
11888 'org-blocker-hook
11889 (list :type 'todo-state-change
11890 :position (point)
11891 :from 'todo
11892 :to 'done)))))
11894 (defun org-update-statistics-cookies (all)
11895 "Update the statistics cookie, either from TODO or from checkboxes.
11896 This should be called with the cursor in a line with a statistics cookie."
11897 (interactive "P")
11898 (if all
11899 (progn
11900 (org-update-checkbox-count 'all)
11901 (org-map-entries 'org-update-parent-todo-statistics))
11902 (if (not (org-at-heading-p))
11903 (org-update-checkbox-count)
11904 (let ((pos (move-marker (make-marker) (point)))
11905 end l1 l2)
11906 (ignore-errors (org-back-to-heading t))
11907 (if (not (org-at-heading-p))
11908 (org-update-checkbox-count)
11909 (setq l1 (org-outline-level))
11910 (setq end (save-excursion
11911 (outline-next-heading)
11912 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11913 (point)))
11914 (if (and (save-excursion
11915 (re-search-forward
11916 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11917 (not (save-excursion (re-search-forward
11918 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11919 (org-update-checkbox-count)
11920 (if (and l2 (> l2 l1))
11921 (progn
11922 (goto-char end)
11923 (org-update-parent-todo-statistics))
11924 (goto-char pos)
11925 (beginning-of-line 1)
11926 (while (re-search-forward
11927 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
11928 (point-at-eol) t)
11929 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
11930 (goto-char pos)
11931 (move-marker pos nil)))))
11933 (defvar org-entry-property-inherited-from) ;; defined below
11934 (defun org-update-parent-todo-statistics ()
11935 "Update any statistics cookie in the parent of the current headline.
11936 When `org-hierarchical-todo-statistics' is nil, statistics will cover
11937 the entire subtree and this will travel up the hierarchy and update
11938 statistics everywhere."
11939 (let* ((prop (save-excursion (org-up-heading-safe)
11940 (org-entry-get nil "COOKIE_DATA" 'inherit)))
11941 (recursive (or (not org-hierarchical-todo-statistics)
11942 (and prop (string-match "\\<recursive\\>" prop))))
11943 (lim (or (and prop (marker-position org-entry-property-inherited-from))
11945 (first t)
11946 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
11947 level ltoggle l1 new ndel
11948 (cnt-all 0) (cnt-done 0) is-percent kwd
11949 checkbox-beg ov ovs ove cookie-present)
11950 (catch 'exit
11951 (save-excursion
11952 (beginning-of-line 1)
11953 (setq ltoggle (funcall outline-level))
11954 ;; Three situations are to consider:
11956 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
11957 ;; to the top-level ancestor on the headline;
11959 ;; 2. If parent has "recursive" property, repeat up to the
11960 ;; headline setting that property, taking inheritance into
11961 ;; account;
11963 ;; 3. Else, move up to direct parent and proceed only once.
11964 (while (and (setq level (org-up-heading-safe))
11965 (or recursive first)
11966 (>= (point) lim))
11967 (setq first nil cookie-present nil)
11968 (unless (and level
11969 (not (string-match
11970 "\\<checkbox\\>"
11971 (downcase (or (org-entry-get nil "COOKIE_DATA")
11972 "")))))
11973 (throw 'exit nil))
11974 (while (re-search-forward box-re (point-at-eol) t)
11975 (setq cnt-all 0 cnt-done 0 cookie-present t)
11976 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
11977 (save-match-data
11978 (unless (outline-next-heading) (throw 'exit nil))
11979 (while (and (looking-at org-complex-heading-regexp)
11980 (> (setq l1 (length (match-string 1))) level))
11981 (setq kwd (and (or recursive (= l1 ltoggle))
11982 (match-string 2)))
11983 (if (or (eq org-provide-todo-statistics 'all-headlines)
11984 (and (listp org-provide-todo-statistics)
11985 (or (member kwd org-provide-todo-statistics)
11986 (member kwd org-done-keywords))))
11987 (setq cnt-all (1+ cnt-all))
11988 (if (eq org-provide-todo-statistics t)
11989 (and kwd (setq cnt-all (1+ cnt-all)))))
11990 (and (member kwd org-done-keywords)
11991 (setq cnt-done (1+ cnt-done)))
11992 (outline-next-heading)))
11993 (setq new
11994 (if is-percent
11995 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
11996 (format "[%d/%d]" cnt-done cnt-all))
11997 ndel (- (match-end 0) checkbox-beg))
11998 ;; handle overlays when updating cookie from column view
11999 (when (setq ov (car (overlays-at checkbox-beg)))
12000 (setq ovs (overlay-start ov) ove (overlay-end ov))
12001 (delete-overlay ov))
12002 (goto-char checkbox-beg)
12003 (insert new)
12004 (delete-region (point) (+ (point) ndel))
12005 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12006 (when ov (move-overlay ov ovs ove)))
12007 (when cookie-present
12008 (run-hook-with-args 'org-after-todo-statistics-hook
12009 cnt-done (- cnt-all cnt-done))))))
12010 (run-hooks 'org-todo-statistics-hook)))
12012 (defvar org-after-todo-statistics-hook nil
12013 "Hook that is called after a TODO statistics cookie has been updated.
12014 Each function is called with two arguments: the number of not-done entries
12015 and the number of done entries.
12017 For example, the following function, when added to this hook, will switch
12018 an entry to DONE when all children are done, and back to TODO when new
12019 entries are set to a TODO status. Note that this hook is only called
12020 when there is a statistics cookie in the headline!
12022 (defun org-summary-todo (n-done n-not-done)
12023 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12024 (let (org-log-done org-log-states) ; turn off logging
12025 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12028 (defvar org-todo-statistics-hook nil
12029 "Hook that is run whenever Org thinks TODO statistics should be updated.
12030 This hook runs even if there is no statistics cookie present, in which case
12031 `org-after-todo-statistics-hook' would not run.")
12033 (defun org-todo-trigger-tag-changes (state)
12034 "Apply the changes defined in `org-todo-state-tags-triggers'."
12035 (let ((l org-todo-state-tags-triggers)
12036 changes)
12037 (when (or (not state) (equal state ""))
12038 (setq changes (append changes (cdr (assoc "" l)))))
12039 (when (and (stringp state) (> (length state) 0))
12040 (setq changes (append changes (cdr (assoc state l)))))
12041 (when (member state org-not-done-keywords)
12042 (setq changes (append changes (cdr (assoc 'todo l)))))
12043 (when (member state org-done-keywords)
12044 (setq changes (append changes (cdr (assoc 'done l)))))
12045 (dolist (c changes)
12046 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12048 (defun org-local-logging (value)
12049 "Get logging settings from a property VALUE."
12050 (let* (words w a)
12051 ;; directly set the variables, they are already local.
12052 (setq org-log-done nil
12053 org-log-repeat nil
12054 org-todo-log-states nil)
12055 (setq words (org-split-string value))
12056 (while (setq w (pop words))
12057 (cond
12058 ((setq a (assoc w org-startup-options))
12059 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12060 (set (nth 1 a) (nth 2 a))))
12061 ((setq a (org-extract-log-state-settings w))
12062 (and (member (car a) org-todo-keywords-1)
12063 (push a org-todo-log-states)))))))
12065 (defun org-get-todo-sequence-head (kwd)
12066 "Return the head of the TODO sequence to which KWD belongs.
12067 If KWD is not set, check if there is a text property remembering the
12068 right sequence."
12069 (let (p)
12070 (cond
12071 ((not kwd)
12072 (or (get-text-property (point-at-bol) 'org-todo-head)
12073 (progn
12074 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12075 nil (point-at-eol)))
12076 (get-text-property p 'org-todo-head))))
12077 ((not (member kwd org-todo-keywords-1))
12078 (car org-todo-keywords-1))
12079 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12081 (defun org-fast-todo-selection ()
12082 "Fast TODO keyword selection with single keys.
12083 Returns the new TODO keyword, or nil if no state change should occur."
12084 (let* ((fulltable org-todo-key-alist)
12085 (done-keywords org-done-keywords) ;; needed for the faces.
12086 (maxlen (apply 'max (mapcar
12087 (lambda (x)
12088 (if (stringp (car x)) (string-width (car x)) 0))
12089 fulltable)))
12090 (expert nil)
12091 (fwidth (+ maxlen 3 1 3))
12092 (ncol (/ (- (window-width) 4) fwidth))
12093 tg cnt e c tbl
12094 groups ingroup)
12095 (save-excursion
12096 (save-window-excursion
12097 (if expert
12098 (set-buffer (get-buffer-create " *Org todo*"))
12099 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12100 (erase-buffer)
12101 (org-set-local 'org-done-keywords done-keywords)
12102 (setq tbl fulltable cnt 0)
12103 (while (setq e (pop tbl))
12104 (cond
12105 ((equal e '(:startgroup))
12106 (push '() groups) (setq ingroup t)
12107 (when (not (= cnt 0))
12108 (setq cnt 0)
12109 (insert "\n"))
12110 (insert "{ "))
12111 ((equal e '(:endgroup))
12112 (setq ingroup nil cnt 0)
12113 (insert "}\n"))
12114 ((equal e '(:newline))
12115 (when (not (= cnt 0))
12116 (setq cnt 0)
12117 (insert "\n")
12118 (setq e (car tbl))
12119 (while (equal (car tbl) '(:newline))
12120 (insert "\n")
12121 (setq tbl (cdr tbl)))))
12123 (setq tg (car e) c (cdr e))
12124 (if ingroup (push tg (car groups)))
12125 (setq tg (org-add-props tg nil 'face
12126 (org-get-todo-face tg)))
12127 (if (and (= cnt 0) (not ingroup)) (insert " "))
12128 (insert "[" c "] " tg (make-string
12129 (- fwidth 4 (length tg)) ?\ ))
12130 (when (= (setq cnt (1+ cnt)) ncol)
12131 (insert "\n")
12132 (if ingroup (insert " "))
12133 (setq cnt 0)))))
12134 (insert "\n")
12135 (goto-char (point-min))
12136 (if (not expert) (org-fit-window-to-buffer))
12137 (message "[a-z..]:Set [SPC]:clear")
12138 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12139 (cond
12140 ((or (= c ?\C-g)
12141 (and (= c ?q) (not (rassoc c fulltable))))
12142 (setq quit-flag t))
12143 ((= c ?\ ) nil)
12144 ((setq e (rassoc c fulltable) tg (car e))
12146 (t (setq quit-flag t)))))))
12148 (defun org-entry-is-todo-p ()
12149 (member (org-get-todo-state) org-not-done-keywords))
12151 (defun org-entry-is-done-p ()
12152 (member (org-get-todo-state) org-done-keywords))
12154 (defun org-get-todo-state ()
12155 (save-excursion
12156 (org-back-to-heading t)
12157 (and (looking-at org-todo-line-regexp)
12158 (match-end 2)
12159 (match-string 2))))
12161 (defun org-at-date-range-p (&optional inactive-ok)
12162 "Is the cursor inside a date range?"
12163 (interactive)
12164 (save-excursion
12165 (catch 'exit
12166 (let ((pos (point)))
12167 (skip-chars-backward "^[<\r\n")
12168 (skip-chars-backward "<[")
12169 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12170 (>= (match-end 0) pos)
12171 (throw 'exit t))
12172 (skip-chars-backward "^<[\r\n")
12173 (skip-chars-backward "<[")
12174 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12175 (>= (match-end 0) pos)
12176 (throw 'exit t)))
12177 nil)))
12179 (defun org-get-repeat (&optional tagline)
12180 "Check if there is a deadline/schedule with repeater in this entry."
12181 (save-match-data
12182 (save-excursion
12183 (org-back-to-heading t)
12184 (and (re-search-forward (if tagline
12185 (concat tagline "\\s-*" org-repeat-re)
12186 org-repeat-re)
12187 (org-entry-end-position) t)
12188 (match-string-no-properties 1)))))
12190 (defvar org-last-changed-timestamp)
12191 (defvar org-last-inserted-timestamp)
12192 (defvar org-log-post-message)
12193 (defvar org-log-note-purpose)
12194 (defvar org-log-note-how)
12195 (defvar org-log-note-extra)
12196 (defun org-auto-repeat-maybe (done-word)
12197 "Check if the current headline contains a repeated deadline/schedule.
12198 If yes, set TODO state back to what it was and change the base date
12199 of repeating deadline/scheduled time stamps to new date.
12200 This function is run automatically after each state change to a DONE state."
12201 ;; last-state is dynamically scoped into this function
12202 (let* ((repeat (org-get-repeat))
12203 (aa (assoc org-last-state org-todo-kwd-alist))
12204 (interpret (nth 1 aa))
12205 (head (nth 2 aa))
12206 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12207 (msg "Entry repeats: ")
12208 (org-log-done nil)
12209 (org-todo-log-states nil)
12210 re type n what ts time to-state)
12211 (when repeat
12212 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12213 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12214 org-todo-repeat-to-state))
12215 (unless (and to-state (member to-state org-todo-keywords-1))
12216 (setq to-state (if (eq interpret 'type) org-last-state head)))
12217 (org-todo to-state)
12218 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12219 (org-entry-put nil "LAST_REPEAT" (format-time-string
12220 (org-time-stamp-format t t))))
12221 (when org-log-repeat
12222 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12223 (memq 'org-add-log-note post-command-hook))
12224 ;; OK, we are already setup for some record
12225 (if (eq org-log-repeat 'note)
12226 ;; make sure we take a note, not only a time stamp
12227 (setq org-log-note-how 'note))
12228 ;; Set up for taking a record
12229 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12230 org-last-state
12231 'findpos org-log-repeat)))
12232 (org-back-to-heading t)
12233 (org-add-planning-info nil nil 'closed)
12234 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12235 org-deadline-time-regexp "\\)\\|\\("
12236 org-ts-regexp "\\)"))
12237 (while (re-search-forward
12238 re (save-excursion (outline-next-heading) (point)) t)
12239 (setq type (if (match-end 1) org-scheduled-string
12240 (if (match-end 3) org-deadline-string "Plain:"))
12241 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12242 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12243 (setq n (string-to-number (match-string 2 ts))
12244 what (match-string 3 ts))
12245 (if (equal what "w") (setq n (* n 7) what "d"))
12246 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12247 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12248 ;; Preparation, see if we need to modify the start date for the change
12249 (when (match-end 1)
12250 (setq time (save-match-data (org-time-string-to-time ts)))
12251 (cond
12252 ((equal (match-string 1 ts) ".")
12253 ;; Shift starting date to today
12254 (org-timestamp-change
12255 (- (org-today) (time-to-days time))
12256 'day))
12257 ((equal (match-string 1 ts) "+")
12258 (let ((nshiftmax 10) (nshift 0))
12259 (while (or (= nshift 0)
12260 (<= (time-to-days time)
12261 (time-to-days (current-time))))
12262 (when (= (incf nshift) nshiftmax)
12263 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12264 (error "Abort")))
12265 (org-timestamp-change n (cdr (assoc what whata)))
12266 (org-at-timestamp-p t)
12267 (setq ts (match-string 1))
12268 (setq time (save-match-data (org-time-string-to-time ts)))))
12269 (org-timestamp-change (- n) (cdr (assoc what whata)))
12270 ;; rematch, so that we have everything in place for the real shift
12271 (org-at-timestamp-p t)
12272 (setq ts (match-string 1))
12273 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12274 (org-timestamp-change n (cdr (assoc what whata)))
12275 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12276 (setq org-log-post-message msg)
12277 (message "%s" msg))))
12279 (defun org-show-todo-tree (arg)
12280 "Make a compact tree which shows all headlines marked with TODO.
12281 The tree will show the lines where the regexp matches, and all higher
12282 headlines above the match.
12283 With a \\[universal-argument] prefix, prompt for a regexp to match.
12284 With a numeric prefix N, construct a sparse tree for the Nth element
12285 of `org-todo-keywords-1'."
12286 (interactive "P")
12287 (let ((case-fold-search nil)
12288 (kwd-re
12289 (cond ((null arg) org-not-done-regexp)
12290 ((equal arg '(4))
12291 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12292 (mapcar 'list org-todo-keywords-1))))
12293 (concat "\\("
12294 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12295 "\\)\\>")))
12296 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12297 (regexp-quote (nth (1- (prefix-numeric-value arg))
12298 org-todo-keywords-1)))
12299 (t (error "Invalid prefix argument: %s" arg)))))
12300 (message "%d TODO entries found"
12301 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12303 (defun org-deadline (&optional remove time)
12304 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12305 With argument REMOVE, remove any deadline from the item.
12306 With argument TIME, set the deadline at the corresponding date. TIME
12307 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12308 (interactive "P")
12309 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12310 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12311 'region-start-level 'region))
12312 org-loop-over-headlines-in-active-region)
12313 (org-map-entries
12314 `(org-deadline ',remove ,time)
12315 org-loop-over-headlines-in-active-region
12316 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12317 (let* ((old-date (org-entry-get nil "DEADLINE"))
12318 (repeater (and old-date
12319 (string-match
12320 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12321 old-date)
12322 (match-string 1 old-date))))
12323 (if remove
12324 (progn
12325 (when (and old-date org-log-redeadline)
12326 (org-add-log-setup 'deldeadline nil old-date 'findpos
12327 org-log-redeadline))
12328 (org-remove-timestamp-with-keyword org-deadline-string)
12329 (message "Item no longer has a deadline."))
12330 (org-add-planning-info 'deadline time 'closed)
12331 (when (and old-date org-log-redeadline
12332 (not (equal old-date
12333 (substring org-last-inserted-timestamp 1 -1))))
12334 (org-add-log-setup 'redeadline nil old-date 'findpos
12335 org-log-redeadline))
12336 (when repeater
12337 (save-excursion
12338 (org-back-to-heading t)
12339 (when (re-search-forward (concat org-deadline-string " "
12340 org-last-inserted-timestamp)
12341 (save-excursion
12342 (outline-next-heading) (point)) t)
12343 (goto-char (1- (match-end 0)))
12344 (insert " " repeater)
12345 (setq org-last-inserted-timestamp
12346 (concat (substring org-last-inserted-timestamp 0 -1)
12347 " " repeater
12348 (substring org-last-inserted-timestamp -1))))))
12349 (message "Deadline on %s" org-last-inserted-timestamp)))))
12351 (defun org-schedule (&optional remove time)
12352 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12353 With argument REMOVE, remove any scheduling date from the item.
12354 With argument TIME, scheduled at the corresponding date. TIME can
12355 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12356 (interactive "P")
12357 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12358 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12359 'region-start-level 'region))
12360 org-loop-over-headlines-in-active-region)
12361 (org-map-entries
12362 `(org-schedule ',remove ,time)
12363 org-loop-over-headlines-in-active-region
12364 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12365 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12366 (repeater (and old-date
12367 (string-match
12368 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12369 old-date)
12370 (match-string 1 old-date))))
12371 (if remove
12372 (progn
12373 (when (and old-date org-log-reschedule)
12374 (org-add-log-setup 'delschedule nil old-date 'findpos
12375 org-log-reschedule))
12376 (org-remove-timestamp-with-keyword org-scheduled-string)
12377 (message "Item is no longer scheduled."))
12378 (org-add-planning-info 'scheduled time 'closed)
12379 (when (and old-date org-log-reschedule
12380 (not (equal old-date
12381 (substring org-last-inserted-timestamp 1 -1))))
12382 (org-add-log-setup 'reschedule nil old-date 'findpos
12383 org-log-reschedule))
12384 (when repeater
12385 (save-excursion
12386 (org-back-to-heading t)
12387 (when (re-search-forward (concat org-scheduled-string " "
12388 org-last-inserted-timestamp)
12389 (save-excursion
12390 (outline-next-heading) (point)) t)
12391 (goto-char (1- (match-end 0)))
12392 (insert " " repeater)
12393 (setq org-last-inserted-timestamp
12394 (concat (substring org-last-inserted-timestamp 0 -1)
12395 " " repeater
12396 (substring org-last-inserted-timestamp -1))))))
12397 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12399 (defun org-get-scheduled-time (pom &optional inherit)
12400 "Get the scheduled time as a time tuple, of a format suitable
12401 for calling org-schedule with, or if there is no scheduling,
12402 returns nil."
12403 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12404 (when time
12405 (apply 'encode-time (org-parse-time-string time)))))
12407 (defun org-get-deadline-time (pom &optional inherit)
12408 "Get the deadline as a time tuple, of a format suitable for
12409 calling org-deadline with, or if there is no scheduling, returns
12410 nil."
12411 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12412 (when time
12413 (apply 'encode-time (org-parse-time-string time)))))
12415 (defun org-remove-timestamp-with-keyword (keyword)
12416 "Remove all time stamps with KEYWORD in the current entry."
12417 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12418 beg)
12419 (save-excursion
12420 (org-back-to-heading t)
12421 (setq beg (point))
12422 (outline-next-heading)
12423 (while (re-search-backward re beg t)
12424 (replace-match "")
12425 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12426 (equal (char-before) ?\ ))
12427 (backward-delete-char 1)
12428 (if (string-match "^[ \t]*$" (buffer-substring
12429 (point-at-bol) (point-at-eol)))
12430 (delete-region (point-at-bol)
12431 (min (point-max) (1+ (point-at-eol))))))))))
12433 (defun org-add-planning-info (what &optional time &rest remove)
12434 "Insert new timestamp with keyword in the line directly after the headline.
12435 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12436 If non is given, the user is prompted for a date.
12437 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12438 be removed."
12439 (interactive)
12440 (let (org-time-was-given org-end-time-was-given ts
12441 end default-time default-input)
12443 (catch 'exit
12444 (when (and (memq what '(scheduled deadline))
12445 (or (not time)
12446 (and (stringp time)
12447 (string-match "^[-+]+[0-9]" time))))
12448 ;; Try to get a default date/time from existing timestamp
12449 (save-excursion
12450 (org-back-to-heading t)
12451 (setq end (save-excursion (outline-next-heading) (point)))
12452 (when (re-search-forward (if (eq what 'scheduled)
12453 org-scheduled-time-regexp
12454 org-deadline-time-regexp)
12455 end t)
12456 (setq ts (match-string 1)
12457 default-time
12458 (apply 'encode-time (org-parse-time-string ts))
12459 default-input (and ts (org-get-compact-tod ts))))))
12460 (when what
12461 (setq time
12462 (if (stringp time)
12463 ;; This is a string (relative or absolute), set proper date
12464 (apply 'encode-time
12465 (org-read-date-analyze
12466 time default-time (decode-time default-time)))
12467 ;; If necessary, get the time from the user
12468 (or time (org-read-date nil 'to-time nil nil
12469 default-time default-input)))))
12471 (when (and org-insert-labeled-timestamps-at-point
12472 (member what '(scheduled deadline)))
12473 (insert
12474 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12475 (org-insert-time-stamp time org-time-was-given
12476 nil nil nil (list org-end-time-was-given))
12477 (setq what nil))
12478 (save-excursion
12479 (save-restriction
12480 (let (col list elt ts buffer-invisibility-spec)
12481 (org-back-to-heading t)
12482 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12483 (goto-char (match-end 1))
12484 (setq col (current-column))
12485 (goto-char (match-end 0))
12486 (if (eobp) (insert "\n") (forward-char 1))
12487 (when (and (not what)
12488 (not (looking-at
12489 (concat "[ \t]*"
12490 org-keyword-time-not-clock-regexp))))
12491 ;; Nothing to add, nothing to remove...... :-)
12492 (throw 'exit nil))
12493 (if (and (not (looking-at org-outline-regexp))
12494 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12495 "[^\r\n]*"))
12496 (not (equal (match-string 1) org-clock-string)))
12497 (narrow-to-region (match-beginning 0) (match-end 0))
12498 (insert-before-markers "\n")
12499 (backward-char 1)
12500 (narrow-to-region (point) (point))
12501 (and org-adapt-indentation (org-indent-to-column col)))
12502 ;; Check if we have to remove something.
12503 (setq list (cons what remove))
12504 (while list
12505 (setq elt (pop list))
12506 (when (or (and (eq elt 'scheduled)
12507 (re-search-forward org-scheduled-time-regexp nil t))
12508 (and (eq elt 'deadline)
12509 (re-search-forward org-deadline-time-regexp nil t))
12510 (and (eq elt 'closed)
12511 (re-search-forward org-closed-time-regexp nil t)))
12512 (replace-match "")
12513 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12514 (and (looking-at "[ \t]+") (replace-match ""))
12515 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12516 (when what
12517 (insert
12518 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12519 (cond ((eq what 'scheduled) org-scheduled-string)
12520 ((eq what 'deadline) org-deadline-string)
12521 ((eq what 'closed) org-closed-string))
12522 " ")
12523 (setq ts (org-insert-time-stamp
12524 time
12525 (or org-time-was-given
12526 (and (eq what 'closed) org-log-done-with-time))
12527 (eq what 'closed)
12528 nil nil (list org-end-time-was-given)))
12529 (insert
12530 (if (not (or (bolp) (eq (char-before) ?\ )
12531 (memq (char-after) '(32 10))
12532 (eobp))) " " ""))
12533 (end-of-line 1))
12534 (goto-char (point-min))
12535 (widen)
12536 (if (and (looking-at "[ \t]*\n")
12537 (equal (char-before) ?\n))
12538 (delete-region (1- (point)) (point-at-eol)))
12539 ts))))))
12541 (defvar org-log-note-marker (make-marker))
12542 (defvar org-log-note-purpose nil)
12543 (defvar org-log-note-state nil)
12544 (defvar org-log-note-previous-state nil)
12545 (defvar org-log-note-how nil)
12546 (defvar org-log-note-extra nil)
12547 (defvar org-log-note-window-configuration nil)
12548 (defvar org-log-note-return-to (make-marker))
12549 (defvar org-log-note-effective-time nil
12550 "Remembered current time so that dynamically scoped
12551 `org-extend-today-until' affects tha timestamps in state change
12552 log")
12554 (defvar org-log-post-message nil
12555 "Message to be displayed after a log note has been stored.
12556 The auto-repeater uses this.")
12558 (defun org-add-note ()
12559 "Add a note to the current entry.
12560 This is done in the same way as adding a state change note."
12561 (interactive)
12562 (org-add-log-setup 'note nil nil 'findpos nil))
12564 (defvar org-property-end-re)
12565 (defun org-add-log-setup (&optional purpose state prev-state
12566 findpos how extra)
12567 "Set up the post command hook to take a note.
12568 If this is about to TODO state change, the new state is expected in STATE.
12569 When FINDPOS is non-nil, find the correct position for the note in
12570 the current entry. If not, assume that it can be inserted at point.
12571 HOW is an indicator what kind of note should be created.
12572 EXTRA is additional text that will be inserted into the notes buffer."
12573 (let* ((org-log-into-drawer (org-log-into-drawer))
12574 (drawer (cond ((stringp org-log-into-drawer)
12575 org-log-into-drawer)
12576 (org-log-into-drawer "LOGBOOK"))))
12577 (save-restriction
12578 (save-excursion
12579 (when findpos
12580 (org-back-to-heading t)
12581 (narrow-to-region (point) (save-excursion
12582 (outline-next-heading) (point)))
12583 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12584 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12585 "[^\r\n]*\\)?"))
12586 (goto-char (match-end 0))
12587 (cond
12588 (drawer
12589 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12590 nil t)
12591 (progn
12592 (goto-char (match-end 0))
12593 (or org-log-states-order-reversed
12594 (and (re-search-forward org-property-end-re nil t)
12595 (goto-char (1- (match-beginning 0))))))
12596 (insert "\n:" drawer ":\n:END:")
12597 (beginning-of-line 0)
12598 (org-indent-line)
12599 (beginning-of-line 2)
12600 (org-indent-line)
12601 (end-of-line 0)))
12602 ((and org-log-state-notes-insert-after-drawers
12603 (save-excursion
12604 (forward-line) (looking-at org-drawer-regexp)))
12605 (forward-line)
12606 (while (looking-at org-drawer-regexp)
12607 (goto-char (match-end 0))
12608 (re-search-forward org-property-end-re (point-max) t)
12609 (forward-line))
12610 (forward-line -1)))
12611 (unless org-log-states-order-reversed
12612 (and (= (char-after) ?\n) (forward-char 1))
12613 (org-skip-over-state-notes)
12614 (skip-chars-backward " \t\n\r")))
12615 (move-marker org-log-note-marker (point))
12616 (setq org-log-note-purpose purpose
12617 org-log-note-state state
12618 org-log-note-previous-state prev-state
12619 org-log-note-how how
12620 org-log-note-extra extra
12621 org-log-note-effective-time (org-current-effective-time))
12622 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12624 (defun org-skip-over-state-notes ()
12625 "Skip past the list of State notes in an entry."
12626 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12627 (when (ignore-errors (goto-char (org-in-item-p)))
12628 (let* ((struct (org-list-struct))
12629 (prevs (org-list-prevs-alist struct)))
12630 (while (looking-at "[ \t]*- State")
12631 (goto-char (or (org-list-get-next-item (point) struct prevs)
12632 (org-list-get-item-end (point) struct)))))))
12634 (defun org-add-log-note (&optional purpose)
12635 "Pop up a window for taking a note, and add this note later at point."
12636 (remove-hook 'post-command-hook 'org-add-log-note)
12637 (setq org-log-note-window-configuration (current-window-configuration))
12638 (delete-other-windows)
12639 (move-marker org-log-note-return-to (point))
12640 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12641 (goto-char org-log-note-marker)
12642 (org-switch-to-buffer-other-window "*Org Note*")
12643 (erase-buffer)
12644 (if (memq org-log-note-how '(time state))
12645 (let (current-prefix-arg) (org-store-log-note))
12646 (let ((org-inhibit-startup t)) (org-mode))
12647 (insert (format "# Insert note for %s.
12648 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12649 (cond
12650 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12651 ((eq org-log-note-purpose 'done) "closed todo item")
12652 ((eq org-log-note-purpose 'state)
12653 (format "state change from \"%s\" to \"%s\""
12654 (or org-log-note-previous-state "")
12655 (or org-log-note-state "")))
12656 ((eq org-log-note-purpose 'reschedule)
12657 "rescheduling")
12658 ((eq org-log-note-purpose 'delschedule)
12659 "no longer scheduled")
12660 ((eq org-log-note-purpose 'redeadline)
12661 "changing deadline")
12662 ((eq org-log-note-purpose 'deldeadline)
12663 "removing deadline")
12664 ((eq org-log-note-purpose 'refile)
12665 "refiling")
12666 ((eq org-log-note-purpose 'note)
12667 "this entry")
12668 (t (error "This should not happen")))))
12669 (if org-log-note-extra (insert org-log-note-extra))
12670 (org-set-local 'org-finish-function 'org-store-log-note)
12671 (run-hooks 'org-log-buffer-setup-hook)))
12673 (defvar org-note-abort nil) ; dynamically scoped
12674 (defun org-store-log-note ()
12675 "Finish taking a log note, and insert it to where it belongs."
12676 (let ((txt (buffer-string))
12677 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12678 lines ind bul)
12679 (kill-buffer (current-buffer))
12680 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12681 (setq txt (replace-match "" t t txt)))
12682 (if (string-match "\\s-+\\'" txt)
12683 (setq txt (replace-match "" t t txt)))
12684 (setq lines (org-split-string txt "\n"))
12685 (when (and note (string-match "\\S-" note))
12686 (setq note
12687 (org-replace-escapes
12688 note
12689 (list (cons "%u" (user-login-name))
12690 (cons "%U" user-full-name)
12691 (cons "%t" (format-time-string
12692 (org-time-stamp-format 'long 'inactive)
12693 org-log-note-effective-time))
12694 (cons "%T" (format-time-string
12695 (org-time-stamp-format 'long nil)
12696 org-log-note-effective-time))
12697 (cons "%d" (format-time-string
12698 (org-time-stamp-format nil 'inactive)
12699 org-log-note-effective-time))
12700 (cons "%D" (format-time-string
12701 (org-time-stamp-format nil nil)
12702 org-log-note-effective-time))
12703 (cons "%s" (if org-log-note-state
12704 (concat "\"" org-log-note-state "\"")
12705 ""))
12706 (cons "%S" (if org-log-note-previous-state
12707 (concat "\"" org-log-note-previous-state "\"")
12708 "\"\"")))))
12709 (if lines (setq note (concat note " \\\\")))
12710 (push note lines))
12711 (when (or current-prefix-arg org-note-abort)
12712 (when org-log-into-drawer
12713 (org-remove-empty-drawer-at
12714 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12715 org-log-note-marker))
12716 (setq lines nil))
12717 (when lines
12718 (with-current-buffer (marker-buffer org-log-note-marker)
12719 (save-excursion
12720 (goto-char org-log-note-marker)
12721 (move-marker org-log-note-marker nil)
12722 (end-of-line 1)
12723 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12724 (setq ind (save-excursion
12725 (if (ignore-errors (goto-char (org-in-item-p)))
12726 (let ((struct (org-list-struct)))
12727 (org-list-get-ind
12728 (org-list-get-top-point struct) struct))
12729 (skip-chars-backward " \r\t\n")
12730 (cond
12731 ((and (org-at-heading-p)
12732 org-adapt-indentation)
12733 (1+ (org-current-level)))
12734 ((org-at-heading-p) 0)
12735 (t (org-get-indentation))))))
12736 (setq bul (org-list-bullet-string "-"))
12737 (org-indent-line-to ind)
12738 (insert bul (pop lines))
12739 (let ((ind-body (+ (length bul) ind)))
12740 (while lines
12741 (insert "\n")
12742 (org-indent-line-to ind-body)
12743 (insert (pop lines))))
12744 (message "Note stored")
12745 (org-back-to-heading t)
12746 (org-cycle-hide-drawers 'children)))))
12747 (set-window-configuration org-log-note-window-configuration)
12748 (with-current-buffer (marker-buffer org-log-note-return-to)
12749 (goto-char org-log-note-return-to))
12750 (move-marker org-log-note-return-to nil)
12751 (and org-log-post-message (message "%s" org-log-post-message)))
12753 (defun org-remove-empty-drawer-at (drawer pos)
12754 "Remove an empty drawer DRAWER at position POS.
12755 POS may also be a marker."
12756 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12757 (save-excursion
12758 (save-restriction
12759 (widen)
12760 (goto-char pos)
12761 (if (org-in-regexp
12762 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12763 (replace-match ""))))))
12765 (defvar org-ts-type nil)
12766 (defun org-sparse-tree (&optional arg type)
12767 "Create a sparse tree, prompt for the details.
12768 This command can create sparse trees. You first need to select the type
12769 of match used to create the tree:
12771 t Show all TODO entries.
12772 T Show entries with a specific TODO keyword.
12773 m Show entries selected by a tags/property match.
12774 p Enter a property name and its value (both with completion on existing
12775 names/values) and show entries with that property.
12776 r Show entries matching a regular expression (`/' can be used as well).
12777 b Show deadlines and scheduled items before a date.
12778 a Show deadlines and scheduled items after a date.
12779 d Show deadlines due within `org-deadline-warning-days'.
12780 D Show deadlines and scheduled items between a date range."
12781 (interactive "P")
12782 (let (ans kwd value ts-type)
12783 (setq type (or type org-sparse-tree-default-date-type))
12784 (setq org-ts-type type)
12785 (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"
12786 (cond ((eq type 'all) "all timestamps")
12787 ((eq type 'scheduled) "only scheduled")
12788 ((eq type 'deadline) "only deadline")
12789 ((eq type 'active) "only active timestamps")
12790 ((eq type 'inactive) "only inactive timestamps")
12791 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12792 (t "scheduled/deadline")))
12793 (setq ans (read-char-exclusive))
12794 (cond
12795 ((equal ans ?c)
12796 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12797 ((equal ans ?d)
12798 (call-interactively 'org-check-deadlines))
12799 ((equal ans ?b)
12800 (call-interactively 'org-check-before-date))
12801 ((equal ans ?a)
12802 (call-interactively 'org-check-after-date))
12803 ((equal ans ?D)
12804 (call-interactively 'org-check-dates-range))
12805 ((equal ans ?t)
12806 (org-show-todo-tree nil))
12807 ((equal ans ?T)
12808 (org-show-todo-tree '(4)))
12809 ((member ans '(?T ?m))
12810 (call-interactively 'org-match-sparse-tree))
12811 ((member ans '(?p ?P))
12812 (setq kwd (org-icompleting-read "Property: "
12813 (mapcar 'list (org-buffer-property-keys))))
12814 (setq value (org-icompleting-read "Value: "
12815 (mapcar 'list (org-property-values kwd))))
12816 (unless (string-match "\\`{.*}\\'" value)
12817 (setq value (concat "\"" value "\"")))
12818 (org-match-sparse-tree arg (concat kwd "=" value)))
12819 ((member ans '(?r ?R ?/))
12820 (call-interactively 'org-occur))
12821 (t (error "No such sparse tree command \"%c\"" ans)))))
12823 (defvar org-occur-highlights nil
12824 "List of overlays used for occur matches.")
12825 (make-variable-buffer-local 'org-occur-highlights)
12826 (defvar org-occur-parameters nil
12827 "Parameters of the active org-occur calls.
12828 This is a list, each call to org-occur pushes as cons cell,
12829 containing the regular expression and the callback, onto the list.
12830 The list can contain several entries if `org-occur' has been called
12831 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12832 will only contain one set of parameters. When the highlights are
12833 removed (for example with `C-c C-c', or with the next edit (depending
12834 on `org-remove-highlights-with-change'), this variable is emptied
12835 as well.")
12836 (make-variable-buffer-local 'org-occur-parameters)
12838 (defun org-occur (regexp &optional keep-previous callback)
12839 "Make a compact tree which shows all matches of REGEXP.
12840 The tree will show the lines where the regexp matches, and all higher
12841 headlines above the match. It will also show the heading after the match,
12842 to make sure editing the matching entry is easy.
12843 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12844 call to `org-occur' will be kept, to allow stacking of calls to this
12845 command.
12846 If CALLBACK is non-nil, it is a function which is called to confirm
12847 that the match should indeed be shown."
12848 (interactive "sRegexp: \nP")
12849 (when (equal regexp "")
12850 (error "Regexp cannot be empty"))
12851 (unless keep-previous
12852 (org-remove-occur-highlights nil nil t))
12853 (push (cons regexp callback) org-occur-parameters)
12854 (let ((cnt 0))
12855 (save-excursion
12856 (goto-char (point-min))
12857 (if (or (not keep-previous) ; do not want to keep
12858 (not org-occur-highlights)) ; no previous matches
12859 ;; hide everything
12860 (org-overview))
12861 (while (re-search-forward regexp nil t)
12862 (when (or (not callback)
12863 (save-match-data (funcall callback)))
12864 (setq cnt (1+ cnt))
12865 (when org-highlight-sparse-tree-matches
12866 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12867 (org-show-context 'occur-tree))))
12868 (when org-remove-highlights-with-change
12869 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12870 nil 'local))
12871 (unless org-sparse-tree-open-archived-trees
12872 (org-hide-archived-subtrees (point-min) (point-max)))
12873 (run-hooks 'org-occur-hook)
12874 (if (org-called-interactively-p 'interactive)
12875 (message "%d match(es) for regexp %s" cnt regexp))
12876 cnt))
12878 (defun org-occur-next-match (&optional n reset)
12879 "Function for `next-error-function' to find sparse tree matches.
12880 N is the number of matches to move, when negative move backwards.
12881 RESET is entirely ignored - this function always goes back to the
12882 starting point when no match is found."
12883 (let* ((limit (if (< n 0) (point-min) (point-max)))
12884 (search-func (if (< n 0)
12885 'previous-single-char-property-change
12886 'next-single-char-property-change))
12887 (n (abs n))
12888 (pos (point))
12890 (catch 'exit
12891 (while (setq p1 (funcall search-func (point) 'org-type))
12892 (when (equal p1 limit)
12893 (goto-char pos)
12894 (error "No more matches"))
12895 (when (equal (get-char-property p1 'org-type) 'org-occur)
12896 (setq n (1- n))
12897 (when (= n 0)
12898 (goto-char p1)
12899 (throw 'exit (point))))
12900 (goto-char p1))
12901 (goto-char p1)
12902 (error "No more matches"))))
12904 (defun org-show-context (&optional key)
12905 "Make sure point and context are visible.
12906 How much context is shown depends upon the variables
12907 `org-show-hierarchy-above', `org-show-following-heading',
12908 `org-show-entry-below' and `org-show-siblings'."
12909 (let ((heading-p (org-at-heading-p t))
12910 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12911 (following-p (org-get-alist-option org-show-following-heading key))
12912 (entry-p (org-get-alist-option org-show-entry-below key))
12913 (siblings-p (org-get-alist-option org-show-siblings key)))
12914 (catch 'exit
12915 ;; Show heading or entry text
12916 (if (and heading-p (not entry-p))
12917 (org-flag-heading nil) ; only show the heading
12918 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12919 (org-show-hidden-entry))) ; show entire entry
12920 (when following-p
12921 ;; Show next sibling, or heading below text
12922 (save-excursion
12923 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12924 (org-flag-heading nil))))
12925 (when siblings-p (org-show-siblings))
12926 (when hierarchy-p
12927 ;; show all higher headings, possibly with siblings
12928 (save-excursion
12929 (while (and (condition-case nil
12930 (progn (org-up-heading-all 1) t)
12931 (error nil))
12932 (not (bobp)))
12933 (org-flag-heading nil)
12934 (when siblings-p (org-show-siblings))))))))
12936 (defvar org-reveal-start-hook nil
12937 "Hook run before revealing a location.")
12939 (defun org-reveal (&optional siblings)
12940 "Show current entry, hierarchy above it, and the following headline.
12941 This can be used to show a consistent set of context around locations
12942 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12943 not t for the search context.
12945 With optional argument SIBLINGS, on each level of the hierarchy all
12946 siblings are shown. This repairs the tree structure to what it would
12947 look like when opened with hierarchical calls to `org-cycle'.
12948 With double optional argument \\[universal-argument] \\[universal-argument], \
12949 go to the parent and show the
12950 entire tree."
12951 (interactive "P")
12952 (run-hooks 'org-reveal-start-hook)
12953 (let ((org-show-hierarchy-above t)
12954 (org-show-following-heading t)
12955 (org-show-siblings (if siblings t org-show-siblings)))
12956 (org-show-context nil))
12957 (when (equal siblings '(16))
12958 (save-excursion
12959 (when (org-up-heading-safe)
12960 (org-show-subtree)
12961 (run-hook-with-args 'org-cycle-hook 'subtree)))))
12963 (defun org-highlight-new-match (beg end)
12964 "Highlight from BEG to END and mark the highlight is an occur headline."
12965 (let ((ov (make-overlay beg end)))
12966 (overlay-put ov 'face 'secondary-selection)
12967 (overlay-put ov 'org-type 'org-occur)
12968 (push ov org-occur-highlights)))
12970 (defun org-remove-occur-highlights (&optional beg end noremove)
12971 "Remove the occur highlights from the buffer.
12972 BEG and END are ignored. If NOREMOVE is nil, remove this function
12973 from the `before-change-functions' in the current buffer."
12974 (interactive)
12975 (unless org-inhibit-highlight-removal
12976 (mapc 'delete-overlay org-occur-highlights)
12977 (setq org-occur-highlights nil)
12978 (setq org-occur-parameters nil)
12979 (unless noremove
12980 (remove-hook 'before-change-functions
12981 'org-remove-occur-highlights 'local))))
12983 ;;;; Priorities
12985 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12986 "Regular expression matching the priority indicator.")
12988 (defvar org-remove-priority-next-time nil)
12990 (defun org-priority-up ()
12991 "Increase the priority of the current item."
12992 (interactive)
12993 (org-priority 'up))
12995 (defun org-priority-down ()
12996 "Decrease the priority of the current item."
12997 (interactive)
12998 (org-priority 'down))
13000 (defun org-priority (&optional action)
13001 "Change the priority of an item.
13002 ACTION can be `set', `up', `down', or a character."
13003 (interactive)
13004 (unless org-enable-priority-commands
13005 (error "Priority commands are disabled"))
13006 (setq action (or action 'set))
13007 (let (current new news have remove)
13008 (save-excursion
13009 (org-back-to-heading t)
13010 (if (looking-at org-priority-regexp)
13011 (setq current (string-to-char (match-string 2))
13012 have t))
13013 (cond
13014 ((eq action 'remove)
13015 (setq remove t new ?\ ))
13016 ((or (eq action 'set)
13017 (if (featurep 'xemacs) (characterp action) (integerp action)))
13018 (if (not (eq action 'set))
13019 (setq new action)
13020 (message "Priority %c-%c, SPC to remove: "
13021 org-highest-priority org-lowest-priority)
13022 (save-match-data
13023 (setq new (read-char-exclusive))))
13024 (if (and (= (upcase org-highest-priority) org-highest-priority)
13025 (= (upcase org-lowest-priority) org-lowest-priority))
13026 (setq new (upcase new)))
13027 (cond ((equal new ?\ ) (setq remove t))
13028 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13029 (error "Priority must be between `%c' and `%c'"
13030 org-highest-priority org-lowest-priority))))
13031 ((eq action 'up)
13032 (setq new (if have
13033 (1- current) ; normal cycling
13034 ;; last priority was empty
13035 (if (eq last-command this-command)
13036 org-lowest-priority ; wrap around empty to lowest
13037 ;; default
13038 (if org-priority-start-cycle-with-default
13039 org-default-priority
13040 (1- org-default-priority))))))
13041 ((eq action 'down)
13042 (setq new (if have
13043 (1+ current) ; normal cycling
13044 ;; last priority was empty
13045 (if (eq last-command this-command)
13046 org-highest-priority ; wrap around empty to highest
13047 ;; default
13048 (if org-priority-start-cycle-with-default
13049 org-default-priority
13050 (1+ org-default-priority))))))
13051 (t (error "Invalid action")))
13052 (if (or (< (upcase new) org-highest-priority)
13053 (> (upcase new) org-lowest-priority))
13054 (if (and (memq action '(up down))
13055 (not have) (not (eq last-command this-command)))
13056 ;; `new' is from default priority
13057 (error
13058 "The default can not be set, see `org-default-priority' why")
13059 ;; normal cycling: `new' is beyond highest/lowest priority
13060 ;; and is wrapped around to the empty priority
13061 (setq remove t)))
13062 (setq news (format "%c" new))
13063 (if have
13064 (if remove
13065 (replace-match "" t t nil 1)
13066 (replace-match news t t nil 2))
13067 (if remove
13068 (error "No priority cookie found in line")
13069 (let ((case-fold-search nil))
13070 (looking-at org-todo-line-regexp))
13071 (if (match-end 2)
13072 (progn
13073 (goto-char (match-end 2))
13074 (insert " [#" news "]"))
13075 (goto-char (match-beginning 3))
13076 (insert "[#" news "] "))))
13077 (org-preserve-lc (org-set-tags nil 'align)))
13078 (if remove
13079 (message "Priority removed")
13080 (message "Priority of current item set to %s" news))))
13082 (defun org-get-priority (s)
13083 "Find priority cookie and return priority."
13084 (if (functionp org-get-priority-function)
13085 (funcall org-get-priority-function)
13086 (save-match-data
13087 (if (not (string-match org-priority-regexp s))
13088 (* 1000 (- org-lowest-priority org-default-priority))
13089 (* 1000 (- org-lowest-priority
13090 (string-to-char (match-string 2 s))))))))
13092 ;;;; Tags
13094 (defvar org-agenda-archives-mode)
13095 (defvar org-map-continue-from nil
13096 "Position from where mapping should continue.
13097 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13099 (defvar org-scanner-tags nil
13100 "The current tag list while the tags scanner is running.")
13101 (defvar org-trust-scanner-tags nil
13102 "Should `org-get-tags-at' use the tags for the scanner.
13103 This is for internal dynamical scoping only.
13104 When this is non-nil, the function `org-get-tags-at' will return the value
13105 of `org-scanner-tags' instead of building the list by itself. This
13106 can lead to large speed-ups when the tags scanner is used in a file with
13107 many entries, and when the list of tags is retrieved, for example to
13108 obtain a list of properties. Building the tags list for each entry in such
13109 a file becomes an N^2 operation - but with this variable set, it scales
13110 as N.")
13112 (defun org-scan-tags (action matcher todo-only &optional start-level)
13113 "Scan headline tags with inheritance and produce output ACTION.
13115 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13116 or `agenda' to produce an entry list for an agenda view. It can also be
13117 a Lisp form or a function that should be called at each matched headline, in
13118 this case the return value is a list of all return values from these calls.
13120 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13121 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13122 only lines with a not-done TODO keyword are included in the output.
13123 This should be the same variable that was scoped into
13124 and set by `org-make-tags-matcher' when it constructed MATCHER.
13126 START-LEVEL can be a string with asterisks, reducing the scope to
13127 headlines matching this string."
13128 (require 'org-agenda)
13129 (let* ((re (concat "^"
13130 (if start-level
13131 ;; Get the correct level to match
13132 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13133 org-outline-regexp)
13134 " *\\(\\<\\("
13135 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13136 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13137 (props (list 'face 'default
13138 'done-face 'org-agenda-done
13139 'undone-face 'default
13140 'mouse-face 'highlight
13141 'org-not-done-regexp org-not-done-regexp
13142 'org-todo-regexp org-todo-regexp
13143 'org-complex-heading-regexp org-complex-heading-regexp
13144 'help-echo
13145 (format "mouse-2 or RET jump to org file %s"
13146 (abbreviate-file-name
13147 (or (buffer-file-name (buffer-base-buffer))
13148 (buffer-name (buffer-base-buffer)))))))
13149 (case-fold-search nil)
13150 (org-map-continue-from nil)
13151 lspos tags tags-list
13152 (tags-alist (list (cons 0 org-file-tags)))
13153 (llast 0) rtn rtn1 level category i txt
13154 todo marker entry priority)
13155 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13156 (setq action (list 'lambda nil action)))
13157 (save-excursion
13158 (goto-char (point-min))
13159 (when (eq action 'sparse-tree)
13160 (org-overview)
13161 (org-remove-occur-highlights))
13162 (while (re-search-forward re nil t)
13163 (setq org-map-continue-from nil)
13164 (catch :skip
13165 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13166 tags (if (match-end 4) (org-match-string-no-properties 4)))
13167 (goto-char (setq lspos (match-beginning 0)))
13168 (setq level (org-reduced-level (funcall outline-level))
13169 category (org-get-category))
13170 (setq i llast llast level)
13171 ;; remove tag lists from same and sublevels
13172 (while (>= i level)
13173 (when (setq entry (assoc i tags-alist))
13174 (setq tags-alist (delete entry tags-alist)))
13175 (setq i (1- i)))
13176 ;; add the next tags
13177 (when tags
13178 (setq tags (org-split-string tags ":")
13179 tags-alist
13180 (cons (cons level tags) tags-alist)))
13181 ;; compile tags for current headline
13182 (setq tags-list
13183 (if org-use-tag-inheritance
13184 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13185 tags)
13186 org-scanner-tags tags-list)
13187 (when org-use-tag-inheritance
13188 (setcdr (car tags-alist)
13189 (mapcar (lambda (x)
13190 (setq x (copy-sequence x))
13191 (org-add-prop-inherited x))
13192 (cdar tags-alist))))
13193 (when (and tags org-use-tag-inheritance
13194 (or (not (eq t org-use-tag-inheritance))
13195 org-tags-exclude-from-inheritance))
13196 ;; selective inheritance, remove uninherited ones
13197 (setcdr (car tags-alist)
13198 (org-remove-uninherited-tags (cdar tags-alist))))
13199 (when (and
13201 ;; eval matcher only when the todo condition is OK
13202 (and (or (not todo-only) (member todo org-not-done-keywords))
13203 (let ((case-fold-search t) (org-trust-scanner-tags t))
13204 (eval matcher)))
13206 ;; Call the skipper, but return t if it does not skip,
13207 ;; so that the `and' form continues evaluating
13208 (progn
13209 (unless (eq action 'sparse-tree) (org-agenda-skip))
13212 ;; Check if timestamps are deselecting this entry
13213 (or (not todo-only)
13214 (and (member todo org-not-done-keywords)
13215 (or (not org-agenda-tags-todo-honor-ignore-options)
13216 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13218 ;; Extra check for the archive tag
13219 ;; FIXME: Does the skipper already do this????
13221 (not (member org-archive-tag tags-list))
13222 ;; we have an archive tag, should we use this anyway?
13223 (or (not org-agenda-skip-archived-trees)
13224 (and (eq action 'agenda) org-agenda-archives-mode))))
13226 ;; select this headline
13228 (cond
13229 ((eq action 'sparse-tree)
13230 (and org-highlight-sparse-tree-matches
13231 (org-get-heading) (match-end 0)
13232 (org-highlight-new-match
13233 (match-beginning 1) (match-end 1)))
13234 (org-show-context 'tags-tree))
13235 ((eq action 'agenda)
13236 (setq txt (org-agenda-format-item
13238 (concat
13239 (if (eq org-tags-match-list-sublevels 'indented)
13240 (make-string (1- level) ?.) "")
13241 (org-get-heading))
13242 category
13243 tags-list)
13244 priority (org-get-priority txt))
13245 (goto-char lspos)
13246 (setq marker (org-agenda-new-marker))
13247 (org-add-props txt props
13248 'org-marker marker 'org-hd-marker marker 'org-category category
13249 'todo-state todo
13250 'priority priority 'type "tagsmatch")
13251 (push txt rtn))
13252 ((functionp action)
13253 (setq org-map-continue-from nil)
13254 (save-excursion
13255 (setq rtn1 (funcall action))
13256 (push rtn1 rtn)))
13257 (t (error "Invalid action")))
13259 ;; if we are to skip sublevels, jump to end of subtree
13260 (unless org-tags-match-list-sublevels
13261 (org-end-of-subtree t)
13262 (backward-char 1))))
13263 ;; Get the correct position from where to continue
13264 (if org-map-continue-from
13265 (goto-char org-map-continue-from)
13266 (and (= (point) lspos) (end-of-line 1)))))
13267 (when (and (eq action 'sparse-tree)
13268 (not org-sparse-tree-open-archived-trees))
13269 (org-hide-archived-subtrees (point-min) (point-max)))
13270 (nreverse rtn)))
13272 (defun org-remove-uninherited-tags (tags)
13273 "Remove all tags that are not inherited from the list TAGS."
13274 (cond
13275 ((eq org-use-tag-inheritance t)
13276 (if org-tags-exclude-from-inheritance
13277 (org-delete-all org-tags-exclude-from-inheritance tags)
13278 tags))
13279 ((not org-use-tag-inheritance) nil)
13280 ((stringp org-use-tag-inheritance)
13281 (delq nil (mapcar
13282 (lambda (x)
13283 (if (and (string-match org-use-tag-inheritance x)
13284 (not (member x org-tags-exclude-from-inheritance)))
13285 x nil))
13286 tags)))
13287 ((listp org-use-tag-inheritance)
13288 (delq nil (mapcar
13289 (lambda (x)
13290 (if (member x org-use-tag-inheritance) x nil))
13291 tags)))))
13293 (defun org-match-sparse-tree (&optional todo-only match)
13294 "Create a sparse tree according to tags string MATCH.
13295 MATCH can contain positive and negative selection of tags, like
13296 \"+WORK+URGENT-WITHBOSS\".
13297 If optional argument TODO-ONLY is non-nil, only select lines that are
13298 also TODO lines."
13299 (interactive "P")
13300 (org-agenda-prepare-buffers (list (current-buffer)))
13301 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13303 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13305 (defvar org-cached-props nil)
13306 (defun org-cached-entry-get (pom property)
13307 (if (or (eq t org-use-property-inheritance)
13308 (and (stringp org-use-property-inheritance)
13309 (string-match org-use-property-inheritance property))
13310 (and (listp org-use-property-inheritance)
13311 (member property org-use-property-inheritance)))
13312 ;; Caching is not possible, check it directly
13313 (org-entry-get pom property 'inherit)
13314 ;; Get all properties, so that we can do complicated checks easily
13315 (cdr (assoc property (or org-cached-props
13316 (setq org-cached-props
13317 (org-entry-properties pom)))))))
13319 (defun org-global-tags-completion-table (&optional files)
13320 "Return the list of all tags in all agenda buffer/files.
13321 Optional FILES argument is a list of files which can be used
13322 instead of the agenda files."
13323 (save-excursion
13324 (org-uniquify
13325 (delq nil
13326 (apply 'append
13327 (mapcar
13328 (lambda (file)
13329 (set-buffer (find-file-noselect file))
13330 (append (org-get-buffer-tags)
13331 (mapcar (lambda (x) (if (stringp (car-safe x))
13332 (list (car-safe x)) nil))
13333 org-tag-alist)))
13334 (if (and files (car files))
13335 files
13336 (org-agenda-files))))))))
13338 (defun org-make-tags-matcher (match)
13339 "Create the TAGS/TODO matcher form for the selection string MATCH.
13341 The variable `todo-only' is scoped dynamically into this function.
13342 It will be set to t if the matcher restricts matching to TODO entries,
13343 otherwise will not be touched.
13345 Returns a cons of the selection string MATCH and the constructed
13346 lisp form implementing the matcher. The matcher is to be evaluated
13347 at an Org entry, with point on the headline, and returns t if the
13348 entry matches the selection string MATCH. The returned lisp form
13349 references two variables with information about the entry, which
13350 must be bound around the form's evaluation: todo, the TODO keyword
13351 at the entry (or nil of none); and tags-list, the list of all tags
13352 at the entry including inherited ones. Additionally, the category
13353 of the entry (if any) must be specified as the text property
13354 'org-category on the headline.
13356 See also `org-scan-tags'.
13358 (declare (special todo-only))
13359 (unless (boundp 'todo-only)
13360 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13361 (unless match
13362 ;; Get a new match request, with completion
13363 (let ((org-last-tags-completion-table
13364 (org-global-tags-completion-table)))
13365 (setq match (org-completing-read-no-i
13366 "Match: " 'org-tags-completion-function nil nil nil
13367 'org-tags-history))))
13369 ;; Parse the string and create a lisp form
13370 (let ((match0 match)
13371 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13372 minus tag mm
13373 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13374 orterms term orlist re-p str-p level-p level-op time-p
13375 prop-p pn pv po gv rest)
13376 (if (string-match "/+" match)
13377 ;; match contains also a todo-matching request
13378 (progn
13379 (setq tagsmatch (substring match 0 (match-beginning 0))
13380 todomatch (substring match (match-end 0)))
13381 (if (string-match "^!" todomatch)
13382 (setq todo-only t todomatch (substring todomatch 1)))
13383 (if (string-match "^\\s-*$" todomatch)
13384 (setq todomatch nil)))
13385 ;; only matching tags
13386 (setq tagsmatch match todomatch nil))
13388 ;; Make the tags matcher
13389 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13390 (setq tagsmatcher t)
13391 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13392 (while (setq term (pop orterms))
13393 (while (and (equal (substring term -1) "\\") orterms)
13394 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13395 (while (string-match re term)
13396 (setq rest (substring term (match-end 0))
13397 minus (and (match-end 1)
13398 (equal (match-string 1 term) "-"))
13399 tag (save-match-data (replace-regexp-in-string
13400 "\\\\-" "-"
13401 (match-string 2 term)))
13402 re-p (equal (string-to-char tag) ?{)
13403 level-p (match-end 4)
13404 prop-p (match-end 5)
13405 mm (cond
13406 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13407 (level-p
13408 (setq level-op (org-op-to-function (match-string 3 term)))
13409 `(,level-op level ,(string-to-number
13410 (match-string 4 term))))
13411 (prop-p
13412 (setq pn (match-string 5 term)
13413 po (match-string 6 term)
13414 pv (match-string 7 term)
13415 re-p (equal (string-to-char pv) ?{)
13416 str-p (equal (string-to-char pv) ?\")
13417 time-p (save-match-data
13418 (string-match "^\"[[<].*[]>]\"$" pv))
13419 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13420 (if time-p (setq pv (org-matcher-time pv)))
13421 (setq po (org-op-to-function po (if time-p 'time str-p)))
13422 (cond
13423 ((equal pn "CATEGORY")
13424 (setq gv '(get-text-property (point) 'org-category)))
13425 ((equal pn "TODO")
13426 (setq gv 'todo))
13428 (setq gv `(org-cached-entry-get nil ,pn))))
13429 (if re-p
13430 (if (eq po 'org<>)
13431 `(not (string-match ,pv (or ,gv "")))
13432 `(string-match ,pv (or ,gv "")))
13433 (if str-p
13434 `(,po (or ,gv "") ,pv)
13435 `(,po (string-to-number (or ,gv ""))
13436 ,(string-to-number pv) ))))
13437 (t `(member ,tag tags-list)))
13438 mm (if minus (list 'not mm) mm)
13439 term rest)
13440 (push mm tagsmatcher))
13441 (push (if (> (length tagsmatcher) 1)
13442 (cons 'and tagsmatcher)
13443 (car tagsmatcher))
13444 orlist)
13445 (setq tagsmatcher nil))
13446 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13447 (setq tagsmatcher
13448 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13449 ;; Make the todo matcher
13450 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13451 (setq todomatcher t)
13452 (setq orterms (org-split-string todomatch "|") orlist nil)
13453 (while (setq term (pop orterms))
13454 (while (string-match re term)
13455 (setq minus (and (match-end 1)
13456 (equal (match-string 1 term) "-"))
13457 kwd (match-string 2 term)
13458 re-p (equal (string-to-char kwd) ?{)
13459 term (substring term (match-end 0))
13460 mm (if re-p
13461 `(string-match ,(substring kwd 1 -1) todo)
13462 (list 'equal 'todo kwd))
13463 mm (if minus (list 'not mm) mm))
13464 (push mm todomatcher))
13465 (push (if (> (length todomatcher) 1)
13466 (cons 'and todomatcher)
13467 (car todomatcher))
13468 orlist)
13469 (setq todomatcher nil))
13470 (setq todomatcher (if (> (length orlist) 1)
13471 (cons 'or orlist) (car orlist))))
13473 ;; Return the string and lisp forms of the matcher
13474 (setq matcher (if todomatcher
13475 (list 'and tagsmatcher todomatcher)
13476 tagsmatcher))
13477 (when todo-only
13478 (setq matcher (list 'and '(member todo org-not-done-keywords)
13479 matcher)))
13480 (cons match0 matcher)))
13482 (defun org-op-to-function (op &optional stringp)
13483 "Turn an operator into the appropriate function."
13484 (setq op
13485 (cond
13486 ((equal op "<" ) '(< string< org-time<))
13487 ((equal op ">" ) '(> org-string> org-time>))
13488 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13489 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13490 ((member op '("=" "==")) '(= string= org-time=))
13491 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13492 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13494 (defun org<> (a b) (not (= a b)))
13495 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13496 (defun org-string>= (a b) (not (string< a b)))
13497 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13498 (defun org-string<> (a b) (not (string= a b)))
13499 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13500 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13501 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13502 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13503 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13504 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13505 (defun org-2ft (s)
13506 "Convert S to a floating point time.
13507 If S is already a number, just return it. If it is a string, parse
13508 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13509 (cond
13510 ((numberp s) s)
13511 ((stringp s)
13512 (condition-case nil
13513 (float-time (apply 'encode-time (org-parse-time-string s)))
13514 (error 0.)))
13515 (t 0.)))
13517 (defun org-time-today ()
13518 "Time in seconds today at 0:00.
13519 Returns the float number of seconds since the beginning of the
13520 epoch to the beginning of today (00:00)."
13521 (float-time (apply 'encode-time
13522 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13524 (defun org-matcher-time (s)
13525 "Interpret a time comparison value."
13526 (save-match-data
13527 (cond
13528 ((string= s "<now>") (float-time))
13529 ((string= s "<today>") (org-time-today))
13530 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13531 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13532 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13533 (+ (org-time-today)
13534 (* (string-to-number (match-string 1 s))
13535 (cdr (assoc (match-string 2 s)
13536 '(("d" . 86400.0) ("w" . 604800.0)
13537 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13538 (t (org-2ft s)))))
13540 (defun org-match-any-p (re list)
13541 "Does re match any element of list?"
13542 (setq list (mapcar (lambda (x) (string-match re x)) list))
13543 (delq nil list))
13545 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13546 (defvar org-tags-overlay (make-overlay 1 1))
13547 (org-detach-overlay org-tags-overlay)
13549 (defun org-get-local-tags-at (&optional pos)
13550 "Get a list of tags defined in the current headline."
13551 (org-get-tags-at pos 'local))
13553 (defun org-get-local-tags ()
13554 "Get a list of tags defined in the current headline."
13555 (org-get-tags-at nil 'local))
13557 (defun org-get-tags-at (&optional pos local)
13558 "Get a list of all headline tags applicable at POS.
13559 POS defaults to point. If tags are inherited, the list contains
13560 the targets in the same sequence as the headlines appear, i.e.
13561 the tags of the current headline come last.
13562 When LOCAL is non-nil, only return tags from the current headline,
13563 ignore inherited ones."
13564 (interactive)
13565 (if (and org-trust-scanner-tags
13566 (or (not pos) (equal pos (point)))
13567 (not local))
13568 org-scanner-tags
13569 (let (tags ltags lastpos parent)
13570 (save-excursion
13571 (save-restriction
13572 (widen)
13573 (goto-char (or pos (point)))
13574 (save-match-data
13575 (catch 'done
13576 (condition-case nil
13577 (progn
13578 (org-back-to-heading t)
13579 (while (not (equal lastpos (point)))
13580 (setq lastpos (point))
13581 (when (looking-at
13582 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13583 (setq ltags (org-split-string
13584 (org-match-string-no-properties 1) ":"))
13585 (when parent
13586 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13587 (setq tags (append
13588 (if parent
13589 (org-remove-uninherited-tags ltags)
13590 ltags)
13591 tags)))
13592 (or org-use-tag-inheritance (throw 'done t))
13593 (if local (throw 'done t))
13594 (or (org-up-heading-safe) (error nil))
13595 (setq parent t)))
13596 (error nil)))))
13597 (if local
13598 tags
13599 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13601 (defun org-add-prop-inherited (s)
13602 (add-text-properties 0 (length s) '(inherited t) s)
13605 (defun org-toggle-tag (tag &optional onoff)
13606 "Toggle the tag TAG for the current line.
13607 If ONOFF is `on' or `off', don't toggle but set to this state."
13608 (let (res current)
13609 (save-excursion
13610 (org-back-to-heading t)
13611 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13612 (point-at-eol) t)
13613 (progn
13614 (setq current (match-string 1))
13615 (replace-match ""))
13616 (setq current ""))
13617 (setq current (nreverse (org-split-string current ":")))
13618 (cond
13619 ((eq onoff 'on)
13620 (setq res t)
13621 (or (member tag current) (push tag current)))
13622 ((eq onoff 'off)
13623 (or (not (member tag current)) (setq current (delete tag current))))
13624 (t (if (member tag current)
13625 (setq current (delete tag current))
13626 (setq res t)
13627 (push tag current))))
13628 (end-of-line 1)
13629 (if current
13630 (progn
13631 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13632 (org-set-tags nil t))
13633 (delete-horizontal-space))
13634 (run-hooks 'org-after-tags-change-hook))
13635 res))
13637 (defun org-align-tags-here (to-col)
13638 ;; Assumes that this is a headline
13639 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13640 (beginning-of-line 1)
13641 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13642 (< pos (match-beginning 2)))
13643 (progn
13644 (setq tags-l (- (match-end 2) (match-beginning 2)))
13645 (goto-char (match-beginning 1))
13646 (insert " ")
13647 (delete-region (point) (1+ (match-beginning 2)))
13648 (setq ncol (max (current-column)
13649 (1+ col)
13650 (if (> to-col 0)
13651 to-col
13652 (- (abs to-col) tags-l))))
13653 (setq p (point))
13654 (insert (make-string (- ncol (current-column)) ?\ ))
13655 (setq ncol (current-column))
13656 (when indent-tabs-mode (tabify p (point-at-eol)))
13657 (org-move-to-column (min ncol col) t))
13658 (goto-char pos))))
13660 (defun org-set-tags-command (&optional arg just-align)
13661 "Call the set-tags command for the current entry."
13662 (interactive "P")
13663 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13664 (org-set-tags arg just-align)
13665 (save-excursion
13666 (org-back-to-heading t)
13667 (org-set-tags arg just-align))))
13669 (defun org-set-tags-to (data)
13670 "Set the tags of the current entry to DATA, replacing the current tags.
13671 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13672 If DATA is nil or the empty string, any tags will be removed."
13673 (interactive "sTags: ")
13674 (setq data
13675 (cond
13676 ((eq data nil) "")
13677 ((equal data "") "")
13678 ((stringp data)
13679 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13680 ":"))
13681 ((listp data)
13682 (concat ":" (mapconcat 'identity data ":") ":"))))
13683 (when data
13684 (save-excursion
13685 (org-back-to-heading t)
13686 (when (looking-at org-complex-heading-regexp)
13687 (if (match-end 5)
13688 (progn
13689 (goto-char (match-beginning 5))
13690 (insert data)
13691 (delete-region (point) (point-at-eol))
13692 (org-set-tags nil 'align))
13693 (goto-char (point-at-eol))
13694 (insert " " data)
13695 (org-set-tags nil 'align)))
13696 (beginning-of-line 1)
13697 (if (looking-at ".*?\\([ \t]+\\)$")
13698 (delete-region (match-beginning 1) (match-end 1))))))
13700 (defun org-align-all-tags ()
13701 "Align the tags i all headings."
13702 (interactive)
13703 (save-excursion
13704 (or (ignore-errors (org-back-to-heading t))
13705 (outline-next-heading))
13706 (if (org-at-heading-p)
13707 (org-set-tags t)
13708 (message "No headings"))))
13710 (defvar org-indent-indentation-per-level)
13711 (defun org-set-tags (&optional arg just-align)
13712 "Set the tags for the current headline.
13713 With prefix ARG, realign all tags in headings in the current buffer."
13714 (interactive "P")
13715 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13716 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13717 'region-start-level 'region))
13718 org-loop-over-headlines-in-active-region)
13719 (org-map-entries
13720 ;; We don't use ARG and JUST-ALIGN here these args are not
13721 ;; useful when looping over headlines
13722 `(org-set-tags)
13723 org-loop-over-headlines-in-active-region
13724 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13725 (let* ((re org-outline-regexp-bol)
13726 (current (unless arg (org-get-tags-string)))
13727 (col (current-column))
13728 (org-setting-tags t)
13729 table current-tags inherited-tags ; computed below when needed
13730 tags p0 c0 c1 rpl di tc level)
13731 (if arg
13732 (save-excursion
13733 (goto-char (point-min))
13734 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13735 (while (re-search-forward re nil t)
13736 (org-set-tags nil t)
13737 (end-of-line 1)))
13738 (message "All tags realigned to column %d" org-tags-column))
13739 (if just-align
13740 (setq tags current)
13741 ;; Get a new set of tags from the user
13742 (save-excursion
13743 (setq table (append org-tag-persistent-alist
13744 (or org-tag-alist (org-get-buffer-tags))
13745 (and
13746 org-complete-tags-always-offer-all-agenda-tags
13747 (org-global-tags-completion-table
13748 (org-agenda-files))))
13749 org-last-tags-completion-table table
13750 current-tags (org-split-string current ":")
13751 inherited-tags (nreverse
13752 (nthcdr (length current-tags)
13753 (nreverse (org-get-tags-at))))
13754 tags
13755 (if (or (eq t org-use-fast-tag-selection)
13756 (and org-use-fast-tag-selection
13757 (delq nil (mapcar 'cdr table))))
13758 (org-fast-tag-selection
13759 current-tags inherited-tags table
13760 (if org-fast-tag-selection-include-todo
13761 org-todo-key-alist))
13762 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13763 (org-trim
13764 (org-icompleting-read "Tags: "
13765 'org-tags-completion-function
13766 nil nil current 'org-tags-history))))))
13767 (while (string-match "[-+&]+" tags)
13768 ;; No boolean logic, just a list
13769 (setq tags (replace-match ":" t t tags))))
13771 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13773 (if org-tags-sort-function
13774 (setq tags (mapconcat 'identity
13775 (sort (org-split-string
13776 tags (org-re "[^[:alnum:]_@#%]+"))
13777 org-tags-sort-function) ":")))
13779 (if (string-match "\\`[\t ]*\\'" tags)
13780 (setq tags "")
13781 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13782 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13784 ;; Insert new tags at the correct column
13785 (beginning-of-line 1)
13786 (setq level (or (and (looking-at org-outline-regexp)
13787 (- (match-end 0) (point) 1))
13789 (cond
13790 ((and (equal current "") (equal tags "")))
13791 ((re-search-forward
13792 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13793 (point-at-eol) t)
13794 (if (equal tags "")
13795 (setq rpl "")
13796 (goto-char (match-beginning 0))
13797 (setq c0 (current-column)
13798 ;; compute offset for the case of org-indent-mode active
13799 di (if org-indent-mode
13800 (* (1- org-indent-indentation-per-level) (1- level))
13802 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13803 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13804 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13805 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13806 (replace-match rpl t t)
13807 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13808 tags)
13809 (t (error "Tags alignment failed")))
13810 (org-move-to-column col)
13811 (unless just-align
13812 (run-hooks 'org-after-tags-change-hook))))))
13814 (defun org-change-tag-in-region (beg end tag off)
13815 "Add or remove TAG for each entry in the region.
13816 This works in the agenda, and also in an org-mode buffer."
13817 (interactive
13818 (list (region-beginning) (region-end)
13819 (let ((org-last-tags-completion-table
13820 (if (derived-mode-p 'org-mode)
13821 (org-get-buffer-tags)
13822 (org-global-tags-completion-table))))
13823 (org-icompleting-read
13824 "Tag: " 'org-tags-completion-function nil nil nil
13825 'org-tags-history))
13826 (progn
13827 (message "[s]et or [r]emove? ")
13828 (equal (read-char-exclusive) ?r))))
13829 (if (fboundp 'deactivate-mark) (deactivate-mark))
13830 (let ((agendap (equal major-mode 'org-agenda-mode))
13831 l1 l2 m buf pos newhead (cnt 0))
13832 (goto-char end)
13833 (setq l2 (1- (org-current-line)))
13834 (goto-char beg)
13835 (setq l1 (org-current-line))
13836 (loop for l from l1 to l2 do
13837 (org-goto-line l)
13838 (setq m (get-text-property (point) 'org-hd-marker))
13839 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13840 (and agendap m))
13841 (setq buf (if agendap (marker-buffer m) (current-buffer))
13842 pos (if agendap m (point)))
13843 (with-current-buffer buf
13844 (save-excursion
13845 (save-restriction
13846 (goto-char pos)
13847 (setq cnt (1+ cnt))
13848 (org-toggle-tag tag (if off 'off 'on))
13849 (setq newhead (org-get-heading)))))
13850 (and agendap (org-agenda-change-all-lines newhead m))))
13851 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13853 (defun org-tags-completion-function (string predicate &optional flag)
13854 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13855 (confirm (lambda (x) (stringp (car x)))))
13856 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13857 (setq s1 (match-string 1 string)
13858 s2 (match-string 2 string))
13859 (setq s1 "" s2 string))
13860 (cond
13861 ((eq flag nil)
13862 ;; try completion
13863 (setq rtn (try-completion s2 ctable confirm))
13864 (if (stringp rtn)
13865 (setq rtn
13866 (concat s1 s2 (substring rtn (length s2))
13867 (if (and org-add-colon-after-tag-completion
13868 (assoc rtn ctable))
13869 ":" ""))))
13870 rtn)
13871 ((eq flag t)
13872 ;; all-completions
13873 (all-completions s2 ctable confirm)
13875 ((eq flag 'lambda)
13876 ;; exact match?
13877 (assoc s2 ctable)))
13880 (defun org-fast-tag-insert (kwd tags face &optional end)
13881 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13882 (insert (format "%-12s" (concat kwd ":"))
13883 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13884 (or end "")))
13886 (defun org-fast-tag-show-exit (flag)
13887 (save-excursion
13888 (org-goto-line 3)
13889 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13890 (replace-match ""))
13891 (when flag
13892 (end-of-line 1)
13893 (org-move-to-column (- (window-width) 19) t)
13894 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13896 (defun org-set-current-tags-overlay (current prefix)
13897 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13898 (if (featurep 'xemacs)
13899 (org-overlay-display org-tags-overlay (concat prefix s)
13900 'secondary-selection)
13901 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13902 (org-overlay-display org-tags-overlay (concat prefix s)))))
13904 (defvar org-last-tag-selection-key nil)
13905 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13906 "Fast tag selection with single keys.
13907 CURRENT is the current list of tags in the headline, INHERITED is the
13908 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13909 possibly with grouping information. TODO-TABLE is a similar table with
13910 TODO keywords, should these have keys assigned to them.
13911 If the keys are nil, a-z are automatically assigned.
13912 Returns the new tags string, or nil to not change the current settings."
13913 (let* ((fulltable (append table todo-table))
13914 (maxlen (apply 'max (mapcar
13915 (lambda (x)
13916 (if (stringp (car x)) (string-width (car x)) 0))
13917 fulltable)))
13918 (buf (current-buffer))
13919 (expert (eq org-fast-tag-selection-single-key 'expert))
13920 (buffer-tags nil)
13921 (fwidth (+ maxlen 3 1 3))
13922 (ncol (/ (- (window-width) 4) fwidth))
13923 (i-face 'org-done)
13924 (c-face 'org-todo)
13925 tg cnt e c char c1 c2 ntable tbl rtn
13926 ov-start ov-end ov-prefix
13927 (exit-after-next org-fast-tag-selection-single-key)
13928 (done-keywords org-done-keywords)
13929 groups ingroup)
13930 (save-excursion
13931 (beginning-of-line 1)
13932 (if (looking-at
13933 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13934 (setq ov-start (match-beginning 1)
13935 ov-end (match-end 1)
13936 ov-prefix "")
13937 (setq ov-start (1- (point-at-eol))
13938 ov-end (1+ ov-start))
13939 (skip-chars-forward "^\n\r")
13940 (setq ov-prefix
13941 (concat
13942 (buffer-substring (1- (point)) (point))
13943 (if (> (current-column) org-tags-column)
13945 (make-string (- org-tags-column (current-column)) ?\ ))))))
13946 (move-overlay org-tags-overlay ov-start ov-end)
13947 (save-window-excursion
13948 (if expert
13949 (set-buffer (get-buffer-create " *Org tags*"))
13950 (delete-other-windows)
13951 (split-window-vertically)
13952 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13953 (erase-buffer)
13954 (org-set-local 'org-done-keywords done-keywords)
13955 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13956 (org-fast-tag-insert "Current" current c-face "\n\n")
13957 (org-fast-tag-show-exit exit-after-next)
13958 (org-set-current-tags-overlay current ov-prefix)
13959 (setq tbl fulltable char ?a cnt 0)
13960 (while (setq e (pop tbl))
13961 (cond
13962 ((equal (car e) :startgroup)
13963 (push '() groups) (setq ingroup t)
13964 (when (not (= cnt 0))
13965 (setq cnt 0)
13966 (insert "\n"))
13967 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
13968 ((equal (car e) :endgroup)
13969 (setq ingroup nil cnt 0)
13970 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
13971 ((equal e '(:newline))
13972 (when (not (= cnt 0))
13973 (setq cnt 0)
13974 (insert "\n")
13975 (setq e (car tbl))
13976 (while (equal (car tbl) '(:newline))
13977 (insert "\n")
13978 (setq tbl (cdr tbl)))))
13980 (setq tg (copy-sequence (car e)) c2 nil)
13981 (if (cdr e)
13982 (setq c (cdr e))
13983 ;; automatically assign a character.
13984 (setq c1 (string-to-char
13985 (downcase (substring
13986 tg (if (= (string-to-char tg) ?@) 1 0)))))
13987 (if (or (rassoc c1 ntable) (rassoc c1 table))
13988 (while (or (rassoc char ntable) (rassoc char table))
13989 (setq char (1+ char)))
13990 (setq c2 c1))
13991 (setq c (or c2 char)))
13992 (if ingroup (push tg (car groups)))
13993 (setq tg (org-add-props tg nil 'face
13994 (cond
13995 ((not (assoc tg table))
13996 (org-get-todo-face tg))
13997 ((member tg current) c-face)
13998 ((member tg inherited) i-face))))
13999 (if (and (= cnt 0) (not ingroup)) (insert " "))
14000 (insert "[" c "] " tg (make-string
14001 (- fwidth 4 (length tg)) ?\ ))
14002 (push (cons tg c) ntable)
14003 (when (= (setq cnt (1+ cnt)) ncol)
14004 (insert "\n")
14005 (if ingroup (insert " "))
14006 (setq cnt 0)))))
14007 (setq ntable (nreverse ntable))
14008 (insert "\n")
14009 (goto-char (point-min))
14010 (if (not expert) (org-fit-window-to-buffer))
14011 (setq rtn
14012 (catch 'exit
14013 (while t
14014 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14015 (if (not groups) "no " "")
14016 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14017 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14018 (setq org-last-tag-selection-key c)
14019 (cond
14020 ((= c ?\r) (throw 'exit t))
14021 ((= c ?!)
14022 (setq groups (not groups))
14023 (goto-char (point-min))
14024 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14025 ((= c ?\C-c)
14026 (if (not expert)
14027 (org-fast-tag-show-exit
14028 (setq exit-after-next (not exit-after-next)))
14029 (setq expert nil)
14030 (delete-other-windows)
14031 (set-window-buffer (split-window-vertically) " *Org tags*")
14032 (org-switch-to-buffer-other-window " *Org tags*")
14033 (org-fit-window-to-buffer)))
14034 ((or (= c ?\C-g)
14035 (and (= c ?q) (not (rassoc c ntable))))
14036 (org-detach-overlay org-tags-overlay)
14037 (setq quit-flag t))
14038 ((= c ?\ )
14039 (setq current nil)
14040 (if exit-after-next (setq exit-after-next 'now)))
14041 ((= c ?\t)
14042 (condition-case nil
14043 (setq tg (org-icompleting-read
14044 "Tag: "
14045 (or buffer-tags
14046 (with-current-buffer buf
14047 (org-get-buffer-tags)))))
14048 (quit (setq tg "")))
14049 (when (string-match "\\S-" tg)
14050 (add-to-list 'buffer-tags (list tg))
14051 (if (member tg current)
14052 (setq current (delete tg current))
14053 (push tg current)))
14054 (if exit-after-next (setq exit-after-next 'now)))
14055 ((setq e (rassoc c todo-table) tg (car e))
14056 (with-current-buffer buf
14057 (save-excursion (org-todo tg)))
14058 (if exit-after-next (setq exit-after-next 'now)))
14059 ((setq e (rassoc c ntable) tg (car e))
14060 (if (member tg current)
14061 (setq current (delete tg current))
14062 (loop for g in groups do
14063 (if (member tg g)
14064 (mapc (lambda (x)
14065 (setq current (delete x current)))
14066 g)))
14067 (push tg current))
14068 (if exit-after-next (setq exit-after-next 'now))))
14070 ;; Create a sorted list
14071 (setq current
14072 (sort current
14073 (lambda (a b)
14074 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14075 (if (eq exit-after-next 'now) (throw 'exit t))
14076 (goto-char (point-min))
14077 (beginning-of-line 2)
14078 (delete-region (point) (point-at-eol))
14079 (org-fast-tag-insert "Current" current c-face)
14080 (org-set-current-tags-overlay current ov-prefix)
14081 (while (re-search-forward
14082 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14083 (setq tg (match-string 1))
14084 (add-text-properties
14085 (match-beginning 1) (match-end 1)
14086 (list 'face
14087 (cond
14088 ((member tg current) c-face)
14089 ((member tg inherited) i-face)
14090 (t (get-text-property (match-beginning 1) 'face))))))
14091 (goto-char (point-min)))))
14092 (org-detach-overlay org-tags-overlay)
14093 (if rtn
14094 (mapconcat 'identity current ":")
14095 nil))))
14097 (defun org-get-tags-string ()
14098 "Get the TAGS string in the current headline."
14099 (unless (org-at-heading-p t)
14100 (error "Not on a heading"))
14101 (save-excursion
14102 (beginning-of-line 1)
14103 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14104 (org-match-string-no-properties 1)
14105 "")))
14107 (defun org-get-tags ()
14108 "Get the list of tags specified in the current headline."
14109 (org-split-string (org-get-tags-string) ":"))
14111 (defun org-get-buffer-tags ()
14112 "Get a table of all tags used in the buffer, for completion."
14113 (let (tags)
14114 (save-excursion
14115 (goto-char (point-min))
14116 (while (re-search-forward
14117 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14118 (when (equal (char-after (point-at-bol 0)) ?*)
14119 (mapc (lambda (x) (add-to-list 'tags x))
14120 (org-split-string (org-match-string-no-properties 1) ":")))))
14121 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14122 (mapcar 'list tags)))
14124 ;;;; The mapping API
14126 ;;;###autoload
14127 (defun org-map-entries (func &optional match scope &rest skip)
14128 "Call FUNC at each headline selected by MATCH in SCOPE.
14130 FUNC is a function or a lisp form. The function will be called without
14131 arguments, with the cursor positioned at the beginning of the headline.
14132 The return values of all calls to the function will be collected and
14133 returned as a list.
14135 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14136 does not need to preserve point. After evaluation, the cursor will be
14137 moved to the end of the line (presumably of the headline of the
14138 processed entry) and search continues from there. Under some
14139 circumstances, this may not produce the wanted results. For example,
14140 if you have removed (e.g. archived) the current (sub)tree it could
14141 mean that the next entry will be skipped entirely. In such cases, you
14142 can specify the position from where search should continue by making
14143 FUNC set the variable `org-map-continue-from' to the desired buffer
14144 position.
14146 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14147 Only headlines that are matched by this query will be considered during
14148 the iteration. When MATCH is nil or t, all headlines will be
14149 visited by the iteration.
14151 SCOPE determines the scope of this command. It can be any of:
14153 nil The current buffer, respecting the restriction if any
14154 tree The subtree started with the entry at point
14155 region The entries within the active region, if any
14156 region-start-level
14157 The entries within the active region, but only those at
14158 the same level than the first one.
14159 file The current buffer, without restriction
14160 file-with-archives
14161 The current buffer, and any archives associated with it
14162 agenda All agenda files
14163 agenda-with-archives
14164 All agenda files with any archive files associated with them
14165 \(file1 file2 ...)
14166 If this is a list, all files in the list will be scanned
14168 The remaining args are treated as settings for the skipping facilities of
14169 the scanner. The following items can be given here:
14171 archive skip trees with the archive tag.
14172 comment skip trees with the COMMENT keyword
14173 function or Emacs Lisp form:
14174 will be used as value for `org-agenda-skip-function', so whenever
14175 the function returns t, FUNC will not be called for that
14176 entry and search will continue from the point where the
14177 function leaves it.
14179 If your function needs to retrieve the tags including inherited tags
14180 at the *current* entry, you can use the value of the variable
14181 `org-scanner-tags' which will be much faster than getting the value
14182 with `org-get-tags-at'. If your function gets properties with
14183 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14184 to t around the call to `org-entry-properties' to get the same speedup.
14185 Note that if your function moves around to retrieve tags and properties at
14186 a *different* entry, you cannot use these techniques."
14187 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14188 (not (org-region-active-p)))
14189 (let* ((org-agenda-archives-mode nil) ; just to make sure
14190 (org-agenda-skip-archived-trees (memq 'archive skip))
14191 (org-agenda-skip-comment-trees (memq 'comment skip))
14192 (org-agenda-skip-function
14193 (car (org-delete-all '(comment archive) skip)))
14194 (org-tags-match-list-sublevels t)
14195 (start-level (eq scope 'region-start-level))
14196 matcher file res
14197 org-todo-keywords-for-agenda
14198 org-done-keywords-for-agenda
14199 org-todo-keyword-alist-for-agenda
14200 org-drawers-for-agenda
14201 org-tag-alist-for-agenda
14202 todo-only)
14204 (cond
14205 ((eq match t) (setq matcher t))
14206 ((eq match nil) (setq matcher t))
14207 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14209 (save-excursion
14210 (save-restriction
14211 (cond ((eq scope 'tree)
14212 (org-back-to-heading t)
14213 (org-narrow-to-subtree)
14214 (setq scope nil))
14215 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14216 (org-region-active-p))
14217 ;; If needed, set start-level to a string like "2"
14218 (when start-level
14219 (save-excursion
14220 (goto-char (region-beginning))
14221 (unless (org-at-heading-p) (outline-next-heading))
14222 (setq start-level (org-current-level))))
14223 (narrow-to-region (region-beginning)
14224 (save-excursion
14225 (goto-char (region-end))
14226 (unless (and (bolp) (org-at-heading-p))
14227 (outline-next-heading))
14228 (point)))
14229 (setq scope nil)))
14231 (if (not scope)
14232 (progn
14233 (org-agenda-prepare-buffers
14234 (list (buffer-file-name (current-buffer))))
14235 (setq res (org-scan-tags func matcher todo-only start-level)))
14236 ;; Get the right scope
14237 (cond
14238 ((and scope (listp scope) (symbolp (car scope)))
14239 (setq scope (eval scope)))
14240 ((eq scope 'agenda)
14241 (setq scope (org-agenda-files t)))
14242 ((eq scope 'agenda-with-archives)
14243 (setq scope (org-agenda-files t))
14244 (setq scope (org-add-archive-files scope)))
14245 ((eq scope 'file)
14246 (setq scope (list (buffer-file-name))))
14247 ((eq scope 'file-with-archives)
14248 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14249 (org-agenda-prepare-buffers scope)
14250 (while (setq file (pop scope))
14251 (with-current-buffer (org-find-base-buffer-visiting file)
14252 (save-excursion
14253 (save-restriction
14254 (widen)
14255 (goto-char (point-min))
14256 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14257 res)))
14259 ;;;; Properties
14261 ;;; Setting and retrieving properties
14263 (defconst org-special-properties
14264 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14265 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14266 "The special properties valid in Org-mode.
14268 These are properties that are not defined in the property drawer,
14269 but in some other way.")
14271 (defconst org-default-properties
14272 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14273 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14274 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14275 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14276 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14277 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14278 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14279 "Some properties that are used by Org-mode for various purposes.
14280 Being in this list makes sure that they are offered for completion.")
14282 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14283 "Regular expression matching the first line of a property drawer.")
14285 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14286 "Regular expression matching the last line of a property drawer.")
14288 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14289 "Regular expression matching the first line of a property drawer.")
14291 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14292 "Regular expression matching the first line of a property drawer.")
14294 (defconst org-property-drawer-re
14295 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14296 org-property-end-re "\\)\n?")
14297 "Matches an entire property drawer.")
14299 (defconst org-clock-drawer-re
14300 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14301 org-property-end-re "\\)\n?")
14302 "Matches an entire clock drawer.")
14304 (defsubst org-re-property (property)
14305 "Return a regexp matching a PROPERTY line.
14306 Match group 1 will be set to the value."
14307 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14309 (defsubst org-re-property-keyword (property)
14310 "Return a regexp matching a PROPERTY line, possibly with no
14311 value for the property."
14312 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14314 (defun org-property-action ()
14315 "Do an action on properties."
14316 (interactive)
14317 (let (c)
14318 (org-at-property-p)
14319 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14320 (setq c (read-char-exclusive))
14321 (cond
14322 ((equal c ?s)
14323 (call-interactively 'org-set-property))
14324 ((equal c ?d)
14325 (call-interactively 'org-delete-property))
14326 ((equal c ?D)
14327 (call-interactively 'org-delete-property-globally))
14328 ((equal c ?c)
14329 (call-interactively 'org-compute-property-at-point))
14330 (t (error "No such property action %c" c)))))
14332 (defun org-inc-effort ()
14333 "Increment the value of the effort property in the current entry."
14334 (interactive)
14335 (org-set-effort nil t))
14337 (defun org-set-effort (&optional value increment)
14338 "Set the effort property of the current entry.
14339 With numerical prefix arg, use the nth allowed value, 0 stands for the
14340 10th allowed value.
14342 When INCREMENT is non-nil, set the property to the next allowed value."
14343 (interactive "P")
14344 (if (equal value 0) (setq value 10))
14345 (let* ((completion-ignore-case t)
14346 (prop org-effort-property)
14347 (cur (org-entry-get nil prop))
14348 (allowed (org-property-get-allowed-values nil prop 'table))
14349 (existing (mapcar 'list (org-property-values prop)))
14351 (val (cond
14352 ((stringp value) value)
14353 ((and allowed (integerp value))
14354 (or (car (nth (1- value) allowed))
14355 (car (org-last allowed))))
14356 ((and allowed increment)
14357 (or (caadr (member (list cur) allowed))
14358 (error "Allowed effort values are not set")))
14359 (allowed
14360 (message "Select 1-9,0, [RET%s]: %s"
14361 (if cur (concat "=" cur) "")
14362 (mapconcat 'car allowed " "))
14363 (setq rpl (read-char-exclusive))
14364 (if (equal rpl ?\r)
14366 (setq rpl (- rpl ?0))
14367 (if (equal rpl 0) (setq rpl 10))
14368 (if (and (> rpl 0) (<= rpl (length allowed)))
14369 (car (nth (1- rpl) allowed))
14370 (org-completing-read "Effort: " allowed nil))))
14372 (let (org-completion-use-ido org-completion-use-iswitchb)
14373 (org-completing-read
14374 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14375 (concat "[" cur "]") "")
14376 ": ")
14377 existing nil nil "" nil cur))))))
14378 (unless (equal (org-entry-get nil prop) val)
14379 (org-entry-put nil prop val))
14380 (message "%s is now %s" prop val)))
14382 (defun org-at-property-p ()
14383 "Is cursor inside a property drawer?"
14384 (save-excursion
14385 (beginning-of-line 1)
14386 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14387 (save-match-data ;; Used by calling procedures
14388 (let ((p (point))
14389 (range (unless (org-before-first-heading-p)
14390 (org-get-property-block))))
14391 (and range (<= (car range) p) (< p (cdr range))))))))
14393 (defun org-get-property-block (&optional beg end force)
14394 "Return the (beg . end) range of the body of the property drawer.
14395 BEG and END are the beginning and end of the current subtree, or of
14396 the part before the first headline. If they are not given, they will
14397 be found. If the drawer does not exist and FORCE is non-nil, create
14398 the drawer."
14399 (catch 'exit
14400 (save-excursion
14401 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14402 (progn (org-back-to-heading t) (point))))
14403 (end (or end (and (not (outline-next-heading)) (point-max))
14404 (point))))
14405 (goto-char beg)
14406 (if (re-search-forward org-property-start-re end t)
14407 (setq beg (1+ (match-end 0)))
14408 (if force
14409 (save-excursion
14410 (org-insert-property-drawer)
14411 (setq end (progn (outline-next-heading) (point))))
14412 (throw 'exit nil))
14413 (goto-char beg)
14414 (if (re-search-forward org-property-start-re end t)
14415 (setq beg (1+ (match-end 0)))))
14416 (if (re-search-forward org-property-end-re end t)
14417 (setq end (match-beginning 0))
14418 (or force (throw 'exit nil))
14419 (goto-char beg)
14420 (setq end beg)
14421 (org-indent-line)
14422 (insert ":END:\n"))
14423 (cons beg end)))))
14425 (defun org-entry-properties (&optional pom which specific)
14426 "Get all properties of the entry at point-or-marker POM.
14427 This includes the TODO keyword, the tags, time strings for deadline,
14428 scheduled, and clocking, and any additional properties defined in the
14429 entry. The return value is an alist, keys may occur multiple times
14430 if the property key was used several times.
14431 POM may also be nil, in which case the current entry is used.
14432 If WHICH is nil or `all', get all properties. If WHICH is
14433 `special' or `standard', only get that subclass. If WHICH
14434 is a string only get exactly this property. SPECIFIC can be a string, the
14435 specific property we are interested in. Specifying it can speed
14436 things up because then unnecessary parsing is avoided."
14437 (setq which (or which 'all))
14438 (org-with-point-at pom
14439 (let ((clockstr (substring org-clock-string 0 -1))
14440 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14441 (case-fold-search nil)
14442 beg end range props sum-props key key1 value string clocksum clocksumt)
14443 (save-excursion
14444 (when (condition-case nil
14445 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14446 (error nil))
14447 (setq beg (point))
14448 (setq sum-props (get-text-property (point) 'org-summaries))
14449 (setq clocksum (get-text-property (point) :org-clock-minutes)
14450 clocksumt (get-text-property (point) :org-clock-minutes-today))
14451 (outline-next-heading)
14452 (setq end (point))
14453 (when (memq which '(all special))
14454 ;; Get the special properties, like TODO and tags
14455 (goto-char beg)
14456 (when (and (or (not specific) (string= specific "TODO"))
14457 (looking-at org-todo-line-regexp) (match-end 2))
14458 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14459 (when (and (or (not specific) (string= specific "PRIORITY"))
14460 (looking-at org-priority-regexp))
14461 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14462 (when (or (not specific) (string= specific "FILE"))
14463 (push (cons "FILE" buffer-file-name) props))
14464 (when (and (or (not specific) (string= specific "TAGS"))
14465 (setq value (org-get-tags-string))
14466 (string-match "\\S-" value))
14467 (push (cons "TAGS" value) props))
14468 (when (and (or (not specific) (string= specific "ALLTAGS"))
14469 (setq value (org-get-tags-at)))
14470 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14471 ":"))
14472 props))
14473 (when (or (not specific) (string= specific "BLOCKED"))
14474 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14475 (when (or (not specific)
14476 (member specific
14477 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14478 "TIMESTAMP" "TIMESTAMP_IA")))
14479 (catch 'match
14480 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14481 (setq key (if (match-end 1)
14482 (substring (org-match-string-no-properties 1)
14483 0 -1))
14484 string (if (equal key clockstr)
14485 (org-trim
14486 (buffer-substring-no-properties
14487 (match-beginning 3) (goto-char
14488 (point-at-eol))))
14489 (substring (org-match-string-no-properties 3)
14490 1 -1)))
14491 ;; Get the correct property name from the key. This is
14492 ;; necessary if the user has configured time keywords.
14493 (setq key1 (concat key ":"))
14494 (cond
14495 ((not key)
14496 (setq key
14497 (if (= (char-after (match-beginning 3)) ?\[)
14498 "TIMESTAMP_IA" "TIMESTAMP")))
14499 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14500 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14501 ((equal key1 org-closed-string) (setq key "CLOSED"))
14502 ((equal key1 org-clock-string) (setq key "CLOCK")))
14503 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14504 (progn
14505 (push (cons key string) props)
14506 ;; no need to search further if match is found
14507 (throw 'match t))
14508 (when (or (equal key "CLOCK") (not (assoc key props)))
14509 (push (cons key string) props)))))))
14511 (when (memq which '(all standard))
14512 ;; Get the standard properties, like :PROP: ...
14513 (setq range (org-get-property-block beg end))
14514 (when range
14515 (goto-char (car range))
14516 (while (re-search-forward
14517 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14518 (cdr range) t)
14519 (setq key (org-match-string-no-properties 1)
14520 value (org-trim (or (org-match-string-no-properties 2) "")))
14521 (unless (member key excluded)
14522 (push (cons key (or value "")) props)))))
14523 (if clocksum
14524 (push (cons "CLOCKSUM"
14525 (org-columns-number-to-string (/ (float clocksum) 60.)
14526 'add_times))
14527 props))
14528 (if clocksumt
14529 (push (cons "CLOCKSUM_T"
14530 (org-columns-number-to-string (/ (float clocksumt) 60.)
14531 'add_times))
14532 props))
14533 (unless (assoc "CATEGORY" props)
14534 (push (cons "CATEGORY" (org-get-category)) props))
14535 (append sum-props (nreverse props)))))))
14537 (defun org-entry-get (pom property &optional inherit literal-nil)
14538 "Get value of PROPERTY for entry or content at point-or-marker POM.
14539 If INHERIT is non-nil and the entry does not have the property,
14540 then also check higher levels of the hierarchy.
14541 If INHERIT is the symbol `selective', use inheritance only if the setting
14542 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14543 If the property is present but empty, the return value is the empty string.
14544 If the property is not present at all, nil is returned.
14546 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14547 do not interpret it as the list atom nil. This is used for inheritance
14548 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14549 (org-with-point-at pom
14550 (if (and inherit (if (eq inherit 'selective)
14551 (org-property-inherit-p property)
14553 (org-entry-get-with-inheritance property literal-nil)
14554 (if (member property org-special-properties)
14555 ;; We need a special property. Use `org-entry-properties' to
14556 ;; retrieve it, but specify the wanted property
14557 (cdr (assoc property (org-entry-properties nil 'special property)))
14558 (let* ((range (org-get-property-block))
14559 (props (list (or (assoc property org-file-properties)
14560 (assoc property org-global-properties)
14561 (assoc property org-global-properties-fixed))))
14562 (ap (lambda (key)
14563 (when (re-search-forward
14564 (org-re-property key) (cdr range) t)
14565 (setq props
14566 (org-update-property-plist
14568 (if (match-end 1)
14569 (org-match-string-no-properties 1) "")
14570 props)))))
14571 val)
14572 (when (and range (goto-char (car range)))
14573 (funcall ap property)
14574 (goto-char (car range))
14575 (while (funcall ap (concat property "+")))
14576 (setq val (cdr (assoc property props)))
14577 (when val (if literal-nil val (org-not-nil val)))))))))
14579 (defun org-property-or-variable-value (var &optional inherit)
14580 "Check if there is a property fixing the value of VAR.
14581 If yes, return this value. If not, return the current value of the variable."
14582 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14583 (if (and prop (stringp prop) (string-match "\\S-" prop))
14584 (read prop)
14585 (symbol-value var))))
14587 (defun org-entry-delete (pom property)
14588 "Delete the property PROPERTY from entry at point-or-marker POM."
14589 (org-with-point-at pom
14590 (if (member property org-special-properties)
14591 nil ; cannot delete these properties.
14592 (let ((range (org-get-property-block)))
14593 (if (and range
14594 (goto-char (car range))
14595 (re-search-forward
14596 (org-re-property property)
14597 (cdr range) t))
14598 (progn
14599 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14601 nil)))))
14603 ;; Multi-values properties are properties that contain multiple values
14604 ;; These values are assumed to be single words, separated by whitespace.
14605 (defun org-entry-add-to-multivalued-property (pom property value)
14606 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14607 (let* ((old (org-entry-get pom property))
14608 (values (and old (org-split-string old "[ \t]"))))
14609 (setq value (org-entry-protect-space value))
14610 (unless (member value values)
14611 (setq values (cons value values))
14612 (org-entry-put pom property
14613 (mapconcat 'identity values " ")))))
14615 (defun org-entry-remove-from-multivalued-property (pom property value)
14616 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14617 (let* ((old (org-entry-get pom property))
14618 (values (and old (org-split-string old "[ \t]"))))
14619 (setq value (org-entry-protect-space value))
14620 (when (member value values)
14621 (setq values (delete value values))
14622 (org-entry-put pom property
14623 (mapconcat 'identity values " ")))))
14625 (defun org-entry-member-in-multivalued-property (pom property value)
14626 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14627 (let* ((old (org-entry-get pom property))
14628 (values (and old (org-split-string old "[ \t]"))))
14629 (setq value (org-entry-protect-space value))
14630 (member value values)))
14632 (defun org-entry-get-multivalued-property (pom property)
14633 "Return a list of values in a multivalued property."
14634 (let* ((value (org-entry-get pom property))
14635 (values (and value (org-split-string value "[ \t]"))))
14636 (mapcar 'org-entry-restore-space values)))
14638 (defun org-entry-put-multivalued-property (pom property &rest values)
14639 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14640 VALUES should be a list of strings. Spaces will be protected."
14641 (org-entry-put pom property
14642 (mapconcat 'org-entry-protect-space values " "))
14643 (let* ((value (org-entry-get pom property))
14644 (values (and value (org-split-string value "[ \t]"))))
14645 (mapcar 'org-entry-restore-space values)))
14647 (defun org-entry-protect-space (s)
14648 "Protect spaces and newline in string S."
14649 (while (string-match " " s)
14650 (setq s (replace-match "%20" t t s)))
14651 (while (string-match "\n" s)
14652 (setq s (replace-match "%0A" t t s)))
14655 (defun org-entry-restore-space (s)
14656 "Restore spaces and newline in string S."
14657 (while (string-match "%20" s)
14658 (setq s (replace-match " " t t s)))
14659 (while (string-match "%0A" s)
14660 (setq s (replace-match "\n" t t s)))
14663 (defvar org-entry-property-inherited-from (make-marker)
14664 "Marker pointing to the entry from where a property was inherited.
14665 Each call to `org-entry-get-with-inheritance' will set this marker to the
14666 location of the entry where the inheritance search matched. If there was
14667 no match, the marker will point nowhere.
14668 Note that also `org-entry-get' calls this function, if the INHERIT flag
14669 is set.")
14671 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14672 "Get PROPERTY of entry or content at point, search higher levels if needed.
14673 The search will stop at the first ancestor which has the property defined.
14674 If the value found is \"nil\", return nil to show that the property
14675 should be considered as undefined (this is the meaning of nil here).
14676 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14677 (move-marker org-entry-property-inherited-from nil)
14678 (let (tmp)
14679 (save-excursion
14680 (save-restriction
14681 (widen)
14682 (catch 'ex
14683 (while t
14684 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14685 (or (ignore-errors (org-back-to-heading t))
14686 (goto-char (point-min)))
14687 (move-marker org-entry-property-inherited-from (point))
14688 (throw 'ex tmp))
14689 (or (ignore-errors (org-up-heading-safe))
14690 (throw 'ex nil))))))
14691 (setq tmp (or tmp
14692 (cdr (assoc property org-file-properties))
14693 (cdr (assoc property org-global-properties))
14694 (cdr (assoc property org-global-properties-fixed))))
14695 (if literal-nil tmp (org-not-nil tmp))))
14697 (defvar org-property-changed-functions nil
14698 "Hook called when the value of a property has changed.
14699 Each hook function should accept two arguments, the name of the property
14700 and the new value.")
14702 (defun org-entry-put (pom property value)
14703 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14704 (org-with-point-at pom
14705 (org-back-to-heading t)
14706 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14707 range)
14708 (cond
14709 ((equal property "TODO")
14710 (when (and (stringp value) (string-match "\\S-" value)
14711 (not (member value org-todo-keywords-1)))
14712 (error "\"%s\" is not a valid TODO state" value))
14713 (if (or (not value)
14714 (not (string-match "\\S-" value)))
14715 (setq value 'none))
14716 (org-todo value)
14717 (org-set-tags nil 'align))
14718 ((equal property "PRIORITY")
14719 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14720 (string-to-char value) ?\ ))
14721 (org-set-tags nil 'align))
14722 ((equal property "SCHEDULED")
14723 (if (re-search-forward org-scheduled-time-regexp end t)
14724 (cond
14725 ((eq value 'earlier) (org-timestamp-change -1 'day))
14726 ((eq value 'later) (org-timestamp-change 1 'day))
14727 (t (call-interactively 'org-schedule)))
14728 (call-interactively 'org-schedule)))
14729 ((equal property "DEADLINE")
14730 (if (re-search-forward org-deadline-time-regexp end t)
14731 (cond
14732 ((eq value 'earlier) (org-timestamp-change -1 'day))
14733 ((eq value 'later) (org-timestamp-change 1 'day))
14734 (t (call-interactively 'org-deadline)))
14735 (call-interactively 'org-deadline)))
14736 ((member property org-special-properties)
14737 (error "The %s property can not yet be set with `org-entry-put'"
14738 property))
14739 (t ; a non-special property
14740 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14741 (setq range (org-get-property-block beg end 'force))
14742 (goto-char (car range))
14743 (if (re-search-forward
14744 (org-re-property-keyword property) (cdr range) t)
14745 (progn
14746 (delete-region (match-beginning 0) (match-end 0))
14747 (goto-char (match-beginning 0)))
14748 (goto-char (cdr range))
14749 (insert "\n")
14750 (backward-char 1)
14751 (org-indent-line))
14752 (insert ":" property ":")
14753 (and value (insert " " value))
14754 (org-indent-line)))))
14755 (run-hook-with-args 'org-property-changed-functions property value)))
14757 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14758 "Get all property keys in the current buffer.
14759 With INCLUDE-SPECIALS, also list the special properties that reflect things
14760 like tags and TODO state.
14761 With INCLUDE-DEFAULTS, also include properties that has special meaning
14762 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14763 and others.
14764 With INCLUDE-COLUMNS, also include property names given in COLUMN
14765 formats in the current buffer."
14766 (let (rtn range cfmt s p)
14767 (save-excursion
14768 (save-restriction
14769 (widen)
14770 (goto-char (point-min))
14771 (while (re-search-forward org-property-start-re nil t)
14772 (setq range (org-get-property-block))
14773 (goto-char (car range))
14774 (while (re-search-forward
14775 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14776 (cdr range) t)
14777 (add-to-list 'rtn (org-match-string-no-properties 1)))
14778 (outline-next-heading))))
14780 (when include-specials
14781 (setq rtn (append org-special-properties rtn)))
14783 (when include-defaults
14784 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14785 (add-to-list 'rtn org-effort-property))
14787 (when include-columns
14788 (save-excursion
14789 (save-restriction
14790 (widen)
14791 (goto-char (point-min))
14792 (while (re-search-forward
14793 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14794 nil t)
14795 (setq cfmt (match-string 2) s 0)
14796 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14797 cfmt s)
14798 (setq s (match-end 0)
14799 p (match-string 1 cfmt))
14800 (unless (or (equal p "ITEM")
14801 (member p org-special-properties))
14802 (add-to-list 'rtn (match-string 1 cfmt))))))))
14804 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14806 (defun org-property-values (key)
14807 "Return a list of all values of property KEY in the current buffer."
14808 (save-excursion
14809 (save-restriction
14810 (widen)
14811 (goto-char (point-min))
14812 (let ((re (org-re-property key))
14813 values)
14814 (while (re-search-forward re nil t)
14815 (add-to-list 'values (org-trim (match-string 1))))
14816 (delete "" values)))))
14818 (defun org-insert-property-drawer ()
14819 "Insert a property drawer into the current entry."
14820 (org-back-to-heading t)
14821 (looking-at org-outline-regexp)
14822 (let ((indent (if org-adapt-indentation
14823 (- (match-end 0) (match-beginning 0))
14825 (beg (point))
14826 (re (concat "^[ \t]*" org-keyword-time-regexp))
14827 end hiddenp)
14828 (outline-next-heading)
14829 (setq end (point))
14830 (goto-char beg)
14831 (while (re-search-forward re end t))
14832 (setq hiddenp (outline-invisible-p))
14833 (end-of-line 1)
14834 (and (equal (char-after) ?\n) (forward-char 1))
14835 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14836 (if (member (match-string 1) '("CLOCK:" ":END:"))
14837 ;; just skip this line
14838 (beginning-of-line 2)
14839 ;; Drawer start, find the end
14840 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14841 (beginning-of-line 1)))
14842 (org-skip-over-state-notes)
14843 (skip-chars-backward " \t\n\r")
14844 (if (eq (char-before) ?*) (forward-char 1))
14845 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14846 (beginning-of-line 0)
14847 (org-indent-to-column indent)
14848 (beginning-of-line 2)
14849 (org-indent-to-column indent)
14850 (beginning-of-line 0)
14851 (if hiddenp
14852 (save-excursion
14853 (org-back-to-heading t)
14854 (hide-entry))
14855 (org-flag-drawer t))))
14857 (defun org-insert-drawer (&optional arg drawer)
14858 "Insert a drawer at point.
14860 Optional argument DRAWER, when non-nil, is a string representing
14861 drawer's name. Otherwise, the user is prompted for a name.
14863 If a region is active, insert the drawer around that region
14864 instead.
14866 Point is left between drawer's boundaries."
14867 (interactive "P")
14868 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14869 "LOGBOOK"))
14870 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14871 ;; internally by Org. They are meant to be inserted
14872 ;; automatically.
14873 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14874 ;; Remove system drawers from list. Note: For some reason,
14875 ;; `org-completing-read' ignores the predicate while
14876 ;; `completing-read' handles it fine.
14877 (drawer (if arg "PROPERTIES"
14878 (or drawer
14879 (completing-read
14880 "Drawer: " org-drawers
14881 (lambda (d) (not (member d system-drawers))))))))
14882 (cond
14883 ;; With C-u, fall back on `org-insert-property-drawer'
14884 (arg (org-insert-property-drawer))
14885 ;; With an active region, insert a drawer at point.
14886 ((not (org-region-active-p))
14887 (progn
14888 (unless (bolp) (insert "\n"))
14889 (insert (format ":%s:\n\n:END:\n" drawer))
14890 (forward-line -2)))
14891 ;; Otherwise, insert the drawer at point
14893 (let ((rbeg (region-beginning))
14894 (rend (copy-marker (region-end))))
14895 (unwind-protect
14896 (progn
14897 (goto-char rbeg)
14898 (beginning-of-line)
14899 (when (save-excursion
14900 (re-search-forward org-outline-regexp-bol rend t))
14901 (error "Drawers cannot contain headlines"))
14902 ;; Position point at the beginning of the first
14903 ;; non-blank line in region. Insert drawer's opening
14904 ;; there, then indent it.
14905 (org-skip-whitespace)
14906 (beginning-of-line)
14907 (insert ":" drawer ":\n")
14908 (forward-line -1)
14909 (indent-for-tab-command)
14910 ;; Move point to the beginning of the first blank line
14911 ;; after the last non-blank line in region. Insert
14912 ;; drawer's closing, then indent it.
14913 (goto-char rend)
14914 (skip-chars-backward " \r\t\n")
14915 (insert "\n:END:")
14916 (deactivate-mark t)
14917 (indent-for-tab-command)
14918 (unless (eolp) (insert "\n")))
14919 ;; Clear marker, whatever the outcome of insertion is.
14920 (set-marker rend nil)))))))
14922 (defvar org-property-set-functions-alist nil
14923 "Property set function alist.
14924 Each entry should have the following format:
14926 (PROPERTY . READ-FUNCTION)
14928 The read function will be called with the same argument as
14929 `org-completing-read'.")
14931 (defun org-set-property-function (property)
14932 "Get the function that should be used to set PROPERTY.
14933 This is computed according to `org-property-set-functions-alist'."
14934 (or (cdr (assoc property org-property-set-functions-alist))
14935 'org-completing-read))
14937 (defun org-read-property-value (property)
14938 "Read PROPERTY value from user."
14939 (let* ((completion-ignore-case t)
14940 (allowed (org-property-get-allowed-values nil property 'table))
14941 (cur (org-entry-get nil property))
14942 (prompt (concat property " value"
14943 (if (and cur (string-match "\\S-" cur))
14944 (concat " [" cur "]") "") ": "))
14945 (set-function (org-set-property-function property))
14946 (val (if allowed
14947 (funcall set-function prompt allowed nil
14948 (not (get-text-property 0 'org-unrestricted
14949 (caar allowed))))
14950 (let (org-completion-use-ido org-completion-use-iswitchb)
14951 (funcall set-function prompt
14952 (mapcar 'list (org-property-values property))
14953 nil nil "" nil cur)))))
14954 (if (equal val "")
14956 val)))
14958 (defvar org-last-set-property nil)
14959 (defun org-read-property-name ()
14960 "Read a property name."
14961 (let* ((completion-ignore-case t)
14962 (keys (org-buffer-property-keys nil t t))
14963 (default-prop (or (save-excursion
14964 (save-match-data
14965 (beginning-of-line)
14966 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
14967 (null (string= (match-string 1) "END"))
14968 (match-string 1))))
14969 org-last-set-property))
14970 (property (org-icompleting-read
14971 (concat "Property"
14972 (if default-prop (concat " [" default-prop "]") "")
14973 ": ")
14974 (mapcar 'list keys)
14975 nil nil nil nil
14976 default-prop
14978 (if (member property keys)
14979 property
14980 (or (cdr (assoc (downcase property)
14981 (mapcar (lambda (x) (cons (downcase x) x))
14982 keys)))
14983 property))))
14985 (defun org-set-property (property value)
14986 "In the current entry, set PROPERTY to VALUE.
14987 When called interactively, this will prompt for a property name, offering
14988 completion on existing and default properties. And then it will prompt
14989 for a value, offering completion either on allowed values (via an inherited
14990 xxx_ALL property) or on existing values in other instances of this property
14991 in the current file."
14992 (interactive (list nil nil))
14993 (let* ((property (or property (org-read-property-name)))
14994 (value (or value (org-read-property-value property)))
14995 (fn (cdr (assoc property org-properties-postprocess-alist))))
14996 (setq org-last-set-property property)
14997 ;; Possibly postprocess the inserted value:
14998 (when fn (setq value (funcall fn value)))
14999 (unless (equal (org-entry-get nil property) value)
15000 (org-entry-put nil property value))))
15002 (defun org-delete-property (property)
15003 "In the current entry, delete PROPERTY."
15004 (interactive
15005 (let* ((completion-ignore-case t)
15006 (prop (org-icompleting-read "Property: "
15007 (org-entry-properties nil 'standard))))
15008 (list prop)))
15009 (message "Property %s %s" property
15010 (if (org-entry-delete nil property)
15011 "deleted"
15012 "was not present in the entry")))
15014 (defun org-delete-property-globally (property)
15015 "Remove PROPERTY globally, from all entries."
15016 (interactive
15017 (let* ((completion-ignore-case t)
15018 (prop (org-icompleting-read
15019 "Globally remove property: "
15020 (mapcar 'list (org-buffer-property-keys)))))
15021 (list prop)))
15022 (save-excursion
15023 (save-restriction
15024 (widen)
15025 (goto-char (point-min))
15026 (let ((cnt 0))
15027 (while (re-search-forward
15028 (org-re-property property)
15029 nil t)
15030 (setq cnt (1+ cnt))
15031 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15032 (message "Property \"%s\" removed from %d entries" property cnt)))))
15034 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15036 (defun org-compute-property-at-point ()
15037 "Compute the property at point.
15038 This looks for an enclosing column format, extracts the operator and
15039 then applies it to the property in the column format's scope."
15040 (interactive)
15041 (unless (org-at-property-p)
15042 (error "Not at a property"))
15043 (let ((prop (org-match-string-no-properties 2)))
15044 (org-columns-get-format-and-top-level)
15045 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15046 (error "No operator defined for property %s" prop))
15047 (org-columns-compute prop)))
15049 (defvar org-property-allowed-value-functions nil
15050 "Hook for functions supplying allowed values for a specific property.
15051 The functions must take a single argument, the name of the property, and
15052 return a flat list of allowed values. If \":ETC\" is one of
15053 the values, this means that these values are intended as defaults for
15054 completion, but that other values should be allowed too.
15055 The functions must return nil if they are not responsible for this
15056 property.")
15058 (defun org-property-get-allowed-values (pom property &optional table)
15059 "Get allowed values for the property PROPERTY.
15060 When TABLE is non-nil, return an alist that can directly be used for
15061 completion."
15062 (let (vals)
15063 (cond
15064 ((equal property "TODO")
15065 (setq vals (org-with-point-at pom
15066 (append org-todo-keywords-1 '("")))))
15067 ((equal property "PRIORITY")
15068 (let ((n org-lowest-priority))
15069 (while (>= n org-highest-priority)
15070 (push (char-to-string n) vals)
15071 (setq n (1- n)))))
15072 ((member property org-special-properties))
15073 ((setq vals (run-hook-with-args-until-success
15074 'org-property-allowed-value-functions property)))
15076 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15077 (when (and vals (string-match "\\S-" vals))
15078 (setq vals (car (read-from-string (concat "(" vals ")"))))
15079 (setq vals (mapcar (lambda (x)
15080 (cond ((stringp x) x)
15081 ((numberp x) (number-to-string x))
15082 ((symbolp x) (symbol-name x))
15083 (t "???")))
15084 vals)))))
15085 (when (member ":ETC" vals)
15086 (setq vals (remove ":ETC" vals))
15087 (org-add-props (car vals) '(org-unrestricted t)))
15088 (if table (mapcar 'list vals) vals)))
15090 (defun org-property-previous-allowed-value (&optional previous)
15091 "Switch to the next allowed value for this property."
15092 (interactive)
15093 (org-property-next-allowed-value t))
15095 (defun org-property-next-allowed-value (&optional previous)
15096 "Switch to the next allowed value for this property."
15097 (interactive)
15098 (unless (org-at-property-p)
15099 (error "Not at a property"))
15100 (let* ((key (match-string 2))
15101 (value (match-string 3))
15102 (allowed (or (org-property-get-allowed-values (point) key)
15103 (and (member value '("[ ]" "[-]" "[X]"))
15104 '("[ ]" "[X]"))))
15105 nval)
15106 (unless allowed
15107 (error "Allowed values for this property have not been defined"))
15108 (if previous (setq allowed (reverse allowed)))
15109 (if (member value allowed)
15110 (setq nval (car (cdr (member value allowed)))))
15111 (setq nval (or nval (car allowed)))
15112 (if (equal nval value)
15113 (error "Only one allowed value for this property"))
15114 (org-at-property-p)
15115 (replace-match (concat " :" key ": " nval) t t)
15116 (org-indent-line)
15117 (beginning-of-line 1)
15118 (skip-chars-forward " \t")
15119 (run-hook-with-args 'org-property-changed-functions key nval)))
15121 (defun org-find-olp (path &optional this-buffer)
15122 "Return a marker pointing to the entry at outline path OLP.
15123 If anything goes wrong, throw an error.
15124 You can wrap this call to catch the error like this:
15126 (condition-case msg
15127 (org-mobile-locate-entry (match-string 4))
15128 (error (nth 1 msg)))
15130 The return value will then be either a string with the error message,
15131 or a marker if everything is OK.
15133 If THIS-BUFFER is set, the outline path does not contain a file,
15134 only headings."
15135 (let* ((file (if this-buffer buffer-file-name (pop path)))
15136 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15137 (level 1)
15138 (lmin 1)
15139 (lmax 1)
15140 limit re end found pos heading cnt flevel)
15141 (unless buffer (error "File not found :%s" file))
15142 (with-current-buffer buffer
15143 (save-excursion
15144 (save-restriction
15145 (widen)
15146 (setq limit (point-max))
15147 (goto-char (point-min))
15148 (while (setq heading (pop path))
15149 (setq re (format org-complex-heading-regexp-format
15150 (regexp-quote heading)))
15151 (setq cnt 0 pos (point))
15152 (while (re-search-forward re end t)
15153 (setq level (- (match-end 1) (match-beginning 1)))
15154 (if (and (>= level lmin) (<= level lmax))
15155 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15156 (when (= cnt 0) (error "Heading not found on level %d: %s"
15157 lmax heading))
15158 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15159 lmax heading))
15160 (goto-char found)
15161 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15162 (setq end (save-excursion (org-end-of-subtree t t))))
15163 (when (org-at-heading-p)
15164 (move-marker (make-marker) (point))))))))
15166 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15167 "Find node HEADING in BUFFER.
15168 Return a marker to the heading if it was found, or nil if not.
15169 If POS-ONLY is set, return just the position instead of a marker.
15171 The heading text must match exact, but it may have a TODO keyword,
15172 a priority cookie and tags in the standard locations."
15173 (with-current-buffer (or buffer (current-buffer))
15174 (save-excursion
15175 (save-restriction
15176 (widen)
15177 (goto-char (point-min))
15178 (let (case-fold-search)
15179 (if (re-search-forward
15180 (format org-complex-heading-regexp-format
15181 (regexp-quote heading)) nil t)
15182 (if pos-only
15183 (match-beginning 0)
15184 (move-marker (make-marker) (match-beginning 0)))))))))
15186 (defun org-find-exact-heading-in-directory (heading &optional dir)
15187 "Find Org node headline HEADING in all .org files in directory DIR.
15188 When the target headline is found, return a marker to this location."
15189 (let ((files (directory-files (or dir default-directory)
15190 nil "\\`[^.#].*\\.org\\'"))
15191 file visiting m buffer)
15192 (catch 'found
15193 (while (setq file (pop files))
15194 (message "trying %s" file)
15195 (setq visiting (org-find-base-buffer-visiting file))
15196 (setq buffer (or visiting (find-file-noselect file)))
15197 (setq m (org-find-exact-headline-in-buffer
15198 heading buffer))
15199 (when (and (not m) (not visiting)) (kill-buffer buffer))
15200 (and m (throw 'found m))))))
15202 (defun org-find-entry-with-id (ident)
15203 "Locate the entry that contains the ID property with exact value IDENT.
15204 IDENT can be a string, a symbol or a number, this function will search for
15205 the string representation of it.
15206 Return the position where this entry starts, or nil if there is no such entry."
15207 (interactive "sID: ")
15208 (let ((id (cond
15209 ((stringp ident) ident)
15210 ((symbol-name ident) (symbol-name ident))
15211 ((numberp ident) (number-to-string ident))
15212 (t (error "IDENT %s must be a string, symbol or number" ident))))
15213 (case-fold-search nil))
15214 (save-excursion
15215 (save-restriction
15216 (widen)
15217 (goto-char (point-min))
15218 (when (re-search-forward
15219 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15220 nil t)
15221 (org-back-to-heading t)
15222 (point))))))
15224 ;;;; Timestamps
15226 (defvar org-last-changed-timestamp nil)
15227 (defvar org-last-inserted-timestamp nil
15228 "The last time stamp inserted with `org-insert-time-stamp'.")
15229 (defvar org-time-was-given) ; dynamically scoped parameter
15230 (defvar org-end-time-was-given) ; dynamically scoped parameter
15231 (defvar org-ts-what) ; dynamically scoped parameter
15233 (defun org-time-stamp (arg &optional inactive)
15234 "Prompt for a date/time and insert a time stamp.
15235 If the user specifies a time like HH:MM or if this command is
15236 called with at least one prefix argument, the time stamp contains
15237 the date and the time. Otherwise, only the date is be included.
15239 All parts of a date not specified by the user is filled in from
15240 the current date/time. So if you just press return without
15241 typing anything, the time stamp will represent the current
15242 date/time.
15244 If there is already a timestamp at the cursor, it will be
15245 modified.
15247 With two universal prefix arguments, insert an active timestamp
15248 with the current time without prompting the user."
15249 (interactive "P")
15250 (let* ((ts nil)
15251 (default-time
15252 ;; Default time is either today, or, when entering a range,
15253 ;; the range start.
15254 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15255 (save-excursion
15256 (re-search-backward
15257 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15258 (- (point) 20) t)))
15259 (apply 'encode-time (org-parse-time-string (match-string 1)))
15260 (current-time)))
15261 (default-input (and ts (org-get-compact-tod ts)))
15262 (repeater (save-excursion
15263 (save-match-data
15264 (beginning-of-line)
15265 (when (re-search-forward
15266 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15267 (save-excursion (progn (end-of-line) (point))) t)
15268 (match-string 0)))))
15269 org-time-was-given org-end-time-was-given time)
15270 (cond
15271 ((and (org-at-timestamp-p t)
15272 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15273 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15274 (insert "--")
15275 (setq time (let ((this-command this-command))
15276 (org-read-date arg 'totime nil nil
15277 default-time default-input inactive)))
15278 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15279 ((org-at-timestamp-p t)
15280 (setq time (let ((this-command this-command))
15281 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15282 (when (org-at-timestamp-p t) ; just to get the match data
15283 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15284 (replace-match "")
15285 (setq org-last-changed-timestamp
15286 (org-insert-time-stamp
15287 time (or org-time-was-given arg)
15288 inactive nil nil (list org-end-time-was-given)))
15289 (when repeater (goto-char (1- (point))) (insert " " repeater)
15290 (setq org-last-changed-timestamp
15291 (concat (substring org-last-inserted-timestamp 0 -1)
15292 " " repeater ">"))))
15293 (message "Timestamp updated"))
15294 ((equal arg '(16))
15295 (org-insert-time-stamp (current-time) t))
15297 (setq time (let ((this-command this-command))
15298 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15299 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15300 nil nil (list org-end-time-was-given))))))
15302 ;; FIXME: can we use this for something else, like computing time differences?
15303 (defun org-get-compact-tod (s)
15304 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15305 (let* ((t1 (match-string 1 s))
15306 (h1 (string-to-number (match-string 2 s)))
15307 (m1 (string-to-number (match-string 3 s)))
15308 (t2 (and (match-end 4) (match-string 5 s)))
15309 (h2 (and t2 (string-to-number (match-string 6 s))))
15310 (m2 (and t2 (string-to-number (match-string 7 s))))
15311 dh dm)
15312 (if (not t2)
15314 (setq dh (- h2 h1) dm (- m2 m1))
15315 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15316 (concat t1 "+" (number-to-string dh)
15317 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15319 (defun org-time-stamp-inactive (&optional arg)
15320 "Insert an inactive time stamp.
15321 An inactive time stamp is enclosed in square brackets instead of angle
15322 brackets. It is inactive in the sense that it does not trigger agenda entries,
15323 does not link to the calendar and cannot be changed with the S-cursor keys.
15324 So these are more for recording a certain time/date."
15325 (interactive "P")
15326 (org-time-stamp arg 'inactive))
15328 (defvar org-date-ovl (make-overlay 1 1))
15329 (overlay-put org-date-ovl 'face 'org-date-selected)
15330 (org-detach-overlay org-date-ovl)
15332 (defvar org-ans1) ; dynamically scoped parameter
15333 (defvar org-ans2) ; dynamically scoped parameter
15335 (defvar org-plain-time-of-day-regexp) ; defined below
15337 (defvar org-overriding-default-time nil) ; dynamically scoped
15338 (defvar org-read-date-overlay nil)
15339 (defvar org-dcst nil) ; dynamically scoped
15340 (defvar org-read-date-history nil)
15341 (defvar org-read-date-final-answer nil)
15342 (defvar org-read-date-analyze-futurep nil)
15343 (defvar org-read-date-analyze-forced-year nil)
15344 (defvar org-read-date-inactive)
15346 (defun org-read-date (&optional org-with-time to-time from-string prompt
15347 default-time default-input inactive)
15348 "Read a date, possibly a time, and make things smooth for the user.
15349 The prompt will suggest to enter an ISO date, but you can also enter anything
15350 which will at least partially be understood by `parse-time-string'.
15351 Unrecognized parts of the date will default to the current day, month, year,
15352 hour and minute. If this command is called to replace a timestamp at point,
15353 or to enter the second timestamp of a range, the default time is taken
15354 from the existing stamp. Furthermore, the command prefers the future,
15355 so if you are giving a date where the year is not given, and the day-month
15356 combination is already past in the current year, it will assume you
15357 mean next year. For details, see the manual. A few examples:
15359 3-2-5 --> 2003-02-05
15360 feb 15 --> currentyear-02-15
15361 2/15 --> currentyear-02-15
15362 sep 12 9 --> 2009-09-12
15363 12:45 --> today 12:45
15364 22 sept 0:34 --> currentyear-09-22 0:34
15365 12 --> currentyear-currentmonth-12
15366 Fri --> nearest Friday (today or later)
15367 etc.
15369 Furthermore you can specify a relative date by giving, as the *first* thing
15370 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15371 change in days weeks, months, years.
15372 With a single plus or minus, the date is relative to today. With a double
15373 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15374 +4d --> four days from today
15375 +4 --> same as above
15376 +2w --> two weeks from today
15377 ++5 --> five days from default date
15379 The function understands only English month and weekday abbreviations.
15381 While prompting, a calendar is popped up - you can also select the
15382 date with the mouse (button 1). The calendar shows a period of three
15383 months. To scroll it to other months, use the keys `>' and `<'.
15384 If you don't like the calendar, turn it off with
15385 \(setq org-read-date-popup-calendar nil)
15387 With optional argument TO-TIME, the date will immediately be converted
15388 to an internal time.
15389 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15390 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15391 still enter a time, and this function will inform the calling routine
15392 about this change. The calling routine may then choose to change the
15393 format used to insert the time stamp into the buffer to include the time.
15394 With optional argument FROM-STRING, read from this string instead from
15395 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15396 the time/date that is used for everything that is not specified by the
15397 user."
15398 (require 'parse-time)
15399 (let* ((org-time-stamp-rounding-minutes
15400 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15401 (org-dcst org-display-custom-times)
15402 (ct (org-current-time))
15403 (org-def (or org-overriding-default-time default-time ct))
15404 (org-defdecode (decode-time org-def))
15405 (dummy (progn
15406 (when (< (nth 2 org-defdecode) org-extend-today-until)
15407 (setcar (nthcdr 2 org-defdecode) -1)
15408 (setcar (nthcdr 1 org-defdecode) 59)
15409 (setq org-def (apply 'encode-time org-defdecode)
15410 org-defdecode (decode-time org-def)))))
15411 (calendar-frame-setup nil)
15412 (calendar-setup nil)
15413 (calendar-move-hook nil)
15414 (calendar-view-diary-initially-flag nil)
15415 (calendar-view-holidays-initially-flag nil)
15416 (timestr (format-time-string
15417 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15418 (prompt (concat (if prompt (concat prompt " ") "")
15419 (format "Date+time [%s]: " timestr)))
15420 ans (org-ans0 "") org-ans1 org-ans2 final)
15422 (cond
15423 (from-string (setq ans from-string))
15424 (org-read-date-popup-calendar
15425 (save-excursion
15426 (save-window-excursion
15427 (calendar)
15428 (org-eval-in-calendar '(setq cursor-type nil) t)
15429 (unwind-protect
15430 (progn
15431 (calendar-forward-day (- (time-to-days org-def)
15432 (calendar-absolute-from-gregorian
15433 (calendar-current-date))))
15434 (org-eval-in-calendar nil t)
15435 (let* ((old-map (current-local-map))
15436 (map (copy-keymap calendar-mode-map))
15437 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15438 (org-defkey map (kbd "RET") 'org-calendar-select)
15439 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15440 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15441 (org-defkey minibuffer-local-map [(meta shift left)]
15442 (lambda () (interactive)
15443 (org-eval-in-calendar '(calendar-backward-month 1))))
15444 (org-defkey minibuffer-local-map [(meta shift right)]
15445 (lambda () (interactive)
15446 (org-eval-in-calendar '(calendar-forward-month 1))))
15447 (org-defkey minibuffer-local-map [(meta shift up)]
15448 (lambda () (interactive)
15449 (org-eval-in-calendar '(calendar-backward-year 1))))
15450 (org-defkey minibuffer-local-map [(meta shift down)]
15451 (lambda () (interactive)
15452 (org-eval-in-calendar '(calendar-forward-year 1))))
15453 (org-defkey minibuffer-local-map [?\e (shift left)]
15454 (lambda () (interactive)
15455 (org-eval-in-calendar '(calendar-backward-month 1))))
15456 (org-defkey minibuffer-local-map [?\e (shift right)]
15457 (lambda () (interactive)
15458 (org-eval-in-calendar '(calendar-forward-month 1))))
15459 (org-defkey minibuffer-local-map [?\e (shift up)]
15460 (lambda () (interactive)
15461 (org-eval-in-calendar '(calendar-backward-year 1))))
15462 (org-defkey minibuffer-local-map [?\e (shift down)]
15463 (lambda () (interactive)
15464 (org-eval-in-calendar '(calendar-forward-year 1))))
15465 (org-defkey minibuffer-local-map [(shift up)]
15466 (lambda () (interactive)
15467 (org-eval-in-calendar '(calendar-backward-week 1))))
15468 (org-defkey minibuffer-local-map [(shift down)]
15469 (lambda () (interactive)
15470 (org-eval-in-calendar '(calendar-forward-week 1))))
15471 (org-defkey minibuffer-local-map [(shift left)]
15472 (lambda () (interactive)
15473 (org-eval-in-calendar '(calendar-backward-day 1))))
15474 (org-defkey minibuffer-local-map [(shift right)]
15475 (lambda () (interactive)
15476 (org-eval-in-calendar '(calendar-forward-day 1))))
15477 (org-defkey minibuffer-local-map ">"
15478 (lambda () (interactive)
15479 (org-eval-in-calendar '(scroll-calendar-left 1))))
15480 (org-defkey minibuffer-local-map "<"
15481 (lambda () (interactive)
15482 (org-eval-in-calendar '(scroll-calendar-right 1))))
15483 (org-defkey minibuffer-local-map "\C-v"
15484 (lambda () (interactive)
15485 (org-eval-in-calendar
15486 '(calendar-scroll-left-three-months 1))))
15487 (org-defkey minibuffer-local-map "\M-v"
15488 (lambda () (interactive)
15489 (org-eval-in-calendar
15490 '(calendar-scroll-right-three-months 1))))
15491 (run-hooks 'org-read-date-minibuffer-setup-hook)
15492 (unwind-protect
15493 (progn
15494 (use-local-map map)
15495 (setq org-read-date-inactive inactive)
15496 (add-hook 'post-command-hook 'org-read-date-display)
15497 (setq org-ans0 (read-string prompt default-input
15498 'org-read-date-history nil))
15499 ;; org-ans0: from prompt
15500 ;; org-ans1: from mouse click
15501 ;; org-ans2: from calendar motion
15502 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15503 (remove-hook 'post-command-hook 'org-read-date-display)
15504 (use-local-map old-map)
15505 (when org-read-date-overlay
15506 (delete-overlay org-read-date-overlay)
15507 (setq org-read-date-overlay nil)))))
15508 (bury-buffer "*Calendar*")))))
15510 (t ; Naked prompt only
15511 (unwind-protect
15512 (setq ans (read-string prompt default-input
15513 'org-read-date-history timestr))
15514 (when org-read-date-overlay
15515 (delete-overlay org-read-date-overlay)
15516 (setq org-read-date-overlay nil)))))
15518 (setq final (org-read-date-analyze ans org-def org-defdecode))
15520 (when org-read-date-analyze-forced-year
15521 (message "Year was forced into %s"
15522 (if org-read-date-force-compatible-dates
15523 "compatible range (1970-2037)"
15524 "range representable on this machine"))
15525 (ding))
15527 ;; One round trip to get rid of 34th of August and stuff like that....
15528 (setq final (decode-time (apply 'encode-time final)))
15530 (setq org-read-date-final-answer ans)
15532 (if to-time
15533 (apply 'encode-time final)
15534 (if (and (boundp 'org-time-was-given) org-time-was-given)
15535 (format "%04d-%02d-%02d %02d:%02d"
15536 (nth 5 final) (nth 4 final) (nth 3 final)
15537 (nth 2 final) (nth 1 final))
15538 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15540 (defvar org-def)
15541 (defvar org-defdecode)
15542 (defvar org-with-time)
15543 (defun org-read-date-display ()
15544 "Display the current date prompt interpretation in the minibuffer."
15545 (when org-read-date-display-live
15546 (when org-read-date-overlay
15547 (delete-overlay org-read-date-overlay))
15548 (when (minibufferp (current-buffer))
15549 (save-excursion
15550 (end-of-line 1)
15551 (while (not (equal (buffer-substring
15552 (max (point-min) (- (point) 4)) (point))
15553 " "))
15554 (insert " ")))
15555 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15556 " " (or org-ans1 org-ans2)))
15557 (org-end-time-was-given nil)
15558 (f (org-read-date-analyze ans org-def org-defdecode))
15559 (fmts (if org-dcst
15560 org-time-stamp-custom-formats
15561 org-time-stamp-formats))
15562 (fmt (if (or org-with-time
15563 (and (boundp 'org-time-was-given) org-time-was-given))
15564 (cdr fmts)
15565 (car fmts)))
15566 (txt (format-time-string fmt (apply 'encode-time f)))
15567 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15568 (txt (concat "=> " txt)))
15569 (when (and org-end-time-was-given
15570 (string-match org-plain-time-of-day-regexp txt))
15571 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15572 org-end-time-was-given
15573 (substring txt (match-end 0)))))
15574 (when org-read-date-analyze-futurep
15575 (setq txt (concat txt " (=>F)")))
15576 (setq org-read-date-overlay
15577 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15578 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15580 (defun org-read-date-analyze (ans org-def org-defdecode)
15581 "Analyze the combined answer of the date prompt."
15582 ;; FIXME: cleanup and comment
15583 (let ((nowdecode (decode-time (current-time)))
15584 delta deltan deltaw deltadef year month day
15585 hour minute second wday pm h2 m2 tl wday1
15586 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15587 (setq org-read-date-analyze-futurep nil
15588 org-read-date-analyze-forced-year nil)
15589 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15590 (setq ans "+0"))
15592 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15593 (setq ans (replace-match "" t t ans)
15594 deltan (car delta)
15595 deltaw (nth 1 delta)
15596 deltadef (nth 2 delta)))
15598 ;; Check if there is an iso week date in there. If yes, store the
15599 ;; info and postpone interpreting it until the rest of the parsing
15600 ;; is done.
15601 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15602 (setq iso-year (if (match-end 1)
15603 (org-small-year-to-year
15604 (string-to-number (match-string 1 ans))))
15605 iso-weekday (if (match-end 3)
15606 (string-to-number (match-string 3 ans)))
15607 iso-week (string-to-number (match-string 2 ans)))
15608 (setq ans (replace-match "" t t ans)))
15610 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15611 (when (string-match
15612 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15613 (setq year (if (match-end 2)
15614 (string-to-number (match-string 2 ans))
15615 (progn (setq kill-year t)
15616 (string-to-number (format-time-string "%Y"))))
15617 month (string-to-number (match-string 3 ans))
15618 day (string-to-number (match-string 4 ans)))
15619 (if (< year 100) (setq year (+ 2000 year)))
15620 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15621 t nil ans)))
15623 ;; Help matching dotted european dates
15624 (when (string-match
15625 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\. ?\\([1-9][0-9][0-9][0-9]\\)?" ans)
15626 (setq year (if (match-end 3)
15627 (string-to-number (match-string 3 ans))
15628 (progn (setq kill-year t)
15629 (string-to-number (format-time-string "%Y"))))
15630 day (string-to-number (match-string 1 ans))
15631 month (string-to-number (match-string 2 ans))
15632 ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15633 t nil ans)))
15635 ;; Help matching american dates, like 5/30 or 5/30/7
15636 (when (string-match
15637 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15638 (setq year (if (match-end 4)
15639 (string-to-number (match-string 4 ans))
15640 (progn (setq kill-year t)
15641 (string-to-number (format-time-string "%Y"))))
15642 month (string-to-number (match-string 1 ans))
15643 day (string-to-number (match-string 2 ans)))
15644 (if (< year 100) (setq year (+ 2000 year)))
15645 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15646 t nil ans)))
15647 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15648 ;; If there is a time with am/pm, and *no* time without it, we convert
15649 ;; so that matching will be successful.
15650 (loop for i from 1 to 2 do ; twice, for end time as well
15651 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15652 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15653 (setq hour (string-to-number (match-string 1 ans))
15654 minute (if (match-end 3)
15655 (string-to-number (match-string 3 ans))
15657 pm (equal ?p
15658 (string-to-char (downcase (match-string 4 ans)))))
15659 (if (and (= hour 12) (not pm))
15660 (setq hour 0)
15661 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15662 (setq ans (replace-match (format "%02d:%02d" hour minute)
15663 t t ans))))
15665 ;; Check if a time range is given as a duration
15666 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15667 (setq hour (string-to-number (match-string 1 ans))
15668 h2 (+ hour (string-to-number (match-string 3 ans)))
15669 minute (string-to-number (match-string 2 ans))
15670 m2 (+ minute (if (match-end 5) (string-to-number
15671 (match-string 5 ans))0)))
15672 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15673 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15674 t t ans)))
15676 ;; Check if there is a time range
15677 (when (boundp 'org-end-time-was-given)
15678 (setq org-time-was-given nil)
15679 (when (and (string-match org-plain-time-of-day-regexp ans)
15680 (match-end 8))
15681 (setq org-end-time-was-given (match-string 8 ans))
15682 (setq ans (concat (substring ans 0 (match-beginning 7))
15683 (substring ans (match-end 7))))))
15685 (setq tl (parse-time-string ans)
15686 day (or (nth 3 tl) (nth 3 org-defdecode))
15687 month (or (nth 4 tl)
15688 (if (and org-read-date-prefer-future
15689 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15690 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15691 (nth 4 org-defdecode)))
15692 year (or (and (not kill-year) (nth 5 tl))
15693 (if (and org-read-date-prefer-future
15694 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15695 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15696 (nth 5 org-defdecode)))
15697 hour (or (nth 2 tl) (nth 2 org-defdecode))
15698 minute (or (nth 1 tl) (nth 1 org-defdecode))
15699 second (or (nth 0 tl) 0)
15700 wday (nth 6 tl))
15702 (when (and (eq org-read-date-prefer-future 'time)
15703 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15704 (equal day (nth 3 nowdecode))
15705 (equal month (nth 4 nowdecode))
15706 (equal year (nth 5 nowdecode))
15707 (nth 2 tl)
15708 (or (< (nth 2 tl) (nth 2 nowdecode))
15709 (and (= (nth 2 tl) (nth 2 nowdecode))
15710 (nth 1 tl)
15711 (< (nth 1 tl) (nth 1 nowdecode)))))
15712 (setq day (1+ day)
15713 futurep t))
15715 ;; Special date definitions below
15716 (cond
15717 (iso-week
15718 ;; There was an iso week
15719 (require 'cal-iso)
15720 (setq futurep nil)
15721 (setq year (or iso-year year)
15722 day (or iso-weekday wday 1)
15723 wday nil ; to make sure that the trigger below does not match
15724 iso-date (calendar-gregorian-from-absolute
15725 (calendar-absolute-from-iso
15726 (list iso-week day year))))
15727 ; FIXME: Should we also push ISO weeks into the future?
15728 ; (when (and org-read-date-prefer-future
15729 ; (not iso-year)
15730 ; (< (calendar-absolute-from-gregorian iso-date)
15731 ; (time-to-days (current-time))))
15732 ; (setq year (1+ year)
15733 ; iso-date (calendar-gregorian-from-absolute
15734 ; (calendar-absolute-from-iso
15735 ; (list iso-week day year)))))
15736 (setq month (car iso-date)
15737 year (nth 2 iso-date)
15738 day (nth 1 iso-date)))
15739 (deltan
15740 (setq futurep nil)
15741 (unless deltadef
15742 (let ((now (decode-time (current-time))))
15743 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15744 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15745 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15746 ((equal deltaw "m") (setq month (+ month deltan)))
15747 ((equal deltaw "y") (setq year (+ year deltan)))))
15748 ((and wday (not (nth 3 tl)))
15749 ;; Weekday was given, but no day, so pick that day in the week
15750 ;; on or after the derived date.
15751 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15752 (unless (equal wday wday1)
15753 (setq day (+ day (% (- wday wday1 -7) 7))))))
15754 (if (and (boundp 'org-time-was-given)
15755 (nth 2 tl))
15756 (setq org-time-was-given t))
15757 (if (< year 100) (setq year (+ 2000 year)))
15758 ;; Check of the date is representable
15759 (if org-read-date-force-compatible-dates
15760 (progn
15761 (if (< year 1970)
15762 (setq year 1970 org-read-date-analyze-forced-year t))
15763 (if (> year 2037)
15764 (setq year 2037 org-read-date-analyze-forced-year t)))
15765 (condition-case nil
15766 (ignore (encode-time second minute hour day month year))
15767 (error
15768 (setq year (nth 5 org-defdecode))
15769 (setq org-read-date-analyze-forced-year t))))
15770 (setq org-read-date-analyze-futurep futurep)
15771 (list second minute hour day month year)))
15773 (defvar parse-time-weekdays)
15774 (defun org-read-date-get-relative (s today default)
15775 "Check string S for special relative date string.
15776 TODAY and DEFAULT are internal times, for today and for a default.
15777 Return shift list (N what def-flag)
15778 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15779 N is the number of WHATs to shift.
15780 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15781 the DEFAULT date rather than TODAY."
15782 (require 'parse-time)
15783 (when (and
15784 (string-match
15785 (concat
15786 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15787 "\\([0-9]+\\)?"
15788 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15789 "\\([ \t]\\|$\\)") s)
15790 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15791 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15792 (string-to-char (substring (match-string 1 s) -1))
15793 ?+))
15794 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15795 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15796 (what (if (match-end 3) (match-string 3 s) "d"))
15797 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15798 (date (if rel default today))
15799 (wday (nth 6 (decode-time date)))
15800 delta)
15801 (if wday1
15802 (progn
15803 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15804 (if (= dir ?-) (setq delta (- delta 7)))
15805 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15806 (list delta "d" rel))
15807 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15809 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15810 "Turn a user-specified date into the internal representation.
15811 The internal representation needed by the calendar is (month day year).
15812 This is a wrapper to handle the brain-dead convention in calendar that
15813 user function argument order change dependent on argument order."
15814 (if (boundp 'calendar-date-style)
15815 (cond
15816 ((eq calendar-date-style 'american)
15817 (list arg1 arg2 arg3))
15818 ((eq calendar-date-style 'european)
15819 (list arg2 arg1 arg3))
15820 ((eq calendar-date-style 'iso)
15821 (list arg2 arg3 arg1)))
15822 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15823 (if (org-bound-and-true-p european-calendar-style)
15824 (list arg2 arg1 arg3)
15825 (list arg1 arg2 arg3)))))
15827 (defun org-eval-in-calendar (form &optional keepdate)
15828 "Eval FORM in the calendar window and return to current window.
15829 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15830 otherwise stick to the current value of `org-ans2'."
15831 (let ((sf (selected-frame))
15832 (sw (selected-window)))
15833 (select-window (get-buffer-window "*Calendar*" t))
15834 (eval form)
15835 (when (and (not keepdate) (calendar-cursor-to-date))
15836 (let* ((date (calendar-cursor-to-date))
15837 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15838 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15839 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15840 (select-window sw)
15841 (org-select-frame-set-input-focus sf)))
15843 (defun org-calendar-select ()
15844 "Return to `org-read-date' with the date currently selected.
15845 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15846 (interactive)
15847 (when (calendar-cursor-to-date)
15848 (let* ((date (calendar-cursor-to-date))
15849 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15850 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15851 (if (active-minibuffer-window) (exit-minibuffer))))
15853 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15854 "Insert a date stamp for the date given by the internal TIME.
15855 WITH-HM means use the stamp format that includes the time of the day.
15856 INACTIVE means use square brackets instead of angular ones, so that the
15857 stamp will not contribute to the agenda.
15858 PRE and POST are optional strings to be inserted before and after the
15859 stamp.
15860 The command returns the inserted time stamp."
15861 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15862 stamp)
15863 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15864 (insert-before-markers (or pre ""))
15865 (when (listp extra)
15866 (setq extra (car extra))
15867 (if (and (stringp extra)
15868 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15869 (setq extra (format "-%02d:%02d"
15870 (string-to-number (match-string 1 extra))
15871 (string-to-number (match-string 2 extra))))
15872 (setq extra nil)))
15873 (when extra
15874 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15875 (insert-before-markers (setq stamp (format-time-string fmt time)))
15876 (insert-before-markers (or post ""))
15877 (setq org-last-inserted-timestamp stamp)))
15879 (defun org-toggle-time-stamp-overlays ()
15880 "Toggle the use of custom time stamp formats."
15881 (interactive)
15882 (setq org-display-custom-times (not org-display-custom-times))
15883 (unless org-display-custom-times
15884 (let ((p (point-min)) (bmp (buffer-modified-p)))
15885 (while (setq p (next-single-property-change p 'display))
15886 (if (and (get-text-property p 'display)
15887 (eq (get-text-property p 'face) 'org-date))
15888 (remove-text-properties
15889 p (setq p (next-single-property-change p 'display))
15890 '(display t))))
15891 (set-buffer-modified-p bmp)))
15892 (if (featurep 'xemacs)
15893 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15894 (org-restart-font-lock)
15895 (setq org-table-may-need-update t)
15896 (if org-display-custom-times
15897 (message "Time stamps are overlaid with custom format")
15898 (message "Time stamp overlays removed")))
15900 (defun org-display-custom-time (beg end)
15901 "Overlay modified time stamp format over timestamp between BEG and END."
15902 (let* ((ts (buffer-substring beg end))
15903 t1 w1 with-hm tf time str w2 (off 0))
15904 (save-match-data
15905 (setq t1 (org-parse-time-string ts t))
15906 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
15907 (setq off (- (match-end 0) (match-beginning 0)))))
15908 (setq end (- end off))
15909 (setq w1 (- end beg)
15910 with-hm (and (nth 1 t1) (nth 2 t1))
15911 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15912 time (org-fix-decoded-time t1)
15913 str (org-add-props
15914 (format-time-string
15915 (substring tf 1 -1) (apply 'encode-time time))
15916 nil 'mouse-face 'highlight)
15917 w2 (length str))
15918 (if (not (= w2 w1))
15919 (add-text-properties (1+ beg) (+ 2 beg)
15920 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15921 (if (featurep 'xemacs)
15922 (progn
15923 (put-text-property beg end 'invisible t)
15924 (put-text-property beg end 'end-glyph (make-glyph str)))
15925 (put-text-property beg end 'display str))))
15927 (defun org-translate-time (string)
15928 "Translate all timestamps in STRING to custom format.
15929 But do this only if the variable `org-display-custom-times' is set."
15930 (when org-display-custom-times
15931 (save-match-data
15932 (let* ((start 0)
15933 (re org-ts-regexp-both)
15934 t1 with-hm inactive tf time str beg end)
15935 (while (setq start (string-match re string start))
15936 (setq beg (match-beginning 0)
15937 end (match-end 0)
15938 t1 (save-match-data
15939 (org-parse-time-string (substring string beg end) t))
15940 with-hm (and (nth 1 t1) (nth 2 t1))
15941 inactive (equal (substring string beg (1+ beg)) "[")
15942 tf (funcall (if with-hm 'cdr 'car)
15943 org-time-stamp-custom-formats)
15944 time (org-fix-decoded-time t1)
15945 str (format-time-string
15946 (concat
15947 (if inactive "[" "<") (substring tf 1 -1)
15948 (if inactive "]" ">"))
15949 (apply 'encode-time time))
15950 string (replace-match str t t string)
15951 start (+ start (length str)))))))
15952 string)
15954 (defun org-fix-decoded-time (time)
15955 "Set 0 instead of nil for the first 6 elements of time.
15956 Don't touch the rest."
15957 (let ((n 0))
15958 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15960 (defun org-days-to-time (timestamp-string)
15961 "Difference between TIMESTAMP-STRING and now in days."
15962 (- (time-to-days (org-time-string-to-time timestamp-string))
15963 (time-to-days (current-time))))
15965 (defun org-deadline-close (timestamp-string &optional ndays)
15966 "Is the time in TIMESTAMP-STRING close to the current date?"
15967 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15968 (and (< (org-days-to-time timestamp-string) ndays)
15969 (not (org-entry-is-done-p))))
15971 (defun org-get-wdays (ts)
15972 "Get the deadline lead time appropriate for timestring TS."
15973 (cond
15974 ((<= org-deadline-warning-days 0)
15975 ;; 0 or negative, enforce this value no matter what
15976 (- org-deadline-warning-days))
15977 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
15978 ;; lead time is specified.
15979 (floor (* (string-to-number (match-string 1 ts))
15980 (cdr (assoc (match-string 2 ts)
15981 '(("d" . 1) ("w" . 7)
15982 ("m" . 30.4) ("y" . 365.25)))))))
15983 ;; go for the default.
15984 (t org-deadline-warning-days)))
15986 (defun org-calendar-select-mouse (ev)
15987 "Return to `org-read-date' with the date currently selected.
15988 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15989 (interactive "e")
15990 (mouse-set-point ev)
15991 (when (calendar-cursor-to-date)
15992 (let* ((date (calendar-cursor-to-date))
15993 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15994 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15995 (if (active-minibuffer-window) (exit-minibuffer))))
15997 (defun org-check-deadlines (ndays)
15998 "Check if there are any deadlines due or past due.
15999 A deadline is considered due if it happens within `org-deadline-warning-days'
16000 days from today's date. If the deadline appears in an entry marked DONE,
16001 it is not shown. The prefix arg NDAYS can be used to test that many
16002 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16003 (interactive "P")
16004 (let* ((org-warn-days
16005 (cond
16006 ((equal ndays '(4)) 100000)
16007 (ndays (prefix-numeric-value ndays))
16008 (t (abs org-deadline-warning-days))))
16009 (case-fold-search nil)
16010 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16011 (callback
16012 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16014 (message "%d deadlines past-due or due within %d days"
16015 (org-occur regexp nil callback)
16016 org-warn-days)))
16018 (defsubst org-re-timestamp (type)
16019 "Return a regexp for timestamp TYPE.
16020 Allowed values for TYPE are:
16022 all: all timestamps
16023 active: only active timestamps (<...>)
16024 inactive: only inactive timestamps ([...])
16025 scheduled: only scheduled timestamps
16026 deadline: only deadline timestamps
16028 When TYPE is nil, fall back on returning a regexp that matches
16029 both scheduled and deadline timestamps."
16030 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16031 ((eq type 'active) org-ts-regexp)
16032 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16033 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16034 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16035 ((eq type 'scheduled-or-deadline)
16036 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16038 (defun org-check-before-date (date)
16039 "Check if there are deadlines or scheduled entries before DATE."
16040 (interactive (list (org-read-date)))
16041 (let ((case-fold-search nil)
16042 (regexp (org-re-timestamp org-ts-type))
16043 (callback
16044 (lambda () (time-less-p
16045 (org-time-string-to-time (match-string 1))
16046 (org-time-string-to-time date)))))
16047 (message "%d entries before %s"
16048 (org-occur regexp nil callback) date)))
16050 (defun org-check-after-date (date)
16051 "Check if there are deadlines or scheduled entries after DATE."
16052 (interactive (list (org-read-date)))
16053 (let ((case-fold-search nil)
16054 (regexp (org-re-timestamp org-ts-type))
16055 (callback
16056 (lambda () (not
16057 (time-less-p
16058 (org-time-string-to-time (match-string 1))
16059 (org-time-string-to-time date))))))
16060 (message "%d entries after %s"
16061 (org-occur regexp nil callback) date)))
16063 (defun org-check-dates-range (start-date end-date)
16064 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16065 (interactive (list (org-read-date nil nil nil "Range starts")
16066 (org-read-date nil nil nil "Range end")))
16067 (let ((case-fold-search nil)
16068 (regexp (org-re-timestamp org-ts-type))
16069 (callback
16070 (lambda ()
16071 (let ((match (match-string 1)))
16072 (and
16073 (not (time-less-p
16074 (org-time-string-to-time match)
16075 (org-time-string-to-time start-date)))
16076 (time-less-p
16077 (org-time-string-to-time match)
16078 (org-time-string-to-time end-date)))))))
16079 (message "%d entries between %s and %s"
16080 (org-occur regexp nil callback) start-date end-date)))
16082 (defun org-evaluate-time-range (&optional to-buffer)
16083 "Evaluate a time range by computing the difference between start and end.
16084 Normally the result is just printed in the echo area, but with prefix arg
16085 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16086 If the time range is actually in a table, the result is inserted into the
16087 next column.
16088 For time difference computation, a year is assumed to be exactly 365
16089 days in order to avoid rounding problems."
16090 (interactive "P")
16092 (org-clock-update-time-maybe)
16093 (save-excursion
16094 (unless (org-at-date-range-p t)
16095 (goto-char (point-at-bol))
16096 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16097 (if (not (org-at-date-range-p t))
16098 (error "Not at a time-stamp range, and none found in current line")))
16099 (let* ((ts1 (match-string 1))
16100 (ts2 (match-string 2))
16101 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16102 (match-end (match-end 0))
16103 (time1 (org-time-string-to-time ts1))
16104 (time2 (org-time-string-to-time ts2))
16105 (t1 (org-float-time time1))
16106 (t2 (org-float-time time2))
16107 (diff (abs (- t2 t1)))
16108 (negative (< (- t2 t1) 0))
16109 ;; (ys (floor (* 365 24 60 60)))
16110 (ds (* 24 60 60))
16111 (hs (* 60 60))
16112 (fy "%dy %dd %02d:%02d")
16113 (fy1 "%dy %dd")
16114 (fd "%dd %02d:%02d")
16115 (fd1 "%dd")
16116 (fh "%02d:%02d")
16117 y d h m align)
16118 (if havetime
16119 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16121 d (floor (/ diff ds)) diff (mod diff ds)
16122 h (floor (/ diff hs)) diff (mod diff hs)
16123 m (floor (/ diff 60)))
16124 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16126 d (floor (+ (/ diff ds) 0.5))
16127 h 0 m 0))
16128 (if (not to-buffer)
16129 (message "%s" (org-make-tdiff-string y d h m))
16130 (if (org-at-table-p)
16131 (progn
16132 (goto-char match-end)
16133 (setq align t)
16134 (and (looking-at " *|") (goto-char (match-end 0))))
16135 (goto-char match-end))
16136 (if (looking-at
16137 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16138 (replace-match ""))
16139 (if negative (insert " -"))
16140 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16141 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16142 (insert " " (format fh h m))))
16143 (if align (org-table-align))
16144 (message "Time difference inserted")))))
16146 (defun org-make-tdiff-string (y d h m)
16147 (let ((fmt "")
16148 (l nil))
16149 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16150 l (push y l)))
16151 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16152 l (push d l)))
16153 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16154 l (push h l)))
16155 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16156 l (push m l)))
16157 (apply 'format fmt (nreverse l))))
16159 (defun org-time-string-to-time (s &optional buffer pos)
16160 "Convert a timestamp string into internal time."
16161 (condition-case errdata
16162 (apply 'encode-time (org-parse-time-string s))
16163 (error (error "Bad timestamp `%s'%s\nError was: %s"
16164 s (if (not (and buffer pos))
16166 (format " at %d in buffer `%s'" pos buffer))
16167 (cdr errdata)))))
16169 (defun org-time-string-to-seconds (s)
16170 "Convert a timestamp string to a number of seconds."
16171 (org-float-time (org-time-string-to-time s)))
16173 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16174 "Convert a time stamp to an absolute day number.
16175 If there is a specifier for a cyclic time stamp, get the closest date to
16176 DAYNR.
16177 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16178 The variable date is bound by the calendar when this is called."
16179 (cond
16180 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16181 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16182 daynr
16183 (+ daynr 1000)))
16184 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16185 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16186 (time-to-days (current-time))) (match-string 0 s)
16187 prefer show-all))
16188 (t (time-to-days
16189 (condition-case errdata
16190 (apply 'encode-time (org-parse-time-string s))
16191 (error (error "Bad timestamp `%s'%s\nError was: %s"
16192 s (if (not (and buffer pos))
16194 (format " at %d in buffer `%s'" pos buffer))
16195 (cdr errdata))))))))
16197 (defun org-days-to-iso-week (days)
16198 "Return the iso week number."
16199 (require 'cal-iso)
16200 (car (calendar-iso-from-absolute days)))
16202 (defun org-small-year-to-year (year)
16203 "Convert 2-digit years into 4-digit years.
16204 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16205 The year 2000 cannot be abbreviated. Any year larger than 99
16206 is returned unchanged."
16207 (if (< year 38)
16208 (setq year (+ 2000 year))
16209 (if (< year 100)
16210 (setq year (+ 1900 year))))
16211 year)
16213 (defun org-time-from-absolute (d)
16214 "Return the time corresponding to date D.
16215 D may be an absolute day number, or a calendar-type list (month day year)."
16216 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16217 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16219 (defun org-calendar-holiday ()
16220 "List of holidays, for Diary display in Org-mode."
16221 (require 'holidays)
16222 (let ((hl (funcall
16223 (if (fboundp 'calendar-check-holidays)
16224 'calendar-check-holidays 'check-calendar-holidays) date)))
16225 (if hl (mapconcat 'identity hl "; "))))
16227 (defun org-diary-sexp-entry (sexp entry date)
16228 "Process a SEXP diary ENTRY for DATE."
16229 (require 'diary-lib)
16230 (let ((result (if calendar-debug-sexp
16231 (let ((stack-trace-on-error t))
16232 (eval (car (read-from-string sexp))))
16233 (condition-case nil
16234 (eval (car (read-from-string sexp)))
16235 (error
16236 (beep)
16237 (message "Bad sexp at line %d in %s: %s"
16238 (org-current-line)
16239 (buffer-file-name) sexp)
16240 (sleep-for 2))))))
16241 (cond ((stringp result) (split-string result "; "))
16242 ((and (consp result)
16243 (not (consp (cdr result)))
16244 (stringp (cdr result))) (cdr result))
16245 ((and (consp result)
16246 (stringp (car result))) result)
16247 (result entry))))
16249 (defun org-diary-to-ical-string (frombuf)
16250 "Get iCalendar entries from diary entries in buffer FROMBUF.
16251 This uses the icalendar.el library."
16252 (let* ((tmpdir (if (featurep 'xemacs)
16253 (temp-directory)
16254 temporary-file-directory))
16255 (tmpfile (make-temp-name
16256 (expand-file-name "orgics" tmpdir)))
16257 buf rtn b e)
16258 (with-current-buffer frombuf
16259 (icalendar-export-region (point-min) (point-max) tmpfile)
16260 (setq buf (find-buffer-visiting tmpfile))
16261 (set-buffer buf)
16262 (goto-char (point-min))
16263 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16264 (setq b (match-beginning 0)))
16265 (goto-char (point-max))
16266 (if (re-search-backward "^END:VEVENT" nil t)
16267 (setq e (match-end 0)))
16268 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16269 (kill-buffer buf)
16270 (delete-file tmpfile)
16271 rtn))
16273 (defun org-closest-date (start current change prefer show-all)
16274 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16275 When PREFER is `past', return a date that is either CURRENT or past.
16276 When PREFER is `future', return a date that is either CURRENT or future.
16277 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16278 ;; Make the proper lists from the dates
16279 (catch 'exit
16280 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16281 dn dw sday cday n1 n2 n0
16282 d m y y1 y2 date1 date2 nmonths nm ny m2)
16284 (setq start (org-date-to-gregorian start)
16285 current (org-date-to-gregorian
16286 (if show-all
16287 current
16288 (time-to-days (current-time))))
16289 sday (calendar-absolute-from-gregorian start)
16290 cday (calendar-absolute-from-gregorian current))
16292 (if (<= cday sday) (throw 'exit sday))
16294 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16295 (setq dn (string-to-number (match-string 1 change))
16296 dw (cdr (assoc (match-string 2 change) a1)))
16297 (error "Invalid change specifier: %s" change))
16298 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16299 (cond
16300 ((eq dw 'day)
16301 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16302 n2 (+ n1 dn)))
16303 ((eq dw 'year)
16304 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16305 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16306 (setq date1 (list m d y1)
16307 n1 (calendar-absolute-from-gregorian date1)
16308 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16309 n2 (calendar-absolute-from-gregorian date2)))
16310 ((eq dw 'month)
16311 ;; approx number of month between the two dates
16312 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16313 ;; How often does dn fit in there?
16314 (setq d (nth 1 start) m (car start) y (nth 2 start)
16315 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16316 m (+ m nm)
16317 ny (floor (/ m 12))
16318 y (+ y ny)
16319 m (- m (* ny 12)))
16320 (while (> m 12) (setq m (- m 12) y (1+ y)))
16321 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16322 (setq m2 (+ m dn) y2 y)
16323 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16324 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16325 (while (<= n2 cday)
16326 (setq n1 n2 m m2 y y2)
16327 (setq m2 (+ m dn) y2 y)
16328 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16329 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16330 ;; Make sure n1 is the earlier date
16331 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16332 (if show-all
16333 (cond
16334 ((eq prefer 'past) (if (= cday n2) n2 n1))
16335 ((eq prefer 'future) (if (= cday n1) n1 n2))
16336 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16337 (cond
16338 ((eq prefer 'past) (if (= cday n2) n2 n1))
16339 ((eq prefer 'future) (if (= cday n1) n1 n2))
16340 (t (if (= cday n1) n1 n2)))))))
16342 (defun org-date-to-gregorian (date)
16343 "Turn any specification of DATE into a Gregorian date for the calendar."
16344 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16345 ((and (listp date) (= (length date) 3)) date)
16346 ((stringp date)
16347 (setq date (org-parse-time-string date))
16348 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16349 ((listp date)
16350 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16352 (defun org-parse-time-string (s &optional nodefault)
16353 "Parse the standard Org-mode time string.
16354 This should be a lot faster than the normal `parse-time-string'.
16355 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16356 hour and minute fields will be nil if not given."
16357 (if (string-match org-ts-regexp0 s)
16358 (list 0
16359 (if (or (match-beginning 8) (not nodefault))
16360 (string-to-number (or (match-string 8 s) "0")))
16361 (if (or (match-beginning 7) (not nodefault))
16362 (string-to-number (or (match-string 7 s) "0")))
16363 (string-to-number (match-string 4 s))
16364 (string-to-number (match-string 3 s))
16365 (string-to-number (match-string 2 s))
16366 nil nil nil)
16367 (error "Not a standard Org-mode time string: %s" s)))
16369 (defun org-timestamp-up (&optional arg)
16370 "Increase the date item at the cursor by one.
16371 If the cursor is on the year, change the year. If it is on the month,
16372 the day or the time, change that.
16373 With prefix ARG, change by that many units."
16374 (interactive "p")
16375 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16377 (defun org-timestamp-down (&optional arg)
16378 "Decrease the date item at the cursor by one.
16379 If the cursor is on the year, change the year. If it is on the month,
16380 the day or the time, change that.
16381 With prefix ARG, change by that many units."
16382 (interactive "p")
16383 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16385 (defun org-timestamp-up-day (&optional arg)
16386 "Increase the date in the time stamp by one day.
16387 With prefix ARG, change that many days."
16388 (interactive "p")
16389 (if (and (not (org-at-timestamp-p t))
16390 (org-at-heading-p))
16391 (org-todo 'up)
16392 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16394 (defun org-timestamp-down-day (&optional arg)
16395 "Decrease the date in the time stamp by one day.
16396 With prefix ARG, change that many days."
16397 (interactive "p")
16398 (if (and (not (org-at-timestamp-p t))
16399 (org-at-heading-p))
16400 (org-todo 'down)
16401 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16403 (defun org-at-timestamp-p (&optional inactive-ok)
16404 "Determine if the cursor is in or at a timestamp."
16405 (interactive)
16406 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16407 (pos (point))
16408 (ans (or (looking-at tsr)
16409 (save-excursion
16410 (skip-chars-backward "^[<\n\r\t")
16411 (if (> (point) (point-min)) (backward-char 1))
16412 (and (looking-at tsr)
16413 (> (- (match-end 0) pos) -1))))))
16414 (and ans
16415 (boundp 'org-ts-what)
16416 (setq org-ts-what
16417 (cond
16418 ((= pos (match-beginning 0)) 'bracket)
16419 ;; Point is considered to be "on the bracket" whether
16420 ;; it's really on it or right after it.
16421 ((= pos (1- (match-end 0))) 'bracket)
16422 ((= pos (match-end 0)) 'after)
16423 ((org-pos-in-match-range pos 2) 'year)
16424 ((org-pos-in-match-range pos 3) 'month)
16425 ((org-pos-in-match-range pos 7) 'hour)
16426 ((org-pos-in-match-range pos 8) 'minute)
16427 ((or (org-pos-in-match-range pos 4)
16428 (org-pos-in-match-range pos 5)) 'day)
16429 ((and (> pos (or (match-end 8) (match-end 5)))
16430 (< pos (match-end 0)))
16431 (- pos (or (match-end 8) (match-end 5))))
16432 (t 'day))))
16433 ans))
16435 (defun org-toggle-timestamp-type ()
16436 "Toggle the type (<active> or [inactive]) of a time stamp."
16437 (interactive)
16438 (when (org-at-timestamp-p t)
16439 (let ((beg (match-beginning 0)) (end (match-end 0))
16440 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16441 (save-excursion
16442 (goto-char beg)
16443 (while (re-search-forward "[][<>]" end t)
16444 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16445 t t)))
16446 (message "Timestamp is now %sactive"
16447 (if (equal (char-after beg) ?<) "" "in")))))
16449 (defvar org-clock-history) ; defined in org-clock.el
16450 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16451 (defun org-timestamp-change (n &optional what updown)
16452 "Change the date in the time stamp at point.
16453 The date will be changed by N times WHAT. WHAT can be `day', `month',
16454 `year', `minute', `second'. If WHAT is not given, the cursor position
16455 in the timestamp determines what will be changed."
16456 (let ((origin (point)) origin-cat
16457 with-hm inactive
16458 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16459 org-ts-what
16460 extra rem
16461 ts time time0 fixnext clrgx)
16462 (if (not (org-at-timestamp-p t))
16463 (error "Not at a timestamp"))
16464 (if (and (not what) (eq org-ts-what 'bracket))
16465 (org-toggle-timestamp-type)
16466 ;; Point isn't on brackets. Remember the part of the time-stamp
16467 ;; the point was in. Indeed, size of time-stamps may change,
16468 ;; but point must be kept in the same category nonetheless.
16469 (setq origin-cat org-ts-what)
16470 (if (and (not what) (not (eq org-ts-what 'day))
16471 org-display-custom-times
16472 (get-text-property (point) 'display)
16473 (not (get-text-property (1- (point)) 'display)))
16474 (setq org-ts-what 'day))
16475 (setq org-ts-what (or what org-ts-what)
16476 inactive (= (char-after (match-beginning 0)) ?\[)
16477 ts (match-string 0))
16478 (replace-match "")
16479 (if (string-match
16480 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16482 (setq extra (match-string 1 ts)))
16483 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16484 (setq with-hm t))
16485 (setq time0 (org-parse-time-string ts))
16486 (when (and updown
16487 (eq org-ts-what 'minute)
16488 (not current-prefix-arg))
16489 ;; This looks like s-up and s-down. Change by one rounding step.
16490 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16491 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16492 (setcar (cdr time0) (+ (nth 1 time0)
16493 (if (> n 0) (- rem) (- dm rem))))))
16494 (setq time
16495 (encode-time (or (car time0) 0)
16496 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16497 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16498 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16499 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16500 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16501 (nthcdr 6 time0)))
16502 (when (and (member org-ts-what '(hour minute))
16503 extra
16504 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16505 (setq extra (org-modify-ts-extra
16506 extra
16507 (if (eq org-ts-what 'hour) 2 5)
16508 n dm)))
16509 (when (integerp org-ts-what)
16510 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16511 (if (eq what 'calendar)
16512 (let ((cal-date (org-get-date-from-calendar)))
16513 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16514 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16515 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16516 (setcar time0 (or (car time0) 0))
16517 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16518 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16519 (setq time (apply 'encode-time time0))))
16520 ;; Insert the new time-stamp, and ensure point stays in the same
16521 ;; category as before (i.e. not after the last position in that
16522 ;; category).
16523 (let ((pos (point)))
16524 ;; Stay before inserted string. `save-excursion' is of no use.
16525 (setq org-last-changed-timestamp
16526 (org-insert-time-stamp time with-hm inactive nil nil extra))
16527 (goto-char pos))
16528 (save-match-data
16529 (looking-at org-ts-regexp3)
16530 (goto-char (cond
16531 ;; `day' category ends before `hour' if any, or at
16532 ;; the end of the day name.
16533 ((eq origin-cat 'day)
16534 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16535 ((eq origin-cat 'hour) (min (match-end 7) origin))
16536 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16537 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16538 ;; `year' and `month' have both fixed size: point
16539 ;; couldn't have moved into another part.
16540 (t origin))))
16541 ;; Update clock if on a CLOCK line.
16542 (org-clock-update-time-maybe)
16543 ;; Maybe adjust the closest clock in `org-clock-history'
16544 (when org-clock-adjust-closest
16545 (if (not (and (org-at-clock-log-p)
16546 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16547 org-clock-history))))))
16548 (message "No clock to adjust")
16549 (cond ((save-excursion ; fix previous clock?
16550 (re-search-backward org-ts-regexp0 nil t)
16551 (org-looking-back (concat org-clock-string " \\[")))
16552 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16553 ((save-excursion ; fix next clock?
16554 (re-search-backward org-ts-regexp0 nil t)
16555 (looking-at (concat org-ts-regexp0 "\\] =>")))
16556 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16557 (save-window-excursion
16558 ;; Find closest clock to point, adjust the previous/next one in history
16559 (let* ((p (save-excursion (org-back-to-heading t)))
16560 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16561 (clfixnth
16562 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16563 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16564 (if (not clfixpos)
16565 (message "No clock to adjust")
16566 (save-excursion
16567 (org-goto-marker-or-bmk clfixpos)
16568 (org-show-subtree)
16569 (when (re-search-forward clrgx nil t)
16570 (goto-char (match-beginning 1))
16571 (let (org-clock-adjust-closest)
16572 (org-timestamp-change n org-ts-what updown))
16573 (message "Clock adjusted in %s for heading: %s"
16574 (file-name-nondirectory (buffer-file-name))
16575 (org-get-heading t t)))))))))
16576 ;; Try to recenter the calendar window, if any.
16577 (if (and org-calendar-follow-timestamp-change
16578 (get-buffer-window "*Calendar*" t)
16579 (memq org-ts-what '(day month year)))
16580 (org-recenter-calendar (time-to-days time))))))
16582 (defun org-modify-ts-extra (s pos n dm)
16583 "Change the different parts of the lead-time and repeat fields in timestamp."
16584 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16585 ng h m new rem)
16586 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16587 (cond
16588 ((or (org-pos-in-match-range pos 2)
16589 (org-pos-in-match-range pos 3))
16590 (setq m (string-to-number (match-string 3 s))
16591 h (string-to-number (match-string 2 s)))
16592 (if (org-pos-in-match-range pos 2)
16593 (setq h (+ h n))
16594 (setq n (* dm (org-no-warnings (signum n))))
16595 (when (not (= 0 (setq rem (% m dm))))
16596 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16597 (setq m (+ m n)))
16598 (if (< m 0) (setq m (+ m 60) h (1- h)))
16599 (if (> m 59) (setq m (- m 60) h (1+ h)))
16600 (setq h (min 24 (max 0 h)))
16601 (setq ng 1 new (format "-%02d:%02d" h m)))
16602 ((org-pos-in-match-range pos 6)
16603 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16604 ((org-pos-in-match-range pos 5)
16605 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16607 ((org-pos-in-match-range pos 9)
16608 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16609 ((org-pos-in-match-range pos 8)
16610 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16612 (when ng
16613 (setq s (concat
16614 (substring s 0 (match-beginning ng))
16616 (substring s (match-end ng))))))
16619 (defun org-recenter-calendar (date)
16620 "If the calendar is visible, recenter it to DATE."
16621 (let ((cwin (get-buffer-window "*Calendar*" t)))
16622 (when cwin
16623 (let ((calendar-move-hook nil))
16624 (with-selected-window cwin
16625 (calendar-goto-date (if (listp date) date
16626 (calendar-gregorian-from-absolute date))))))))
16628 (defun org-goto-calendar (&optional arg)
16629 "Go to the Emacs calendar at the current date.
16630 If there is a time stamp in the current line, go to that date.
16631 A prefix ARG can be used to force the current date."
16632 (interactive "P")
16633 (let ((tsr org-ts-regexp) diff
16634 (calendar-move-hook nil)
16635 (calendar-view-holidays-initially-flag nil)
16636 (calendar-view-diary-initially-flag nil))
16637 (if (or (org-at-timestamp-p)
16638 (save-excursion
16639 (beginning-of-line 1)
16640 (looking-at (concat ".*" tsr))))
16641 (let ((d1 (time-to-days (current-time)))
16642 (d2 (time-to-days
16643 (org-time-string-to-time (match-string 1)))))
16644 (setq diff (- d2 d1))))
16645 (calendar)
16646 (calendar-goto-today)
16647 (if (and diff (not arg)) (calendar-forward-day diff))))
16649 (defun org-get-date-from-calendar ()
16650 "Return a list (month day year) of date at point in calendar."
16651 (with-current-buffer "*Calendar*"
16652 (save-match-data
16653 (calendar-cursor-to-date))))
16655 (defun org-date-from-calendar ()
16656 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16657 If there is already a time stamp at the cursor position, update it."
16658 (interactive)
16659 (if (org-at-timestamp-p t)
16660 (org-timestamp-change 0 'calendar)
16661 (let ((cal-date (org-get-date-from-calendar)))
16662 (org-insert-time-stamp
16663 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16665 (defun org-minutes-to-hh:mm-string (m)
16666 "Compute H:MM from a number of minutes."
16667 (let ((h (/ m 60)))
16668 (setq m (- m (* 60 h)))
16669 (format org-time-clocksum-format h m)))
16671 (defun org-hh:mm-string-to-minutes (s)
16672 "Convert a string H:MM to a number of minutes.
16673 If the string is just a number, interpret it as minutes.
16674 In fact, the first hh:mm or number in the string will be taken,
16675 there can be extra stuff in the string.
16676 If no number is found, the return value is 0."
16677 (cond
16678 ((integerp s) s)
16679 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16680 (+ (* (string-to-number (match-string 1 s)) 60)
16681 (string-to-number (match-string 2 s))))
16682 ((string-match "\\([0-9]+\\)" s)
16683 (string-to-number (match-string 1 s)))
16684 (t 0)))
16686 (defcustom org-effort-durations
16687 `(("h" . 60)
16688 ("d" . ,(* 60 8))
16689 ("w" . ,(* 60 8 5))
16690 ("m" . ,(* 60 8 5 4))
16691 ("y" . ,(* 60 8 5 40)))
16692 "Conversion factor to minutes for an effort modifier.
16694 Each entry has the form (MODIFIER . MINUTES).
16696 In an effort string, a number followed by MODIFIER is multiplied
16697 by the specified number of MINUTES to obtain an effort in
16698 minutes.
16700 For example, if the value of this variable is ((\"hours\" . 60)), then an
16701 effort string \"2hours\" is equivalent to 120 minutes."
16702 :group 'org-agenda
16703 :version "24.1"
16704 :type '(alist :key-type (string :tag "Modifier")
16705 :value-type (number :tag "Minutes")))
16707 (defun org-duration-string-to-minutes (s &optional output-to-string)
16708 "Convert a duration string S to minutes.
16710 A bare number is interpreted as minutes, modifiers can be set by
16711 customizing `org-effort-durations' (which see).
16713 Entries containing a colon are interpreted as H:MM by
16714 `org-hh:mm-string-to-minutes'."
16715 (let ((result 0)
16716 (re (concat "\\([0-9.]+\\) *\\("
16717 (regexp-opt (mapcar 'car org-effort-durations))
16718 "\\)")))
16719 (while (string-match re s)
16720 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16721 (string-to-number (match-string 1 s))))
16722 (setq s (replace-match "" nil t s)))
16723 (setq result (floor result))
16724 (incf result (org-hh:mm-string-to-minutes s))
16725 (if output-to-string (number-to-string result) result)))
16727 ;;;; Files
16729 (defun org-save-all-org-buffers ()
16730 "Save all Org-mode buffers without user confirmation."
16731 (interactive)
16732 (message "Saving all Org-mode buffers...")
16733 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16734 (when (featurep 'org-id) (org-id-locations-save))
16735 (message "Saving all Org-mode buffers... done"))
16737 (defun org-revert-all-org-buffers ()
16738 "Revert all Org-mode buffers.
16739 Prompt for confirmation when there are unsaved changes.
16740 Be sure you know what you are doing before letting this function
16741 overwrite your changes.
16743 This function is useful in a setup where one tracks org files
16744 with a version control system, to revert on one machine after pulling
16745 changes from another. I believe the procedure must be like this:
16747 1. M-x org-save-all-org-buffers
16748 2. Pull changes from the other machine, resolve conflicts
16749 3. M-x org-revert-all-org-buffers"
16750 (interactive)
16751 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16752 (error "Abort"))
16753 (save-excursion
16754 (save-window-excursion
16755 (mapc
16756 (lambda (b)
16757 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16758 (with-current-buffer b buffer-file-name))
16759 (org-pop-to-buffer-same-window b)
16760 (revert-buffer t 'no-confirm)))
16761 (buffer-list))
16762 (when (and (featurep 'org-id) org-id-track-globally)
16763 (org-id-locations-load)))))
16765 ;;;; Agenda files
16767 ;;;###autoload
16768 (defun org-switchb (&optional arg)
16769 "Switch between Org buffers.
16770 With one prefix argument, restrict available buffers to files.
16771 With two prefix arguments, restrict available buffers to agenda files.
16773 Defaults to `iswitchb' for buffer name completion.
16774 Set `org-completion-use-ido' to make it use ido instead."
16775 (interactive "P")
16776 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16777 ((equal arg '(16)) (org-buffer-list 'agenda))
16778 (t (org-buffer-list))))
16779 (org-completion-use-iswitchb org-completion-use-iswitchb)
16780 (org-completion-use-ido org-completion-use-ido))
16781 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16782 (setq org-completion-use-iswitchb t))
16783 (org-pop-to-buffer-same-window
16784 (org-icompleting-read "Org buffer: "
16785 (mapcar 'list (mapcar 'buffer-name blist))
16786 nil t))))
16788 ;;; Define some older names previously used for this functionality
16789 ;;;###autoload
16790 (defalias 'org-ido-switchb 'org-switchb)
16791 ;;;###autoload
16792 (defalias 'org-iswitchb 'org-switchb)
16794 (defun org-buffer-list (&optional predicate exclude-tmp)
16795 "Return a list of Org buffers.
16796 PREDICATE can be `export', `files' or `agenda'.
16798 export restrict the list to Export buffers.
16799 files restrict the list to buffers visiting Org files.
16800 agenda restrict the list to buffers visiting agenda files.
16802 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
16803 (let* ((bfn nil)
16804 (agenda-files (and (eq predicate 'agenda)
16805 (mapcar 'file-truename (org-agenda-files t))))
16806 (filter
16807 (cond
16808 ((eq predicate 'files)
16809 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
16810 ((eq predicate 'export)
16811 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
16812 ((eq predicate 'agenda)
16813 (lambda (b)
16814 (with-current-buffer b
16815 (and (derived-mode-p 'org-mode)
16816 (setq bfn (buffer-file-name b))
16817 (member (file-truename bfn) agenda-files)))))
16818 (t (lambda (b) (with-current-buffer b
16819 (or (derived-mode-p 'org-mode)
16820 (string-match "\*Org .*Export"
16821 (buffer-name b)))))))))
16822 (delq nil
16823 (mapcar
16824 (lambda(b)
16825 (if (and (funcall filter b)
16826 (or (not exclude-tmp)
16827 (not (string-match "tmp" (buffer-name b)))))
16829 nil))
16830 (buffer-list)))))
16832 (defun org-agenda-files (&optional unrestricted archives)
16833 "Get the list of agenda files.
16834 Optional UNRESTRICTED means return the full list even if a restriction
16835 is currently in place.
16836 When ARCHIVES is t, include all archive files that are really being
16837 used by the agenda files. If ARCHIVE is `ifmode', do this only if
16838 `org-agenda-archives-mode' is t."
16839 (let ((files
16840 (cond
16841 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16842 ((stringp org-agenda-files) (org-read-agenda-file-list))
16843 ((listp org-agenda-files) org-agenda-files)
16844 (t (error "Invalid value of `org-agenda-files'")))))
16845 (setq files (apply 'append
16846 (mapcar (lambda (f)
16847 (if (file-directory-p f)
16848 (directory-files
16849 f t org-agenda-file-regexp)
16850 (list f)))
16851 files)))
16852 (when org-agenda-skip-unavailable-files
16853 (setq files (delq nil
16854 (mapcar (function
16855 (lambda (file)
16856 (and (file-readable-p file) file)))
16857 files))))
16858 (when (or (eq archives t)
16859 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
16860 (setq files (org-add-archive-files files)))
16861 files))
16863 (defun org-agenda-file-p (&optional file)
16864 "Return non-nil, if FILE is an agenda file.
16865 If FILE is omitted, use the file associated with the current
16866 buffer."
16867 (member (or file (buffer-file-name))
16868 (org-agenda-files t)))
16870 (defun org-edit-agenda-file-list ()
16871 "Edit the list of agenda files.
16872 Depending on setup, this either uses customize to edit the variable
16873 `org-agenda-files', or it visits the file that is holding the list. In the
16874 latter case, the buffer is set up in a way that saving it automatically kills
16875 the buffer and restores the previous window configuration."
16876 (interactive)
16877 (if (stringp org-agenda-files)
16878 (let ((cw (current-window-configuration)))
16879 (find-file org-agenda-files)
16880 (org-set-local 'org-window-configuration cw)
16881 (org-add-hook 'after-save-hook
16882 (lambda ()
16883 (set-window-configuration
16884 (prog1 org-window-configuration
16885 (kill-buffer (current-buffer))))
16886 (org-install-agenda-files-menu)
16887 (message "New agenda file list installed"))
16888 nil 'local)
16889 (message "%s" (substitute-command-keys
16890 "Edit list and finish with \\[save-buffer]")))
16891 (customize-variable 'org-agenda-files)))
16893 (defun org-store-new-agenda-file-list (list)
16894 "Set new value for the agenda file list and save it correctly."
16895 (if (stringp org-agenda-files)
16896 (let ((fe (org-read-agenda-file-list t)) b u)
16897 (while (setq b (find-buffer-visiting org-agenda-files))
16898 (kill-buffer b))
16899 (with-temp-file org-agenda-files
16900 (insert
16901 (mapconcat
16902 (lambda (f) ;; Keep un-expanded entries.
16903 (if (setq u (assoc f fe))
16904 (cdr u)
16906 list "\n")
16907 "\n")))
16908 (let ((org-mode-hook nil) (org-inhibit-startup t)
16909 (org-insert-mode-line-in-empty-file nil))
16910 (setq org-agenda-files list)
16911 (customize-save-variable 'org-agenda-files org-agenda-files))))
16913 (defun org-read-agenda-file-list (&optional pair-with-expansion)
16914 "Read the list of agenda files from a file.
16915 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
16916 filenames, used by `org-store-new-agenda-file-list' to write back
16917 un-expanded file names."
16918 (when (file-directory-p org-agenda-files)
16919 (error "`org-agenda-files' cannot be a single directory"))
16920 (when (stringp org-agenda-files)
16921 (with-temp-buffer
16922 (insert-file-contents org-agenda-files)
16923 (mapcar
16924 (lambda (f)
16925 (let ((e (expand-file-name (substitute-in-file-name f)
16926 org-directory)))
16927 (if pair-with-expansion
16928 (cons e f)
16929 e)))
16930 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
16932 ;;;###autoload
16933 (defun org-cycle-agenda-files ()
16934 "Cycle through the files in `org-agenda-files'.
16935 If the current buffer visits an agenda file, find the next one in the list.
16936 If the current buffer does not, find the first agenda file."
16937 (interactive)
16938 (let* ((fs (org-agenda-files t))
16939 (files (append fs (list (car fs))))
16940 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16941 file)
16942 (unless files (error "No agenda files"))
16943 (catch 'exit
16944 (while (setq file (pop files))
16945 (if (equal (file-truename file) tcf)
16946 (when (car files)
16947 (find-file (car files))
16948 (throw 'exit t))))
16949 (find-file (car fs)))
16950 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
16952 (defun org-agenda-file-to-front (&optional to-end)
16953 "Move/add the current file to the top of the agenda file list.
16954 If the file is not present in the list, it is added to the front. If it is
16955 present, it is moved there. With optional argument TO-END, add/move to the
16956 end of the list."
16957 (interactive "P")
16958 (let ((org-agenda-skip-unavailable-files nil)
16959 (file-alist (mapcar (lambda (x)
16960 (cons (file-truename x) x))
16961 (org-agenda-files t)))
16962 (ctf (file-truename buffer-file-name))
16963 x had)
16964 (setq x (assoc ctf file-alist) had x)
16966 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16967 (if to-end
16968 (setq file-alist (append (delq x file-alist) (list x)))
16969 (setq file-alist (cons x (delq x file-alist))))
16970 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16971 (org-install-agenda-files-menu)
16972 (message "File %s to %s of agenda file list"
16973 (if had "moved" "added") (if to-end "end" "front"))))
16975 (defun org-remove-file (&optional file)
16976 "Remove current file from the list of files in variable `org-agenda-files'.
16977 These are the files which are being checked for agenda entries.
16978 Optional argument FILE means use this file instead of the current."
16979 (interactive)
16980 (let* ((org-agenda-skip-unavailable-files nil)
16981 (file (or file buffer-file-name))
16982 (true-file (file-truename file))
16983 (afile (abbreviate-file-name file))
16984 (files (delq nil (mapcar
16985 (lambda (x)
16986 (if (equal true-file
16987 (file-truename x))
16988 nil x))
16989 (org-agenda-files t)))))
16990 (if (not (= (length files) (length (org-agenda-files t))))
16991 (progn
16992 (org-store-new-agenda-file-list files)
16993 (org-install-agenda-files-menu)
16994 (message "Removed file: %s" afile))
16995 (message "File was not in list: %s (not removed)" afile))))
16997 (defun org-file-menu-entry (file)
16998 (vector file (list 'find-file file) t))
17000 (defun org-check-agenda-file (file)
17001 "Make sure FILE exists. If not, ask user what to do."
17002 (when (not (file-exists-p file))
17003 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
17004 (abbreviate-file-name file))
17005 (let ((r (downcase (read-char-exclusive))))
17006 (cond
17007 ((equal r ?r)
17008 (org-remove-file file)
17009 (throw 'nextfile t))
17010 (t (error "Abort"))))))
17012 (defun org-get-agenda-file-buffer (file)
17013 "Get a buffer visiting FILE. If the buffer needs to be created, add
17014 it to the list of buffers which might be released later."
17015 (let ((buf (org-find-base-buffer-visiting file)))
17016 (if buf
17017 buf ; just return it
17018 ;; Make a new buffer and remember it
17019 (setq buf (find-file-noselect file))
17020 (if buf (push buf org-agenda-new-buffers))
17021 buf)))
17023 (defun org-release-buffers (blist)
17024 "Release all buffers in list, asking the user for confirmation when needed.
17025 When a buffer is unmodified, it is just killed. When modified, it is saved
17026 \(if the user agrees) and then killed."
17027 (let (buf file)
17028 (while (setq buf (pop blist))
17029 (setq file (buffer-file-name buf))
17030 (when (and (buffer-modified-p buf)
17031 file
17032 (y-or-n-p (format "Save file %s? " file)))
17033 (with-current-buffer buf (save-buffer)))
17034 (kill-buffer buf))))
17036 (defun org-agenda-prepare-buffers (files)
17037 "Create buffers for all agenda files, protect archived trees and comments."
17038 (interactive)
17039 (let ((pa '(:org-archived t))
17040 (pc '(:org-comment t))
17041 (pall '(:org-archived t :org-comment t))
17042 (inhibit-read-only t)
17043 (rea (concat ":" org-archive-tag ":"))
17044 bmp file re)
17045 (save-excursion
17046 (save-restriction
17047 (while (setq file (pop files))
17048 (catch 'nextfile
17049 (if (bufferp file)
17050 (set-buffer file)
17051 (org-check-agenda-file file)
17052 (set-buffer (org-get-agenda-file-buffer file)))
17053 (widen)
17054 (setq bmp (buffer-modified-p))
17055 (org-refresh-category-properties)
17056 (setq org-todo-keywords-for-agenda
17057 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17058 (setq org-done-keywords-for-agenda
17059 (append org-done-keywords-for-agenda org-done-keywords))
17060 (setq org-todo-keyword-alist-for-agenda
17061 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17062 (setq org-drawers-for-agenda
17063 (append org-drawers-for-agenda org-drawers))
17064 (setq org-tag-alist-for-agenda
17065 (append org-tag-alist-for-agenda org-tag-alist))
17067 (save-excursion
17068 (remove-text-properties (point-min) (point-max) pall)
17069 (when org-agenda-skip-archived-trees
17070 (goto-char (point-min))
17071 (while (re-search-forward rea nil t)
17072 (if (org-at-heading-p t)
17073 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17074 (goto-char (point-min))
17075 (setq re (format org-heading-keyword-regexp-format
17076 org-comment-string))
17077 (while (re-search-forward re nil t)
17078 (add-text-properties
17079 (match-beginning 0) (org-end-of-subtree t) pc)))
17080 (set-buffer-modified-p bmp)))))
17081 (setq org-todo-keywords-for-agenda
17082 (org-uniquify org-todo-keywords-for-agenda))
17083 (setq org-todo-keyword-alist-for-agenda
17084 (org-uniquify org-todo-keyword-alist-for-agenda)
17085 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17087 ;;;; Embedded LaTeX
17089 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17090 "Keymap for the minor `org-cdlatex-mode'.")
17092 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17093 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17094 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17095 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17096 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17098 (defvar org-cdlatex-texmathp-advice-is-done nil
17099 "Flag remembering if we have applied the advice to texmathp already.")
17101 (define-minor-mode org-cdlatex-mode
17102 "Toggle the minor `org-cdlatex-mode'.
17103 This mode supports entering LaTeX environment and math in LaTeX fragments
17104 in Org-mode.
17105 \\{org-cdlatex-mode-map}"
17106 nil " OCDL" nil
17107 (when org-cdlatex-mode
17108 (require 'cdlatex)
17109 (run-hooks 'cdlatex-mode-hook)
17110 (cdlatex-compute-tables))
17111 (unless org-cdlatex-texmathp-advice-is-done
17112 (setq org-cdlatex-texmathp-advice-is-done t)
17113 (defadvice texmathp (around org-math-always-on activate)
17114 "Always return t in org-mode buffers.
17115 This is because we want to insert math symbols without dollars even outside
17116 the LaTeX math segments. If Orgmode thinks that point is actually inside
17117 an embedded LaTeX fragment, let texmathp do its job.
17118 \\[org-cdlatex-mode-map]"
17119 (interactive)
17120 (let (p)
17121 (cond
17122 ((not (derived-mode-p 'org-mode)) ad-do-it)
17123 ((eq this-command 'cdlatex-math-symbol)
17124 (setq ad-return-value t
17125 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17127 (let ((p (org-inside-LaTeX-fragment-p)))
17128 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17129 (setq ad-return-value t
17130 texmathp-why '("Org-mode embedded math" . 0))
17131 (if p ad-do-it)))))))))
17133 (defun turn-on-org-cdlatex ()
17134 "Unconditionally turn on `org-cdlatex-mode'."
17135 (org-cdlatex-mode 1))
17137 (defun org-inside-LaTeX-fragment-p ()
17138 "Test if point is inside a LaTeX fragment.
17139 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17140 sequence appearing also before point.
17141 Even though the matchers for math are configurable, this function assumes
17142 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17143 delimiters are skipped when they have been removed by customization.
17144 The return value is nil, or a cons cell with the delimiter and the
17145 position of this delimiter.
17147 This function does a reasonably good job, but can locally be fooled by
17148 for example currency specifications. For example it will assume being in
17149 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17150 fragments that are properly closed, but during editing, we have to live
17151 with the uncertainty caused by missing closing delimiters. This function
17152 looks only before point, not after."
17153 (catch 'exit
17154 (let ((pos (point))
17155 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17156 (lim (progn
17157 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17158 (point)))
17159 dd-on str (start 0) m re)
17160 (goto-char pos)
17161 (when dodollar
17162 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17163 re (nth 1 (assoc "$" org-latex-regexps)))
17164 (while (string-match re str start)
17165 (cond
17166 ((= (match-end 0) (length str))
17167 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17168 ((= (match-end 0) (- (length str) 5))
17169 (throw 'exit nil))
17170 (t (setq start (match-end 0))))))
17171 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17172 (goto-char pos)
17173 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17174 (and (match-beginning 2) (throw 'exit nil))
17175 ;; count $$
17176 (while (re-search-backward "\\$\\$" lim t)
17177 (setq dd-on (not dd-on)))
17178 (goto-char pos)
17179 (if dd-on (cons "$$" m))))))
17181 (defun org-inside-latex-macro-p ()
17182 "Is point inside a LaTeX macro or its arguments?"
17183 (save-match-data
17184 (org-in-regexp
17185 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17187 (defun org-try-cdlatex-tab ()
17188 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17189 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17190 - inside a LaTeX fragment, or
17191 - after the first word in a line, where an abbreviation expansion could
17192 insert a LaTeX environment."
17193 (when org-cdlatex-mode
17194 (cond
17195 ;; Before any word on the line: No expansion possible.
17196 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17197 ;; Just after first word on the line: Expand it. Make sure it
17198 ;; cannot happen on headlines, though.
17199 ((save-excursion
17200 (skip-chars-backward "a-zA-Z0-9*")
17201 (skip-chars-backward " \t")
17202 (and (bolp) (not (org-at-heading-p))))
17203 (cdlatex-tab) t)
17204 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17206 (defun org-cdlatex-underscore-caret (&optional arg)
17207 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17208 Revert to the normal definition outside of these fragments."
17209 (interactive "P")
17210 (if (org-inside-LaTeX-fragment-p)
17211 (call-interactively 'cdlatex-sub-superscript)
17212 (let (org-cdlatex-mode)
17213 (call-interactively (key-binding (vector last-input-event))))))
17215 (defun org-cdlatex-math-modify (&optional arg)
17216 "Execute `cdlatex-math-modify' in LaTeX fragments.
17217 Revert to the normal definition outside of these fragments."
17218 (interactive "P")
17219 (if (org-inside-LaTeX-fragment-p)
17220 (call-interactively 'cdlatex-math-modify)
17221 (let (org-cdlatex-mode)
17222 (call-interactively (key-binding (vector last-input-event))))))
17224 (defvar org-latex-fragment-image-overlays nil
17225 "List of overlays carrying the images of latex fragments.")
17226 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17228 (defun org-remove-latex-fragment-image-overlays ()
17229 "Remove all overlays with LaTeX fragment images in current buffer."
17230 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17231 (setq org-latex-fragment-image-overlays nil))
17233 (defun org-preview-latex-fragment (&optional subtree)
17234 "Preview the LaTeX fragment at point, or all locally or globally.
17235 If the cursor is in a LaTeX fragment, create the image and overlay
17236 it over the source code. If there is no fragment at point, display
17237 all fragments in the current text, from one headline to the next. With
17238 prefix SUBTREE, display all fragments in the current subtree. With a
17239 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17240 the cursor is before the first headline,
17241 display all fragments in the buffer.
17242 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17243 (interactive "P")
17244 (unless buffer-file-name
17245 (error "Can't preview LaTeX fragment in a non-file buffer"))
17246 (org-remove-latex-fragment-image-overlays)
17247 (save-excursion
17248 (save-restriction
17249 (let (beg end at msg)
17250 (cond
17251 ((or (equal subtree '(16))
17252 (not (save-excursion
17253 (re-search-backward org-outline-regexp-bol nil t))))
17254 (setq beg (point-min) end (point-max)
17255 msg "Creating images for buffer...%s"))
17256 ((equal subtree '(4))
17257 (org-back-to-heading)
17258 (setq beg (point) end (org-end-of-subtree t)
17259 msg "Creating images for subtree...%s"))
17261 (if (setq at (org-inside-LaTeX-fragment-p))
17262 (goto-char (max (point-min) (- (cdr at) 2)))
17263 (org-back-to-heading))
17264 (setq beg (point) end (progn (outline-next-heading) (point))
17265 msg (if at "Creating image...%s"
17266 "Creating images for entry...%s"))))
17267 (message msg "")
17268 (narrow-to-region beg end)
17269 (goto-char beg)
17270 (org-format-latex
17271 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17272 (file-name-nondirectory
17273 buffer-file-name)))
17274 default-directory 'overlays msg at 'forbuffer
17275 org-latex-create-formula-image-program)
17276 (message msg "done. Use `C-c C-c' to remove images.")))))
17278 (defvar org-latex-regexps
17279 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17280 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17281 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17282 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17283 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17284 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17285 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17286 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17287 "Regular expressions for matching embedded LaTeX.")
17289 (defvar org-export-have-math nil) ;; dynamic scoping
17290 (defun org-format-latex (prefix &optional dir overlays msg at
17291 forbuffer processing-type)
17292 "Replace LaTeX fragments with links to an image, and produce images.
17293 Some of the options can be changed using the variable
17294 `org-format-latex-options'."
17295 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17296 (let* ((prefixnodir (file-name-nondirectory prefix))
17297 (absprefix (expand-file-name prefix dir))
17298 (todir (file-name-directory absprefix))
17299 (opt org-format-latex-options)
17300 (matchers (plist-get opt :matchers))
17301 (re-list org-latex-regexps)
17302 (org-format-latex-header-extra
17303 (plist-get (org-infile-export-plist) :latex-header-extra))
17304 (cnt 0) txt hash link beg end re e checkdir
17305 executables-checked string
17306 m n block-type block linkfile movefile ov)
17307 ;; Check the different regular expressions
17308 (while (setq e (pop re-list))
17309 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17310 block (if block-type "\n\n" ""))
17311 (when (member m matchers)
17312 (goto-char (point-min))
17313 (while (re-search-forward re nil t)
17314 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17315 (not (get-text-property (match-beginning n)
17316 'org-protected))
17317 (or (not overlays)
17318 (not (eq (get-char-property (match-beginning n)
17319 'org-overlay-type)
17320 'org-latex-overlay))))
17321 (setq org-export-have-math t)
17322 (cond
17323 ((eq processing-type 'verbatim)
17324 ;; Leave the text verbatim, just protect it
17325 (add-text-properties (match-beginning n) (match-end n)
17326 '(org-protected t)))
17327 ((eq processing-type 'mathjax)
17328 ;; Prepare for MathJax processing
17329 (setq string (match-string n))
17330 (if (member m '("$" "$1"))
17331 (save-excursion
17332 (delete-region (match-beginning n) (match-end n))
17333 (goto-char (match-beginning n))
17334 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17335 "\\)")
17336 '(org-protected t))))
17337 (add-text-properties (match-beginning n) (match-end n)
17338 '(org-protected t))))
17339 ((or (eq processing-type 'dvipng)
17340 (eq processing-type 'imagemagick))
17341 ;; Process to an image
17342 (setq txt (match-string n)
17343 beg (match-beginning n) end (match-end n)
17344 cnt (1+ cnt))
17345 (let (print-length print-level) ; make sure full list is printed
17346 (setq hash (sha1 (prin1-to-string
17347 (list org-format-latex-header
17348 org-format-latex-header-extra
17349 org-export-latex-default-packages-alist
17350 org-export-latex-packages-alist
17351 org-format-latex-options
17352 forbuffer txt)))
17353 linkfile (format "%s_%s.png" prefix hash)
17354 movefile (format "%s_%s.png" absprefix hash)))
17355 (setq link (concat block "[[file:" linkfile "]]" block))
17356 (if msg (message msg cnt))
17357 (goto-char beg)
17358 (unless checkdir ; make sure the directory exists
17359 (setq checkdir t)
17360 (or (file-directory-p todir) (make-directory todir t)))
17361 (cond
17362 ((eq processing-type 'dvipng)
17363 (unless executables-checked
17364 (org-check-external-command
17365 "latex" "needed to convert LaTeX fragments to images")
17366 (org-check-external-command
17367 "dvipng" "needed to convert LaTeX fragments to images")
17368 (setq executables-checked t))
17369 (unless (file-exists-p movefile)
17370 (org-create-formula-image-with-dvipng
17371 txt movefile opt forbuffer)))
17372 ((eq processing-type 'imagemagick)
17373 (unless executables-checked
17374 (org-check-external-command
17375 "convert" "you need to install imagemagick")
17376 (setq executables-checked t))
17377 (unless (file-exists-p movefile)
17378 (org-create-formula-image-with-imagemagick
17379 txt movefile opt forbuffer))))
17380 (if overlays
17381 (progn
17382 (mapc (lambda (o)
17383 (if (eq (overlay-get o 'org-overlay-type)
17384 'org-latex-overlay)
17385 (delete-overlay o)))
17386 (overlays-in beg end))
17387 (setq ov (make-overlay beg end))
17388 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17389 (if (featurep 'xemacs)
17390 (progn
17391 (overlay-put ov 'invisible t)
17392 (overlay-put
17393 ov 'end-glyph
17394 (make-glyph (vector 'png :file movefile))))
17395 (overlay-put
17396 ov 'display
17397 (list 'image :type 'png :file movefile :ascent 'center)))
17398 (push ov org-latex-fragment-image-overlays)
17399 (goto-char end))
17400 (delete-region beg end)
17401 (insert (org-add-props link
17402 (list 'org-latex-src
17403 (replace-regexp-in-string
17404 "\"" "" txt)
17405 'org-latex-src-embed-type
17406 (if block-type 'paragraph 'character))))))
17407 ((eq processing-type 'mathml)
17408 ;; Process to MathML
17409 (unless executables-checked
17410 (unless (save-match-data (org-format-latex-mathml-available-p))
17411 (error "LaTeX to MathML converter not configured"))
17412 (setq executables-checked t))
17413 (setq txt (match-string n)
17414 beg (match-beginning n) end (match-end n)
17415 cnt (1+ cnt))
17416 (if msg (message msg cnt))
17417 (goto-char beg)
17418 (delete-region beg end)
17419 (insert (org-format-latex-as-mathml
17420 txt block-type prefix dir)))
17422 (error "Unknown conversion type %s for latex fragments"
17423 processing-type)))))))))
17425 (defun org-create-math-formula (latex-frag &optional mathml-file)
17426 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17427 Use `org-latex-to-mathml-convert-command'. If the conversion is
17428 sucessful, return the portion between \"<math...> </math>\"
17429 elements otherwise return nil. When MATHML-FILE is specified,
17430 write the results in to that file. When invoked as an
17431 interactive command, prompt for LATEX-FRAG, with initial value
17432 set to the current active region and echo the results for user
17433 inspection."
17434 (interactive (list (let ((frag (when (org-region-active-p)
17435 (buffer-substring-no-properties
17436 (region-beginning) (region-end)))))
17437 (read-string "LaTeX Fragment: " frag nil frag))))
17438 (unless latex-frag (error "Invalid latex-frag"))
17439 (let* ((tmp-in-file (file-relative-name
17440 (make-temp-name (expand-file-name "ltxmathml-in"))))
17441 (ignore (write-region latex-frag nil tmp-in-file))
17442 (tmp-out-file (file-relative-name
17443 (make-temp-name (expand-file-name "ltxmathml-out"))))
17444 (cmd (format-spec
17445 org-latex-to-mathml-convert-command
17446 `((?j . ,(shell-quote-argument
17447 (expand-file-name org-latex-to-mathml-jar-file)))
17448 (?I . ,(shell-quote-argument tmp-in-file))
17449 (?o . ,(shell-quote-argument tmp-out-file)))))
17450 mathml shell-command-output)
17451 (when (org-called-interactively-p 'any)
17452 (unless (org-format-latex-mathml-available-p)
17453 (error "LaTeX to MathML converter not configured")))
17454 (message "Running %s" cmd)
17455 (setq shell-command-output (shell-command-to-string cmd))
17456 (setq mathml
17457 (when (file-readable-p tmp-out-file)
17458 (with-current-buffer (find-file-noselect tmp-out-file t)
17459 (goto-char (point-min))
17460 (when (re-search-forward
17461 (concat
17462 (regexp-quote
17463 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17464 "\\(.\\|\n\\)*"
17465 (regexp-quote "</math>")) nil t)
17466 (prog1 (match-string 0) (kill-buffer))))))
17467 (cond
17468 (mathml
17469 (setq mathml
17470 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17471 (when mathml-file
17472 (write-region mathml nil mathml-file))
17473 (when (org-called-interactively-p 'any)
17474 (message mathml)))
17475 ((message "LaTeX to MathML conversion failed")
17476 (message shell-command-output)))
17477 (delete-file tmp-in-file)
17478 (when (file-exists-p tmp-out-file)
17479 (delete-file tmp-out-file))
17480 mathml))
17482 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17483 prefix &optional dir)
17484 "Use `org-create-math-formula' but check local cache first."
17485 (let* ((absprefix (expand-file-name prefix dir))
17486 (print-length nil) (print-level nil)
17487 (formula-id (concat
17488 "formula-"
17489 (sha1
17490 (prin1-to-string
17491 (list latex-frag
17492 org-latex-to-mathml-convert-command)))))
17493 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17494 (formula-cache-dir (file-name-directory formula-cache)))
17496 (unless (file-directory-p formula-cache-dir)
17497 (make-directory formula-cache-dir t))
17499 (unless (file-exists-p formula-cache)
17500 (org-create-math-formula latex-frag formula-cache))
17502 (if (file-exists-p formula-cache)
17503 ;; Successful conversion. Return the link to MathML file.
17504 (org-add-props
17505 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17506 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17507 'org-latex-src-embed-type (if latex-frag-type
17508 'paragraph 'character)))
17509 ;; Failed conversion. Return the LaTeX fragment verbatim
17510 (add-text-properties
17511 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17512 latex-frag)))
17514 ;; This function borrows from Ganesh Swami's latex2png.el
17515 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17516 "This calls dvipng."
17517 (require 'org-latex)
17518 (let* ((tmpdir (if (featurep 'xemacs)
17519 (temp-directory)
17520 temporary-file-directory))
17521 (texfilebase (make-temp-name
17522 (expand-file-name "orgtex" tmpdir)))
17523 (texfile (concat texfilebase ".tex"))
17524 (dvifile (concat texfilebase ".dvi"))
17525 (pngfile (concat texfilebase ".png"))
17526 (fnh (if (featurep 'xemacs)
17527 (font-height (face-font 'default))
17528 (face-attribute 'default :height nil)))
17529 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17530 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17531 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17532 "Black"))
17533 (bg (or (plist-get options (if buffer :background :html-background))
17534 "Transparent")))
17535 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
17536 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
17537 (with-temp-file texfile
17538 (insert (org-splice-latex-header
17539 org-format-latex-header
17540 org-export-latex-default-packages-alist
17541 org-export-latex-packages-alist t
17542 org-format-latex-header-extra))
17543 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17544 (require 'org-latex)
17545 (org-export-latex-fix-inputenc))
17546 (let ((dir default-directory))
17547 (condition-case nil
17548 (progn
17549 (cd tmpdir)
17550 (call-process "latex" nil nil nil texfile))
17551 (error nil))
17552 (cd dir))
17553 (if (not (file-exists-p dvifile))
17554 (progn (message "Failed to create dvi file from %s" texfile) nil)
17555 (condition-case nil
17556 (if (featurep 'xemacs)
17557 (call-process "dvipng" nil nil nil
17558 "-fg" fg "-bg" bg
17559 "-T" "tight"
17560 "-o" pngfile
17561 dvifile)
17562 (call-process "dvipng" nil nil nil
17563 "-fg" fg "-bg" bg
17564 "-D" dpi
17565 ;;"-x" scale "-y" scale
17566 "-T" "tight"
17567 "-o" pngfile
17568 dvifile))
17569 (error nil))
17570 (if (not (file-exists-p pngfile))
17571 (if org-format-latex-signal-error
17572 (error "Failed to create png file from %s" texfile)
17573 (message "Failed to create png file from %s" texfile)
17574 nil)
17575 ;; Use the requested file name and clean up
17576 (copy-file pngfile tofile 'replace)
17577 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17578 (if (file-exists-p (concat texfilebase e))
17579 (delete-file (concat texfilebase e))))
17580 pngfile))))
17582 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17583 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17584 "This calls convert, which is included into imagemagick."
17585 (require 'org-latex)
17586 (let* ((tmpdir (if (featurep 'xemacs)
17587 (temp-directory)
17588 temporary-file-directory))
17589 (texfilebase (make-temp-name
17590 (expand-file-name "orgtex" tmpdir)))
17591 (texfile (concat texfilebase ".tex"))
17592 (pdffile (concat texfilebase ".pdf"))
17593 (pngfile (concat texfilebase ".png"))
17594 (fnh (if (featurep 'xemacs)
17595 (font-height (face-font 'default))
17596 (face-attribute 'default :height nil)))
17597 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17598 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17599 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17600 "black"))
17601 (bg (or (plist-get options (if buffer :background :html-background))
17602 "white")))
17603 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17604 (setq fg (org-latex-color-format fg)))
17605 (if (eq bg 'default) (setq bg (org-latex-color :background))
17606 (setq bg (org-latex-color-format
17607 (if (string= bg "Transparent")(setq bg "white")))))
17608 (with-temp-file texfile
17609 (insert (org-splice-latex-header
17610 org-format-latex-header
17611 org-export-latex-default-packages-alist
17612 org-export-latex-packages-alist t
17613 org-format-latex-header-extra))
17614 (insert "\n\\begin{document}\n"
17615 "\\definecolor{fg}{rgb}{" fg "}\n"
17616 "\\definecolor{bg}{rgb}{" bg "}\n"
17617 "\n\\pagecolor{bg}\n"
17618 "\n{\\color{fg}\n"
17619 string
17620 "\n}\n"
17621 "\n\\end{document}\n" )
17622 (require 'org-latex)
17623 (org-export-latex-fix-inputenc))
17624 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17625 (condition-case nil
17626 (progn
17627 (cd tmpdir)
17628 (setq cmds org-latex-to-pdf-process)
17629 (while cmds
17630 (setq latex-frags-cmds (pop cmds))
17631 (if (listp latex-frags-cmds)
17632 (setq cmds nil)
17633 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17634 (while latex-frags-cmds
17635 (setq cmd (pop latex-frags-cmds))
17636 (while (string-match "%b" cmd)
17637 (setq cmd (replace-match
17638 (save-match-data
17639 (shell-quote-argument texfile))
17640 t t cmd)))
17641 (while (string-match "%f" cmd)
17642 (setq cmd (replace-match
17643 (save-match-data
17644 (shell-quote-argument (file-name-nondirectory texfile)))
17645 t t cmd)))
17646 (while (string-match "%o" cmd)
17647 (setq cmd (replace-match
17648 (save-match-data
17649 (shell-quote-argument (file-name-directory texfile)))
17650 t t cmd)))
17651 (setq cmd (split-string cmd))
17652 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17653 (error nil))
17654 (cd dir))
17655 (if (not (file-exists-p pdffile))
17656 (progn (message "Failed to create pdf file from %s" texfile) nil)
17657 (condition-case nil
17658 (if (featurep 'xemacs)
17659 (call-process "convert" nil nil nil
17660 "-density" "96"
17661 "-trim"
17662 "-antialias"
17663 pdffile
17664 "-quality" "100"
17665 ;; "-sharpen" "0x1.0"
17666 pngfile)
17667 (call-process "convert" nil nil nil
17668 "-density" dpi
17669 "-trim"
17670 "-antialias"
17671 pdffile
17672 "-quality" "100"
17673 ; "-sharpen" "0x1.0"
17674 pngfile))
17675 (error nil))
17676 (if (not (file-exists-p pngfile))
17677 (if org-format-latex-signal-error
17678 (error "Failed to create png file from %s" texfile)
17679 (message "Failed to create png file from %s" texfile)
17680 nil)
17681 ;; Use the requested file name and clean up
17682 (copy-file pngfile tofile 'replace)
17683 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17684 (if (file-exists-p (concat texfilebase e))
17685 (delete-file (concat texfilebase e))))
17686 pngfile))))
17688 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17689 "Fill a LaTeX header template TPL.
17690 In the template, the following place holders will be recognized:
17692 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17693 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17694 [PACKAGES] \\usepackage statements for PKG
17695 [NO-PACKAGES] do not include PKG
17696 [EXTRA] the string EXTRA
17697 [NO-EXTRA] do not include EXTRA
17699 For backward compatibility, if both the positive and the negative place
17700 holder is missing, the positive one (without the \"NO-\") will be
17701 assumed to be present at the end of the template.
17702 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17703 EXTRA is a string.
17704 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17705 (let (rpl (end ""))
17706 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17707 (setq rpl (if (or (match-end 1) (not def-pkg))
17708 "" (org-latex-packages-to-string def-pkg snippets-p t))
17709 tpl (replace-match rpl t t tpl))
17710 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17712 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17713 (setq rpl (if (or (match-end 1) (not pkg))
17714 "" (org-latex-packages-to-string pkg snippets-p t))
17715 tpl (replace-match rpl t t tpl))
17716 (if pkg (setq end
17717 (concat end "\n"
17718 (org-latex-packages-to-string pkg snippets-p)))))
17720 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17721 (setq rpl (if (or (match-end 1) (not extra))
17722 "" (concat extra "\n"))
17723 tpl (replace-match rpl t t tpl))
17724 (if (and extra (string-match "\\S-" extra))
17725 (setq end (concat end "\n" extra))))
17727 (if (string-match "\\S-" end)
17728 (concat tpl "\n" end)
17729 tpl)))
17731 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17732 "Turn an alist of packages into a string with the \\usepackage macros."
17733 (setq pkg (mapconcat (lambda(p)
17734 (cond
17735 ((stringp p) p)
17736 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17737 (format "%% Package %s omitted" (cadr p)))
17738 ((equal "" (car p))
17739 (format "\\usepackage{%s}" (cadr p)))
17741 (format "\\usepackage[%s]{%s}"
17742 (car p) (cadr p)))))
17744 "\n"))
17745 (if newline (concat pkg "\n") pkg))
17747 (defun org-dvipng-color (attr)
17748 "Return a RGB color specification for dvipng."
17749 (apply 'format "rgb %s %s %s"
17750 (mapcar 'org-normalize-color
17751 (if (featurep 'xemacs)
17752 (color-rgb-components
17753 (face-property 'default
17754 (cond ((eq attr :foreground) 'foreground)
17755 ((eq attr :background) 'background))))
17756 (color-values (face-attribute 'default attr nil))))))
17758 (defun org-latex-color (attr)
17759 "Return a RGB color for the LaTeX color package."
17760 (apply 'format "%s,%s,%s"
17761 (mapcar 'org-normalize-color
17762 (if (featurep 'xemacs)
17763 (color-rgb-components
17764 (face-property 'default
17765 (cond ((eq attr :foreground) 'foreground)
17766 ((eq attr :background) 'background))))
17767 (color-values (face-attribute 'default attr nil))))))
17769 (defun org-latex-color-format (color-name)
17770 "Convert COLOR-NAME to a RGB color value."
17771 (apply 'format "%s,%s,%s"
17772 (mapcar 'org-normalize-color
17773 (color-values color-name))))
17775 (defun org-normalize-color (value)
17776 "Return string to be used as color value for an RGB component."
17777 (format "%g" (/ value 65535.0)))
17779 ;; Image display
17782 (defvar org-inline-image-overlays nil)
17783 (make-variable-buffer-local 'org-inline-image-overlays)
17785 (defun org-toggle-inline-images (&optional include-linked)
17786 "Toggle the display of inline images.
17787 INCLUDE-LINKED is passed to `org-display-inline-images'."
17788 (interactive "P")
17789 (if org-inline-image-overlays
17790 (progn
17791 (org-remove-inline-images)
17792 (message "Inline image display turned off"))
17793 (org-display-inline-images include-linked)
17794 (if org-inline-image-overlays
17795 (message "%d images displayed inline"
17796 (length org-inline-image-overlays))
17797 (message "No images to display inline"))))
17799 (defun org-redisplay-inline-images ()
17800 "Refresh the display of inline images."
17801 (interactive)
17802 (if (not org-inline-image-overlays)
17803 (org-toggle-inline-images)
17804 (org-toggle-inline-images)
17805 (org-toggle-inline-images)))
17807 (defun org-display-inline-images (&optional include-linked refresh beg end)
17808 "Display inline images.
17809 Normally only links without a description part are inlined, because this
17810 is how it will work for export. When INCLUDE-LINKED is set, also links
17811 with a description part will be inlined. This can be nice for a quick
17812 look at those images, but it does not reflect what exported files will look
17813 like.
17814 When REFRESH is set, refresh existing images between BEG and END.
17815 This will create new image displays only if necessary.
17816 BEG and END default to the buffer boundaries."
17817 (interactive "P")
17818 (unless refresh
17819 (org-remove-inline-images)
17820 (if (fboundp 'clear-image-cache) (clear-image-cache)))
17821 (save-excursion
17822 (save-restriction
17823 (widen)
17824 (setq beg (or beg (point-min)) end (or end (point-max)))
17825 (goto-char beg)
17826 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
17827 (substring (org-image-file-name-regexp) 0 -2)
17828 "\\)\\]" (if include-linked "" "\\]")))
17829 old file ov img)
17830 (while (re-search-forward re end t)
17831 (setq old (get-char-property-and-overlay (match-beginning 1)
17832 'org-image-overlay))
17833 (setq file (expand-file-name
17834 (concat (or (match-string 3) "") (match-string 4))))
17835 (when (file-exists-p file)
17836 (if (and (car-safe old) refresh)
17837 (image-refresh (overlay-get (cdr old) 'display))
17838 (setq img (save-match-data (create-image file)))
17839 (when img
17840 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
17841 (overlay-put ov 'display img)
17842 (overlay-put ov 'face 'default)
17843 (overlay-put ov 'org-image-overlay t)
17844 (overlay-put ov 'modification-hooks
17845 (list 'org-display-inline-remove-overlay))
17846 (push ov org-inline-image-overlays)))))))))
17848 (define-obsolete-function-alias
17849 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
17851 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
17852 "Remove inline-display overlay if a corresponding region is modified."
17853 (let ((inhibit-modification-hooks t))
17854 (when (and ov after)
17855 (delete ov org-inline-image-overlays)
17856 (delete-overlay ov))))
17858 (defun org-remove-inline-images ()
17859 "Remove inline display of images."
17860 (interactive)
17861 (mapc 'delete-overlay org-inline-image-overlays)
17862 (setq org-inline-image-overlays nil))
17864 ;;;; Key bindings
17866 ;; Outline functions from `outline-mode-prefix-map'
17867 ;; that can be remapped in Org:
17868 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
17869 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
17870 (define-key org-mode-map [remap outline-forward-same-level]
17871 'org-forward-heading-same-level)
17872 (define-key org-mode-map [remap outline-backward-same-level]
17873 'org-backward-heading-same-level)
17874 (define-key org-mode-map [remap show-branches]
17875 'org-kill-note-or-show-branches)
17876 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
17877 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
17878 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
17880 ;; Outline functions from `outline-mode-prefix-map' that can not
17881 ;; be remapped in Org:
17883 ;; - the column "key binding" shows whether the Outline function is still
17884 ;; available in Org mode on the same key that it has been bound to in
17885 ;; Outline mode:
17886 ;; - "overridden": key used for a different functionality in Org mode
17887 ;; - else: key still bound to the same Outline function in Org mode
17889 ;; | Outline function | key binding | Org replacement |
17890 ;; |------------------------------------+-------------+-----------------------|
17891 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
17892 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
17893 ;; | `outline-up-heading' | `C-c C-u' | still same function |
17894 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
17895 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
17896 ;; | `show-entry' | overridden | no replacement |
17897 ;; | `show-children' | `C-c C-i' | visibility cycling |
17898 ;; | `show-branches' | `C-c C-k' | still same function |
17899 ;; | `show-subtree' | overridden | visibility cycling |
17900 ;; | `show-all' | overridden | no replacement |
17901 ;; | `hide-subtree' | overridden | visibility cycling |
17902 ;; | `hide-body' | overridden | no replacement |
17903 ;; | `hide-entry' | overridden | visibility cycling |
17904 ;; | `hide-leaves' | overridden | no replacement |
17905 ;; | `hide-sublevels' | overridden | no replacement |
17906 ;; | `hide-other' | overridden | no replacement |
17908 ;; Make `C-c C-x' a prefix key
17909 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
17911 ;; TAB key with modifiers
17912 (org-defkey org-mode-map "\C-i" 'org-cycle)
17913 (org-defkey org-mode-map [(tab)] 'org-cycle)
17914 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
17915 (org-defkey org-mode-map "\M-\t" 'pcomplete)
17916 ;; The following line is necessary under Suse GNU/Linux
17917 (unless (featurep 'xemacs)
17918 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
17919 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
17920 (define-key org-mode-map [backtab] 'org-shifttab)
17922 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
17923 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
17924 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
17926 ;; Cursor keys with modifiers
17927 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
17928 (org-defkey org-mode-map [(meta right)] 'org-metaright)
17929 (org-defkey org-mode-map [(meta up)] 'org-metaup)
17930 (org-defkey org-mode-map [(meta down)] 'org-metadown)
17932 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
17933 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
17934 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
17935 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
17937 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
17938 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
17939 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
17940 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
17942 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
17943 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
17944 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
17945 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
17947 ;; Babel keys
17948 (define-key org-mode-map org-babel-key-prefix org-babel-map)
17949 (mapc (lambda (pair)
17950 (define-key org-babel-map (car pair) (cdr pair)))
17951 org-babel-key-bindings)
17953 ;;; Extra keys for tty access.
17954 ;; We only set them when really needed because otherwise the
17955 ;; menus don't show the simple keys
17957 (when (or org-use-extra-keys
17958 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
17959 (not window-system))
17960 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
17961 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
17962 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
17963 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
17964 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
17965 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
17966 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
17967 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
17968 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
17969 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
17970 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
17971 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
17972 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
17973 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
17974 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
17975 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
17976 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
17977 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
17978 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
17979 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
17980 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
17981 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
17982 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
17983 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
17984 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
17985 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
17986 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
17987 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
17989 ;; All the other keys
17991 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
17992 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
17993 (if (boundp 'narrow-map)
17994 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
17995 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
17996 (if (boundp 'narrow-map)
17997 (org-defkey narrow-map "b" 'org-narrow-to-block)
17998 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
17999 (if (boundp 'narrow-map)
18000 (org-defkey narrow-map "e" 'org-narrow-to-element)
18001 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18002 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18003 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18004 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18005 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18006 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18007 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18008 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18009 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18010 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18011 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18012 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18013 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18014 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18015 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18016 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18017 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18018 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18019 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18020 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18021 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18022 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18023 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18024 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18025 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18026 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18027 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18028 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18029 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18030 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18031 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18032 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18033 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18034 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18035 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18036 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18037 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18038 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18039 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18040 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18041 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18042 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18043 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18044 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18045 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18046 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18047 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18048 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18049 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18050 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18051 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18052 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18053 (org-defkey org-mode-map "\C-c^" 'org-sort)
18054 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18055 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18056 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18057 (org-defkey org-mode-map "\C-m" 'org-return)
18058 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18059 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18060 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18061 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18062 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18063 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18064 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18065 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18066 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18067 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18068 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18069 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18070 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18071 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18072 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18073 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18074 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18075 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18076 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18077 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18078 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18079 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18080 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18082 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
18083 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18084 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18085 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18087 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18088 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18089 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18090 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18091 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18092 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18093 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18094 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18095 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18096 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18097 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18098 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18099 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18100 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18101 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18102 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18103 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18104 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18105 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18106 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18107 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18108 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18110 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18111 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18112 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18113 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18114 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18116 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18118 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18120 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18121 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18123 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18126 (when (featurep 'xemacs)
18127 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18130 (defconst org-speed-commands-default
18132 ("Outline Navigation")
18133 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18134 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18135 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18136 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18137 ("u" . (org-speed-move-safe 'outline-up-heading))
18138 ("j" . org-goto)
18139 ("g" . (org-refile t))
18140 ("Outline Visibility")
18141 ("c" . org-cycle)
18142 ("C" . org-shifttab)
18143 (" " . org-display-outline-path)
18144 (":" . org-columns)
18145 ("Outline Structure Editing")
18146 ("U" . org-shiftmetaup)
18147 ("D" . org-shiftmetadown)
18148 ("r" . org-metaright)
18149 ("l" . org-metaleft)
18150 ("R" . org-shiftmetaright)
18151 ("L" . org-shiftmetaleft)
18152 ("i" . (progn (forward-char 1) (call-interactively
18153 'org-insert-heading-respect-content)))
18154 ("^" . org-sort)
18155 ("w" . org-refile)
18156 ("a" . org-archive-subtree-default-with-confirmation)
18157 ("." . org-mark-subtree)
18158 ("#" . org-toggle-comment)
18159 ("Clock Commands")
18160 ("I" . org-clock-in)
18161 ("O" . org-clock-out)
18162 ("Meta Data Editing")
18163 ("t" . org-todo)
18164 ("0" . (org-priority ?\ ))
18165 ("1" . (org-priority ?A))
18166 ("2" . (org-priority ?B))
18167 ("3" . (org-priority ?C))
18168 (";" . org-set-tags-command)
18169 ("e" . org-set-effort)
18170 ("E" . org-inc-effort)
18171 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18172 (org-entry-put (point) "APPT_WARNTIME" m)))
18173 ("Agenda Views etc")
18174 ("v" . org-agenda)
18175 ("/" . org-sparse-tree)
18176 ("Misc")
18177 ("o" . org-open-at-point)
18178 ("?" . org-speed-command-help)
18179 ("<" . (org-agenda-set-restriction-lock 'subtree))
18180 (">" . (org-agenda-remove-restriction-lock))
18182 "The default speed commands.")
18184 (defun org-print-speed-command (e)
18185 (if (> (length (car e)) 1)
18186 (progn
18187 (princ "\n")
18188 (princ (car e))
18189 (princ "\n")
18190 (princ (make-string (length (car e)) ?-))
18191 (princ "\n"))
18192 (princ (car e))
18193 (princ " ")
18194 (if (symbolp (cdr e))
18195 (princ (symbol-name (cdr e)))
18196 (prin1 (cdr e)))
18197 (princ "\n")))
18199 (defun org-speed-command-help ()
18200 "Show the available speed commands."
18201 (interactive)
18202 (if (not org-use-speed-commands)
18203 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18204 (with-output-to-temp-buffer "*Help*"
18205 (princ "User-defined Speed commands\n===========================\n")
18206 (mapc 'org-print-speed-command org-speed-commands-user)
18207 (princ "\n")
18208 (princ "Built-in Speed commands\n=======================\n")
18209 (mapc 'org-print-speed-command org-speed-commands-default))
18210 (with-current-buffer "*Help*"
18211 (setq truncate-lines t))))
18213 (defun org-speed-move-safe (cmd)
18214 "Execute CMD, but make sure that the cursor always ends up in a headline.
18215 If not, return to the original position and throw an error."
18216 (interactive)
18217 (let ((pos (point)))
18218 (call-interactively cmd)
18219 (unless (and (bolp) (org-at-heading-p))
18220 (goto-char pos)
18221 (error "Boundary reached while executing %s" cmd))))
18223 (defvar org-self-insert-command-undo-counter 0)
18225 (defvar org-table-auto-blank-field) ; defined in org-table.el
18226 (defvar org-speed-command nil)
18228 (define-obsolete-function-alias
18229 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18231 (defun org-speed-command-activate (keys)
18232 "Hook for activating single-letter speed commands.
18233 `org-speed-commands-default' specifies a minimal command set.
18234 Use `org-speed-commands-user' for further customization."
18235 (when (or (and (bolp) (looking-at org-outline-regexp))
18236 (and (functionp org-use-speed-commands)
18237 (funcall org-use-speed-commands)))
18238 (cdr (assoc keys (append org-speed-commands-user
18239 org-speed-commands-default)))))
18241 (define-obsolete-function-alias
18242 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18244 (defun org-babel-speed-command-activate (keys)
18245 "Hook for activating single-letter code block commands."
18246 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18247 (cdr (assoc keys org-babel-key-bindings))))
18249 (defcustom org-speed-command-hook
18250 '(org-speed-command-default-hook org-babel-speed-command-hook)
18251 "Hook for activating speed commands at strategic locations.
18252 Hook functions are called in sequence until a valid handler is
18253 found.
18255 Each hook takes a single argument, a user-pressed command key
18256 which is also a `self-insert-command' from the global map.
18258 Within the hook, examine the cursor position and the command key
18259 and return nil or a valid handler as appropriate. Handler could
18260 be one of an interactive command, a function, or a form.
18262 Set `org-use-speed-commands' to non-nil value to enable this
18263 hook. The default setting is `org-speed-command-activate'."
18264 :group 'org-structure
18265 :version "24.1"
18266 :type 'hook)
18268 (defun org-self-insert-command (N)
18269 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18270 If the cursor is in a table looking at whitespace, the whitespace is
18271 overwritten, and the table is not marked as requiring realignment."
18272 (interactive "p")
18273 (org-check-before-invisible-edit 'insert)
18274 (cond
18275 ((and org-use-speed-commands
18276 (setq org-speed-command
18277 (run-hook-with-args-until-success
18278 'org-speed-command-hook (this-command-keys))))
18279 (cond
18280 ((commandp org-speed-command)
18281 (setq this-command org-speed-command)
18282 (call-interactively org-speed-command))
18283 ((functionp org-speed-command)
18284 (funcall org-speed-command))
18285 ((and org-speed-command (listp org-speed-command))
18286 (eval org-speed-command))
18287 (t (let (org-use-speed-commands)
18288 (call-interactively 'org-self-insert-command)))))
18289 ((and
18290 (org-table-p)
18291 (progn
18292 ;; check if we blank the field, and if that triggers align
18293 (and (featurep 'org-table) org-table-auto-blank-field
18294 (member last-command
18295 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18296 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18297 ;; got extra space, this field does not determine column width
18298 (let (org-table-may-need-update) (org-table-blank-field))
18299 ;; no extra space, this field may determine column width
18300 (org-table-blank-field)))
18302 (eq N 1)
18303 (looking-at "[^|\n]* |"))
18304 (let (org-table-may-need-update)
18305 (goto-char (1- (match-end 0)))
18306 (backward-delete-char 1)
18307 (goto-char (match-beginning 0))
18308 (self-insert-command N)))
18310 (setq org-table-may-need-update t)
18311 (self-insert-command N)
18312 (org-fix-tags-on-the-fly)
18313 (if org-self-insert-cluster-for-undo
18314 (if (not (eq last-command 'org-self-insert-command))
18315 (setq org-self-insert-command-undo-counter 1)
18316 (if (>= org-self-insert-command-undo-counter 20)
18317 (setq org-self-insert-command-undo-counter 1)
18318 (and (> org-self-insert-command-undo-counter 0)
18319 buffer-undo-list (listp buffer-undo-list)
18320 (not (cadr buffer-undo-list)) ; remove nil entry
18321 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18322 (setq org-self-insert-command-undo-counter
18323 (1+ org-self-insert-command-undo-counter))))))))
18325 (defun org-check-before-invisible-edit (kind)
18326 "Check is editing if kind KIND would be dangerous with invisible text around.
18327 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18328 ;; First, try to get out of here as quickly as possible, to reduce overhead
18329 (if (and org-catch-invisible-edits
18330 (or (not (boundp 'visible-mode)) (not visible-mode))
18331 (or (get-char-property (point) 'invisible)
18332 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18333 ;; OK, we need to take a closer look
18334 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18335 (invisible-before-point (if (bobp) nil (get-char-property
18336 (1- (point)) 'invisible)))
18337 (border-and-ok-direction
18339 ;; Check if we are acting predictably before invisible text
18340 (and invisible-at-point (not invisible-before-point)
18341 (memq kind '(insert delete-backward)))
18342 ;; Check if we are acting predictably after invisible text
18343 ;; This works not well, and I have turned it off. It seems
18344 ;; better to always show and stop after invisible text.
18345 ;; (and (not invisible-at-point) invisible-before-point
18346 ;; (memq kind '(insert delete)))
18348 (when (or (memq invisible-at-point '(outline org-hide-block t))
18349 (memq invisible-before-point '(outline org-hide-block t)))
18350 (if (eq org-catch-invisible-edits 'error)
18351 (error "Editing in invisible areas is prohibited - make visible first"))
18352 (if (and org-custom-properties-overlays
18353 (y-or-n-p "Display invisible properties in this buffer? "))
18354 (org-toggle-custom-properties-visibility)
18355 ;; Make the area visible
18356 (save-excursion
18357 (if invisible-before-point
18358 (goto-char (previous-single-char-property-change
18359 (point) 'invisible)))
18360 (org-cycle))
18361 (cond
18362 ((eq org-catch-invisible-edits 'show)
18363 ;; That's it, we do the edit after showing
18364 (message
18365 "Unfolding invisible region around point before editing")
18366 (sit-for 1))
18367 ((and (eq org-catch-invisible-edits 'smart)
18368 border-and-ok-direction)
18369 (message "Unfolding invisible region around point before editing"))
18371 ;; Don't do the edit, make the user repeat it in full visibility
18372 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18374 (defun org-fix-tags-on-the-fly ()
18375 (when (and (equal (char-after (point-at-bol)) ?*)
18376 (org-at-heading-p))
18377 (org-align-tags-here org-tags-column)))
18379 (defun org-delete-backward-char (N)
18380 "Like `delete-backward-char', insert whitespace at field end in tables.
18381 When deleting backwards, in tables this function will insert whitespace in
18382 front of the next \"|\" separator, to keep the table aligned. The table will
18383 still be marked for re-alignment if the field did fill the entire column,
18384 because, in this case the deletion might narrow the column."
18385 (interactive "p")
18386 (org-check-before-invisible-edit 'delete-backward)
18387 (if (and (org-table-p)
18388 (eq N 1)
18389 (string-match "|" (buffer-substring (point-at-bol) (point)))
18390 (looking-at ".*?|"))
18391 (let ((pos (point))
18392 (noalign (looking-at "[^|\n\r]* |"))
18393 (c org-table-may-need-update))
18394 (backward-delete-char N)
18395 (if (not overwrite-mode)
18396 (progn
18397 (skip-chars-forward "^|")
18398 (insert " ")
18399 (goto-char (1- pos))))
18400 ;; noalign: if there were two spaces at the end, this field
18401 ;; does not determine the width of the column.
18402 (if noalign (setq org-table-may-need-update c)))
18403 (backward-delete-char N)
18404 (org-fix-tags-on-the-fly)))
18406 (defun org-delete-char (N)
18407 "Like `delete-char', but insert whitespace at field end in tables.
18408 When deleting characters, in tables this function will insert whitespace in
18409 front of the next \"|\" separator, to keep the table aligned. The table will
18410 still be marked for re-alignment if the field did fill the entire column,
18411 because, in this case the deletion might narrow the column."
18412 (interactive "p")
18413 (org-check-before-invisible-edit 'delete)
18414 (if (and (org-table-p)
18415 (not (bolp))
18416 (not (= (char-after) ?|))
18417 (eq N 1))
18418 (if (looking-at ".*?|")
18419 (let ((pos (point))
18420 (noalign (looking-at "[^|\n\r]* |"))
18421 (c org-table-may-need-update))
18422 (replace-match (concat
18423 (substring (match-string 0) 1 -1)
18424 " |"))
18425 (goto-char pos)
18426 ;; noalign: if there were two spaces at the end, this field
18427 ;; does not determine the width of the column.
18428 (if noalign (setq org-table-may-need-update c)))
18429 (delete-char N))
18430 (delete-char N)
18431 (org-fix-tags-on-the-fly)))
18433 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18434 (put 'org-self-insert-command 'delete-selection t)
18435 (put 'orgtbl-self-insert-command 'delete-selection t)
18436 (put 'org-delete-char 'delete-selection 'supersede)
18437 (put 'org-delete-backward-char 'delete-selection 'supersede)
18438 (put 'org-yank 'delete-selection 'yank)
18440 ;; Make `flyspell-mode' delay after some commands
18441 (put 'org-self-insert-command 'flyspell-delayed t)
18442 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18443 (put 'org-delete-char 'flyspell-delayed t)
18444 (put 'org-delete-backward-char 'flyspell-delayed t)
18446 ;; Make pabbrev-mode expand after org-mode commands
18447 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18448 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18450 ;; How to do this: Measure non-white length of current string
18451 ;; If equal to column width, we should realign.
18453 (defun org-remap (map &rest commands)
18454 "In MAP, remap the functions given in COMMANDS.
18455 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18456 (let (new old)
18457 (while commands
18458 (setq old (pop commands) new (pop commands))
18459 (if (fboundp 'command-remapping)
18460 (org-defkey map (vector 'remap old) new)
18461 (substitute-key-definition old new map global-map)))))
18463 (when (eq org-enable-table-editor 'optimized)
18464 ;; If the user wants maximum table support, we need to hijack
18465 ;; some standard editing functions
18466 (org-remap org-mode-map
18467 'self-insert-command 'org-self-insert-command
18468 'delete-char 'org-delete-char
18469 'delete-backward-char 'org-delete-backward-char)
18470 (org-defkey org-mode-map "|" 'org-force-self-insert))
18472 (defvar org-ctrl-c-ctrl-c-hook nil
18473 "Hook for functions attaching themselves to `C-c C-c'.
18475 This can be used to add additional functionality to the C-c C-c
18476 key which executes context-dependent commands. This hook is run
18477 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18478 run after the last test.
18480 Each function will be called with no arguments. The function
18481 must check if the context is appropriate for it to act. If yes,
18482 it should do its thing and then return a non-nil value. If the
18483 context is wrong, just do nothing and return nil.")
18485 (defvar org-ctrl-c-ctrl-c-final-hook nil
18486 "Hook for functions attaching themselves to `C-c C-c'.
18488 This can be used to add additional functionality to the C-c C-c
18489 key which executes context-dependent commands. This hook is run
18490 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18491 before the first test.
18493 Each function will be called with no arguments. The function
18494 must check if the context is appropriate for it to act. If yes,
18495 it should do its thing and then return a non-nil value. If the
18496 context is wrong, just do nothing and return nil.")
18498 (defvar org-tab-first-hook nil
18499 "Hook for functions to attach themselves to TAB.
18500 See `org-ctrl-c-ctrl-c-hook' for more information.
18501 This hook runs as the first action when TAB is pressed, even before
18502 `org-cycle' messes around with the `outline-regexp' to cater for
18503 inline tasks and plain list item folding.
18504 If any function in this hook returns t, any other actions that
18505 would have been caused by TAB (such as table field motion or visibility
18506 cycling) will not occur.")
18508 (defvar org-tab-after-check-for-table-hook nil
18509 "Hook for functions to attach themselves to TAB.
18510 See `org-ctrl-c-ctrl-c-hook' for more information.
18511 This hook runs after it has been established that the cursor is not in a
18512 table, but before checking if the cursor is in a headline or if global cycling
18513 should be done.
18514 If any function in this hook returns t, not other actions like visibility
18515 cycling will be done.")
18517 (defvar org-tab-after-check-for-cycling-hook nil
18518 "Hook for functions to attach themselves to TAB.
18519 See `org-ctrl-c-ctrl-c-hook' for more information.
18520 This hook runs after it has been established that not table field motion and
18521 not visibility should be done because of current context. This is probably
18522 the place where a package like yasnippets can hook in.")
18524 (defvar org-tab-before-tab-emulation-hook nil
18525 "Hook for functions to attach themselves to TAB.
18526 See `org-ctrl-c-ctrl-c-hook' for more information.
18527 This hook runs after every other options for TAB have been exhausted, but
18528 before indentation and \t insertion takes place.")
18530 (defvar org-metaleft-hook nil
18531 "Hook for functions attaching themselves to `M-left'.
18532 See `org-ctrl-c-ctrl-c-hook' for more information.")
18533 (defvar org-metaright-hook nil
18534 "Hook for functions attaching themselves to `M-right'.
18535 See `org-ctrl-c-ctrl-c-hook' for more information.")
18536 (defvar org-metaup-hook nil
18537 "Hook for functions attaching themselves to `M-up'.
18538 See `org-ctrl-c-ctrl-c-hook' for more information.")
18539 (defvar org-metadown-hook nil
18540 "Hook for functions attaching themselves to `M-down'.
18541 See `org-ctrl-c-ctrl-c-hook' for more information.")
18542 (defvar org-shiftmetaleft-hook nil
18543 "Hook for functions attaching themselves to `M-S-left'.
18544 See `org-ctrl-c-ctrl-c-hook' for more information.")
18545 (defvar org-shiftmetaright-hook nil
18546 "Hook for functions attaching themselves to `M-S-right'.
18547 See `org-ctrl-c-ctrl-c-hook' for more information.")
18548 (defvar org-shiftmetaup-hook nil
18549 "Hook for functions attaching themselves to `M-S-up'.
18550 See `org-ctrl-c-ctrl-c-hook' for more information.")
18551 (defvar org-shiftmetadown-hook nil
18552 "Hook for functions attaching themselves to `M-S-down'.
18553 See `org-ctrl-c-ctrl-c-hook' for more information.")
18554 (defvar org-metareturn-hook nil
18555 "Hook for functions attaching themselves to `M-RET'.
18556 See `org-ctrl-c-ctrl-c-hook' for more information.")
18557 (defvar org-shiftup-hook nil
18558 "Hook for functions attaching themselves to `S-up'.
18559 See `org-ctrl-c-ctrl-c-hook' for more information.")
18560 (defvar org-shiftup-final-hook nil
18561 "Hook for functions attaching themselves to `S-up'.
18562 This one runs after all other options except shift-select have been excluded.
18563 See `org-ctrl-c-ctrl-c-hook' for more information.")
18564 (defvar org-shiftdown-hook nil
18565 "Hook for functions attaching themselves to `S-down'.
18566 See `org-ctrl-c-ctrl-c-hook' for more information.")
18567 (defvar org-shiftdown-final-hook nil
18568 "Hook for functions attaching themselves to `S-down'.
18569 This one runs after all other options except shift-select have been excluded.
18570 See `org-ctrl-c-ctrl-c-hook' for more information.")
18571 (defvar org-shiftleft-hook nil
18572 "Hook for functions attaching themselves to `S-left'.
18573 See `org-ctrl-c-ctrl-c-hook' for more information.")
18574 (defvar org-shiftleft-final-hook nil
18575 "Hook for functions attaching themselves to `S-left'.
18576 This one runs after all other options except shift-select have been excluded.
18577 See `org-ctrl-c-ctrl-c-hook' for more information.")
18578 (defvar org-shiftright-hook nil
18579 "Hook for functions attaching themselves to `S-right'.
18580 See `org-ctrl-c-ctrl-c-hook' for more information.")
18581 (defvar org-shiftright-final-hook nil
18582 "Hook for functions attaching themselves to `S-right'.
18583 This one runs after all other options except shift-select have been excluded.
18584 See `org-ctrl-c-ctrl-c-hook' for more information.")
18586 (defun org-modifier-cursor-error ()
18587 "Throw an error, a modified cursor command was applied in wrong context."
18588 (error "This command is active in special context like tables, headlines or items"))
18590 (defun org-shiftselect-error ()
18591 "Throw an error because Shift-Cursor command was applied in wrong context."
18592 (if (and (boundp 'shift-select-mode) shift-select-mode)
18593 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18594 (error "This command works only in special context like headlines or timestamps")))
18596 (defun org-call-for-shift-select (cmd)
18597 (let ((this-command-keys-shift-translated t))
18598 (call-interactively cmd)))
18600 (defun org-shifttab (&optional arg)
18601 "Global visibility cycling or move to previous table field.
18602 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18603 on context.
18604 See the individual commands for more information."
18605 (interactive "P")
18606 (cond
18607 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18608 ((integerp arg)
18609 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18610 (message "Content view to level: %d" arg)
18611 (org-content (prefix-numeric-value arg2))
18612 (setq org-cycle-global-status 'overview)))
18613 (t (call-interactively 'org-global-cycle))))
18615 (defun org-shiftmetaleft ()
18616 "Promote subtree or delete table column.
18617 Calls `org-promote-subtree', `org-outdent-item-tree', or
18618 `org-table-delete-column', depending on context. See the
18619 individual commands for more information."
18620 (interactive)
18621 (cond
18622 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18623 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18624 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18625 ((if (not (org-region-active-p)) (org-at-item-p)
18626 (save-excursion (goto-char (region-beginning))
18627 (org-at-item-p)))
18628 (call-interactively 'org-outdent-item-tree))
18629 (t (org-modifier-cursor-error))))
18631 (defun org-shiftmetaright ()
18632 "Demote subtree or insert table column.
18633 Calls `org-demote-subtree', `org-indent-item-tree', or
18634 `org-table-insert-column', depending on context. See the
18635 individual commands for more information."
18636 (interactive)
18637 (cond
18638 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18639 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18640 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18641 ((if (not (org-region-active-p)) (org-at-item-p)
18642 (save-excursion (goto-char (region-beginning))
18643 (org-at-item-p)))
18644 (call-interactively 'org-indent-item-tree))
18645 (t (org-modifier-cursor-error))))
18647 (defun org-shiftmetaup (&optional arg)
18648 "Move subtree up or kill table row.
18649 Calls `org-move-subtree-up' or `org-table-kill-row' or
18650 `org-move-item-up' or `org-timestamp-up', depending on context.
18651 See the individual commands for more information."
18652 (interactive "P")
18653 (cond
18654 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18655 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18656 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18657 ((org-at-item-p) (call-interactively 'org-move-item-up))
18658 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18659 (call-interactively 'org-timestamp-up)))
18660 (t (org-modifier-cursor-error))))
18662 (defun org-shiftmetadown (&optional arg)
18663 "Move subtree down or insert table row.
18664 Calls `org-move-subtree-down' or `org-table-insert-row' or
18665 `org-move-item-down' or `org-timestamp-up', depending on context.
18666 See the individual commands for more information."
18667 (interactive "P")
18668 (cond
18669 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18670 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18671 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18672 ((org-at-item-p) (call-interactively 'org-move-item-down))
18673 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18674 (call-interactively 'org-timestamp-down)))
18675 (t (org-modifier-cursor-error))))
18677 (defsubst org-hidden-tree-error ()
18678 (error
18679 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18681 (defun org-metaleft (&optional arg)
18682 "Promote heading or move table column to left.
18683 Calls `org-do-promote' or `org-table-move-column', depending on context.
18684 With no specific context, calls the Emacs default `backward-word'.
18685 See the individual commands for more information."
18686 (interactive "P")
18687 (cond
18688 ((run-hook-with-args-until-success 'org-metaleft-hook))
18689 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18690 ((org-with-limited-levels
18691 (or (org-at-heading-p)
18692 (and (org-region-active-p)
18693 (save-excursion
18694 (goto-char (region-beginning))
18695 (org-at-heading-p)))))
18696 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18697 (call-interactively 'org-do-promote))
18698 ;; At an inline task.
18699 ((org-at-heading-p)
18700 (call-interactively 'org-inlinetask-promote))
18701 ((or (org-at-item-p)
18702 (and (org-region-active-p)
18703 (save-excursion
18704 (goto-char (region-beginning))
18705 (org-at-item-p))))
18706 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18707 (call-interactively 'org-outdent-item))
18708 (t (call-interactively 'backward-word))))
18710 (defun org-metaright (&optional arg)
18711 "Demote a subtree, a list item or move table column to right.
18712 In front of a drawer or a block keyword, indent it correctly.
18713 With no specific context, calls the Emacs default `forward-word'.
18714 See the individual commands for more information."
18715 (interactive "P")
18716 (cond
18717 ((run-hook-with-args-until-success 'org-metaright-hook))
18718 ((org-at-table-p) (call-interactively 'org-table-move-column))
18719 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18720 ((org-at-block-p) (call-interactively 'org-indent-block))
18721 ((org-with-limited-levels
18722 (or (org-at-heading-p)
18723 (and (org-region-active-p)
18724 (save-excursion
18725 (goto-char (region-beginning))
18726 (org-at-heading-p)))))
18727 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18728 (call-interactively 'org-do-demote))
18729 ;; At an inline task.
18730 ((org-at-heading-p)
18731 (call-interactively 'org-inlinetask-demote))
18732 ((or (org-at-item-p)
18733 (and (org-region-active-p)
18734 (save-excursion
18735 (goto-char (region-beginning))
18736 (org-at-item-p))))
18737 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18738 (call-interactively 'org-indent-item))
18739 (t (call-interactively 'forward-word))))
18741 (defun org-check-for-hidden (what)
18742 "Check if there are hidden headlines/items in the current visual line.
18743 WHAT can be either `headlines' or `items'. If the current line is
18744 an outline or item heading and it has a folded subtree below it,
18745 this function returns t, nil otherwise."
18746 (let ((re (cond
18747 ((eq what 'headlines) org-outline-regexp-bol)
18748 ((eq what 'items) (org-item-beginning-re))
18749 (t (error "This should not happen"))))
18750 beg end)
18751 (save-excursion
18752 (catch 'exit
18753 (unless (org-region-active-p)
18754 (setq beg (point-at-bol))
18755 (beginning-of-line 2)
18756 (while (and (not (eobp)) ;; this is like `next-line'
18757 (get-char-property (1- (point)) 'invisible))
18758 (beginning-of-line 2))
18759 (setq end (point))
18760 (goto-char beg)
18761 (goto-char (point-at-eol))
18762 (setq end (max end (point)))
18763 (while (re-search-forward re end t)
18764 (if (get-char-property (match-beginning 0) 'invisible)
18765 (throw 'exit t))))
18766 nil))))
18768 (autoload 'org-element-at-point "org-element")
18770 (declare-function org-element-at-point "org-element" (&optional keep-trail))
18771 (declare-function org-element-type "org-element" (element))
18772 (declare-function org-element-context "org-element" ())
18773 (declare-function org-element-contents "org-element" (element))
18774 (declare-function org-element-property "org-element" (property element))
18775 (declare-function org-element-paragraph-parser "org-element" (limit))
18776 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
18777 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
18778 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
18779 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
18780 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
18782 (defun org-metaup (&optional arg)
18783 "Move subtree up or move table row up.
18784 Calls `org-move-subtree-up' or `org-table-move-row' or
18785 `org-move-item-up', depending on context. See the individual commands
18786 for more information."
18787 (interactive "P")
18788 (cond
18789 ((run-hook-with-args-until-success 'org-metaup-hook))
18790 ((org-region-active-p)
18791 (let* ((a (min (region-beginning) (region-end)))
18792 (b (1- (max (region-beginning) (region-end))))
18793 (c (save-excursion (goto-char a)
18794 (move-beginning-of-line 0)))
18795 (d (save-excursion (goto-char a)
18796 (move-end-of-line 0) (point))))
18797 (transpose-regions a b c d)
18798 (goto-char c)))
18799 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
18800 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18801 ((org-at-item-p) (call-interactively 'org-move-item-up))
18802 (t (org-drag-element-backward))))
18804 (defun org-metadown (&optional arg)
18805 "Move subtree down or move table row down.
18806 Calls `org-move-subtree-down' or `org-table-move-row' or
18807 `org-move-item-down', depending on context. See the individual
18808 commands for more information."
18809 (interactive "P")
18810 (cond
18811 ((run-hook-with-args-until-success 'org-metadown-hook))
18812 ((org-region-active-p)
18813 (let* ((a (min (region-beginning) (region-end)))
18814 (b (max (region-beginning) (region-end)))
18815 (c (save-excursion (goto-char b)
18816 (move-beginning-of-line 1)))
18817 (d (save-excursion (goto-char b)
18818 (move-end-of-line 1) (1+ (point)))))
18819 (transpose-regions a b c d)
18820 (goto-char d)))
18821 ((org-at-table-p) (call-interactively 'org-table-move-row))
18822 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18823 ((org-at-item-p) (call-interactively 'org-move-item-down))
18824 (t (org-drag-element-forward))))
18826 (defun org-shiftup (&optional arg)
18827 "Increase item in timestamp or increase priority of current headline.
18828 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
18829 depending on context. See the individual commands for more information."
18830 (interactive "P")
18831 (cond
18832 ((run-hook-with-args-until-success 'org-shiftup-hook))
18833 ((and org-support-shift-select (org-region-active-p))
18834 (org-call-for-shift-select 'previous-line))
18835 ((org-at-timestamp-p t)
18836 (call-interactively (if org-edit-timestamp-down-means-later
18837 'org-timestamp-down 'org-timestamp-up)))
18838 ((and (not (eq org-support-shift-select 'always))
18839 org-enable-priority-commands
18840 (org-at-heading-p))
18841 (call-interactively 'org-priority-up))
18842 ((and (not org-support-shift-select) (org-at-item-p))
18843 (call-interactively 'org-previous-item))
18844 ((org-clocktable-try-shift 'up arg))
18845 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
18846 (org-support-shift-select
18847 (org-call-for-shift-select 'previous-line))
18848 (t (org-shiftselect-error))))
18850 (defun org-shiftdown (&optional arg)
18851 "Decrease item in timestamp or decrease priority of current headline.
18852 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
18853 depending on context. See the individual commands for more information."
18854 (interactive "P")
18855 (cond
18856 ((run-hook-with-args-until-success 'org-shiftdown-hook))
18857 ((and org-support-shift-select (org-region-active-p))
18858 (org-call-for-shift-select 'next-line))
18859 ((org-at-timestamp-p t)
18860 (call-interactively (if org-edit-timestamp-down-means-later
18861 'org-timestamp-up 'org-timestamp-down)))
18862 ((and (not (eq org-support-shift-select 'always))
18863 org-enable-priority-commands
18864 (org-at-heading-p))
18865 (call-interactively 'org-priority-down))
18866 ((and (not org-support-shift-select) (org-at-item-p))
18867 (call-interactively 'org-next-item))
18868 ((org-clocktable-try-shift 'down arg))
18869 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
18870 (org-support-shift-select
18871 (org-call-for-shift-select 'next-line))
18872 (t (org-shiftselect-error))))
18874 (defun org-shiftright (&optional arg)
18875 "Cycle the thing at point or in the current line, depending on context.
18876 Depending on context, this does one of the following:
18878 - switch a timestamp at point one day into the future
18879 - on a headline, switch to the next TODO keyword.
18880 - on an item, switch entire list to the next bullet type
18881 - on a property line, switch to the next allowed value
18882 - on a clocktable definition line, move time block into the future"
18883 (interactive "P")
18884 (cond
18885 ((run-hook-with-args-until-success 'org-shiftright-hook))
18886 ((and org-support-shift-select (org-region-active-p))
18887 (org-call-for-shift-select 'forward-char))
18888 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
18889 ((and (not (eq org-support-shift-select 'always))
18890 (org-at-heading-p))
18891 (let ((org-inhibit-logging
18892 (not org-treat-S-cursor-todo-selection-as-state-change))
18893 (org-inhibit-blocking
18894 (not org-treat-S-cursor-todo-selection-as-state-change)))
18895 (org-call-with-arg 'org-todo 'right)))
18896 ((or (and org-support-shift-select
18897 (not (eq org-support-shift-select 'always))
18898 (org-at-item-bullet-p))
18899 (and (not org-support-shift-select) (org-at-item-p)))
18900 (org-call-with-arg 'org-cycle-list-bullet nil))
18901 ((and (not (eq org-support-shift-select 'always))
18902 (org-at-property-p))
18903 (call-interactively 'org-property-next-allowed-value))
18904 ((org-clocktable-try-shift 'right arg))
18905 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
18906 (org-support-shift-select
18907 (org-call-for-shift-select 'forward-char))
18908 (t (org-shiftselect-error))))
18910 (defun org-shiftleft (&optional arg)
18911 "Cycle the thing at point or in the current line, depending on context.
18912 Depending on context, this does one of the following:
18914 - switch a timestamp at point one day into the past
18915 - on a headline, switch to the previous TODO keyword.
18916 - on an item, switch entire list to the previous bullet type
18917 - on a property line, switch to the previous allowed value
18918 - on a clocktable definition line, move time block into the past"
18919 (interactive "P")
18920 (cond
18921 ((run-hook-with-args-until-success 'org-shiftleft-hook))
18922 ((and org-support-shift-select (org-region-active-p))
18923 (org-call-for-shift-select 'backward-char))
18924 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
18925 ((and (not (eq org-support-shift-select 'always))
18926 (org-at-heading-p))
18927 (let ((org-inhibit-logging
18928 (not org-treat-S-cursor-todo-selection-as-state-change))
18929 (org-inhibit-blocking
18930 (not org-treat-S-cursor-todo-selection-as-state-change)))
18931 (org-call-with-arg 'org-todo 'left)))
18932 ((or (and org-support-shift-select
18933 (not (eq org-support-shift-select 'always))
18934 (org-at-item-bullet-p))
18935 (and (not org-support-shift-select) (org-at-item-p)))
18936 (org-call-with-arg 'org-cycle-list-bullet 'previous))
18937 ((and (not (eq org-support-shift-select 'always))
18938 (org-at-property-p))
18939 (call-interactively 'org-property-previous-allowed-value))
18940 ((org-clocktable-try-shift 'left arg))
18941 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
18942 (org-support-shift-select
18943 (org-call-for-shift-select 'backward-char))
18944 (t (org-shiftselect-error))))
18946 (defun org-shiftcontrolright ()
18947 "Switch to next TODO set."
18948 (interactive)
18949 (cond
18950 ((and org-support-shift-select (org-region-active-p))
18951 (org-call-for-shift-select 'forward-word))
18952 ((and (not (eq org-support-shift-select 'always))
18953 (org-at-heading-p))
18954 (org-call-with-arg 'org-todo 'nextset))
18955 (org-support-shift-select
18956 (org-call-for-shift-select 'forward-word))
18957 (t (org-shiftselect-error))))
18959 (defun org-shiftcontrolleft ()
18960 "Switch to previous TODO set."
18961 (interactive)
18962 (cond
18963 ((and org-support-shift-select (org-region-active-p))
18964 (org-call-for-shift-select 'backward-word))
18965 ((and (not (eq org-support-shift-select 'always))
18966 (org-at-heading-p))
18967 (org-call-with-arg 'org-todo 'previousset))
18968 (org-support-shift-select
18969 (org-call-for-shift-select 'backward-word))
18970 (t (org-shiftselect-error))))
18972 (defun org-shiftcontrolup ()
18973 "Change timestamps synchronously up in CLOCK log lines."
18974 (interactive)
18975 (cond ((and (not org-support-shift-select)
18976 (org-at-clock-log-p)
18977 (org-at-timestamp-p t))
18978 (org-clock-timestamps-up))
18979 (t (org-shiftselect-error))))
18981 (defun org-shiftcontroldown ()
18982 "Change timestamps synchronously down in CLOCK log lines."
18983 (interactive)
18984 (cond ((and (not org-support-shift-select)
18985 (org-at-clock-log-p)
18986 (org-at-timestamp-p t))
18987 (org-clock-timestamps-down))
18988 (t (org-shiftselect-error))))
18990 (defun org-ctrl-c-ret ()
18991 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
18992 (interactive)
18993 (cond
18994 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
18995 (t (call-interactively 'org-insert-heading))))
18997 (defun org-find-visible ()
18998 (let ((s (point)))
18999 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19000 (get-char-property s 'invisible)))
19002 (defun org-find-invisible ()
19003 (let ((s (point)))
19004 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19005 (not (get-char-property s 'invisible))))
19008 (defun org-copy-visible (beg end)
19009 "Copy the visible parts of the region."
19010 (interactive "r")
19011 (let (snippets s)
19012 (save-excursion
19013 (save-restriction
19014 (narrow-to-region beg end)
19015 (setq s (goto-char (point-min)))
19016 (while (not (= (point) (point-max)))
19017 (goto-char (org-find-invisible))
19018 (push (buffer-substring s (point)) snippets)
19019 (setq s (goto-char (org-find-visible))))))
19020 (kill-new (apply 'concat (nreverse snippets)))))
19022 (defun org-copy-special ()
19023 "Copy region in table or copy current subtree.
19024 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19025 See the individual commands for more information."
19026 (interactive)
19027 (call-interactively
19028 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19030 (defun org-cut-special ()
19031 "Cut region in table or cut current subtree.
19032 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19033 See the individual commands for more information."
19034 (interactive)
19035 (call-interactively
19036 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19038 (defun org-paste-special (arg)
19039 "Paste rectangular region into table, or past subtree relative to level.
19040 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19041 See the individual commands for more information."
19042 (interactive "P")
19043 (if (org-at-table-p)
19044 (org-table-paste-rectangle)
19045 (org-paste-subtree arg)))
19047 (defun org-edit-special (&optional arg)
19048 "Call a special editor for the stuff at point.
19049 When at a table, call the formula editor with `org-table-edit-formulas'.
19050 When at the first line of an src example, call `org-edit-src-code'.
19051 When in an #+include line, visit the include file. Otherwise call
19052 `ffap' to visit the file at point."
19053 (interactive)
19054 ;; possibly prep session before editing source
19055 (when arg
19056 (let* ((info (org-babel-get-src-block-info))
19057 (lang (nth 0 info))
19058 (params (nth 2 info))
19059 (session (cdr (assoc :session params))))
19060 (when (and info session) ;; we are in a source-code block with a session
19061 (funcall
19062 (intern (concat "org-babel-prep-session:" lang)) session params))))
19063 (cond ;; proceed with `org-edit-special'
19064 ((save-excursion
19065 (beginning-of-line 1)
19066 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19067 (find-file (org-trim (match-string 1))))
19068 ((org-edit-src-code))
19069 ((org-edit-fixed-width-region))
19070 ((org-at-table.el-p)
19071 (org-edit-src-code))
19072 ((or (org-at-table-p)
19073 (save-excursion
19074 (beginning-of-line 1)
19075 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19076 (call-interactively 'org-table-edit-formulas))
19077 (t (call-interactively 'ffap))))
19079 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19080 (defun org-ctrl-c-ctrl-c (&optional arg)
19081 "Set tags in headline, or update according to changed information at point.
19083 This command does many different things, depending on context:
19085 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19086 this is what we do.
19088 - If the cursor is on a statistics cookie, update it.
19090 - If the cursor is in a headline, prompt for tags and insert them
19091 into the current line, aligned to `org-tags-column'. When called
19092 with prefix arg, realign all tags in the current buffer.
19094 - If the cursor is in one of the special #+KEYWORD lines, this
19095 triggers scanning the buffer for these lines and updating the
19096 information.
19098 - If the cursor is inside a table, realign the table. This command
19099 works even if the automatic table editor has been turned off.
19101 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19102 the entire table.
19104 - If the cursor is at a footnote reference or definition, jump to
19105 the corresponding definition or references, respectively.
19107 - If the cursor is a the beginning of a dynamic block, update it.
19109 - If the current buffer is a capture buffer, close note and file it.
19111 - If the cursor is on a <<<target>>>, update radio targets and
19112 corresponding links in this buffer.
19114 - If the cursor is on a numbered item in a plain list, renumber the
19115 ordered list.
19117 - If the cursor is on a checkbox, toggle it.
19119 - If the cursor is on a code block, evaluate it. The variable
19120 `org-confirm-babel-evaluate' can be used to control prompting
19121 before code block evaluation, by default every code block
19122 evaluation requires confirmation. Code block evaluation can be
19123 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19124 (interactive "P")
19125 (let ((org-enable-table-editor t))
19126 (cond
19127 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19128 org-occur-highlights
19129 org-latex-fragment-image-overlays)
19130 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19131 (org-remove-occur-highlights)
19132 (org-remove-latex-fragment-image-overlays)
19133 (message "Temporary highlights/overlays removed from current buffer"))
19134 ((and (local-variable-p 'org-finish-function (current-buffer))
19135 (fboundp org-finish-function))
19136 (funcall org-finish-function))
19137 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19138 ((org-in-regexp org-ts-regexp-both)
19139 (org-timestamp-change 0 'day))
19140 ((or (looking-at org-property-start-re)
19141 (org-at-property-p))
19142 (call-interactively 'org-property-action))
19143 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19144 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19145 (or (org-at-heading-p) (org-at-item-p)))
19146 (call-interactively 'org-update-statistics-cookies))
19147 ((org-at-heading-p) (call-interactively 'org-set-tags))
19148 ((org-at-table.el-p)
19149 (message "Use C-c ' to edit table.el tables"))
19150 ((org-at-table-p)
19151 (org-table-maybe-eval-formula)
19152 (if arg
19153 (call-interactively 'org-table-recalculate)
19154 (org-table-maybe-recalculate-line))
19155 (call-interactively 'org-table-align)
19156 (orgtbl-send-table 'maybe))
19157 ((or (org-footnote-at-reference-p)
19158 (org-footnote-at-definition-p))
19159 (call-interactively 'org-footnote-action))
19160 ((org-at-item-checkbox-p)
19161 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19162 ;; list only if at top item.
19163 (let* ((cbox (match-string 1))
19164 (struct (org-list-struct))
19165 (old-struct (copy-tree struct))
19166 (parents (org-list-parents-alist struct))
19167 (orderedp (org-entry-get nil "ORDERED"))
19168 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19169 block-item)
19170 ;; Use a light version of `org-toggle-checkbox' to avoid
19171 ;; computing list structure twice.
19172 (let ((new-box (cond
19173 ((equal arg '(16)) "[-]")
19174 ((equal arg '(4)) nil)
19175 ((equal "[X]" cbox) "[ ]")
19176 (t "[X]"))))
19177 (if (and firstp arg)
19178 ;; If at first item of sub-list, remove check-box from
19179 ;; every item at the same level.
19180 (mapc
19181 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19182 (org-list-get-all-items
19183 (point-at-bol) struct (org-list-prevs-alist struct)))
19184 (org-list-set-checkbox (point-at-bol) struct new-box)))
19185 ;; Replicate `org-list-write-struct', while grabbing a return
19186 ;; value from `org-list-struct-fix-box'.
19187 (org-list-struct-fix-ind struct parents 2)
19188 (org-list-struct-fix-item-end struct)
19189 (let ((prevs (org-list-prevs-alist struct)))
19190 (org-list-struct-fix-bul struct prevs)
19191 (org-list-struct-fix-ind struct parents)
19192 (setq block-item
19193 (org-list-struct-fix-box struct parents prevs orderedp)))
19194 (org-list-struct-apply-struct struct old-struct)
19195 (org-update-checkbox-count-maybe)
19196 (when block-item
19197 (message
19198 "Checkboxes were removed due to unchecked box at line %d"
19199 (org-current-line block-item)))
19200 (when firstp (org-list-send-list 'maybe))))
19201 ((org-at-item-p)
19202 ;; Cursor at an item: repair list. Do checkbox related actions
19203 ;; only if function was called with an argument. Send list only
19204 ;; if at top item.
19205 (let* ((struct (org-list-struct))
19206 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19207 old-struct)
19208 (when arg
19209 (setq old-struct (copy-tree struct))
19210 (if firstp
19211 ;; If at first item of sub-list, add check-box to every
19212 ;; item at the same level.
19213 (mapc
19214 (lambda (pos)
19215 (unless (org-list-get-checkbox pos struct)
19216 (org-list-set-checkbox pos struct "[ ]")))
19217 (org-list-get-all-items
19218 (point-at-bol) struct (org-list-prevs-alist struct)))
19219 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19220 (org-list-write-struct
19221 struct (org-list-parents-alist struct) old-struct)
19222 (when arg (org-update-checkbox-count-maybe))
19223 (when firstp (org-list-send-list 'maybe))))
19224 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19225 ;; Dynamic block
19226 (beginning-of-line 1)
19227 (save-excursion (org-update-dblock)))
19228 ((save-excursion
19229 (let ((case-fold-search t))
19230 (beginning-of-line 1)
19231 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19232 (cond
19233 ((or (equal (match-string 1) "TBLFM")
19234 (equal (match-string 1) "tblfm"))
19235 ;; Recalculate the table before this line
19236 (save-excursion
19237 (beginning-of-line 1)
19238 (skip-chars-backward " \r\n\t")
19239 (if (org-at-table-p)
19240 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19242 (let ((org-inhibit-startup-visibility-stuff t)
19243 (org-startup-align-all-tables nil))
19244 (when (boundp 'org-table-coordinate-overlays)
19245 (mapc 'delete-overlay org-table-coordinate-overlays)
19246 (setq org-table-coordinate-overlays nil))
19247 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19248 (message "Local setup has been refreshed"))))
19249 ((org-clock-update-time-maybe))
19251 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19252 (error "C-c C-c can do nothing useful at this location"))))))
19254 (defun org-mode-restart ()
19255 "Restart Org-mode, to scan again for special lines.
19256 Also updates the keyword regular expressions."
19257 (interactive)
19258 (org-mode)
19259 (message "Org-mode restarted"))
19261 (defun org-kill-note-or-show-branches ()
19262 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19263 (interactive)
19264 (if (not org-finish-function)
19265 (progn
19266 (hide-subtree)
19267 (call-interactively 'show-branches))
19268 (let ((org-note-abort t))
19269 (funcall org-finish-function))))
19271 (defun org-return (&optional indent)
19272 "Goto next table row or insert a newline.
19273 Calls `org-table-next-row' or `newline', depending on context.
19274 See the individual commands for more information."
19275 (interactive)
19276 (let (org-ts-what)
19277 (cond
19278 ((or (bobp) (org-in-src-block-p))
19279 (if indent (newline-and-indent) (newline)))
19280 ((org-at-table-p)
19281 (org-table-justify-field-maybe)
19282 (call-interactively 'org-table-next-row))
19283 ;; when `newline-and-indent' is called within a list, make sure
19284 ;; text moved stays inside the item.
19285 ((and (org-in-item-p) indent)
19286 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19287 (progn
19288 (save-match-data (newline))
19289 (org-indent-line-to (length (match-string 0))))
19290 (let ((ind (org-get-indentation)))
19291 (newline)
19292 (if (org-looking-back org-list-end-re)
19293 (org-indent-line)
19294 (org-indent-line-to ind)))))
19295 ((and org-return-follows-link
19296 (org-at-timestamp-p t)
19297 (not (eq org-ts-what 'after)))
19298 (org-follow-timestamp-link))
19299 ((and org-return-follows-link
19300 (let ((tprop (get-text-property (point) 'face)))
19301 (or (eq tprop 'org-link)
19302 (and (listp tprop) (memq 'org-link tprop)))))
19303 (call-interactively 'org-open-at-point))
19304 ((and (org-at-heading-p)
19305 (looking-at
19306 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19307 (org-show-entry)
19308 (end-of-line 1)
19309 (newline))
19310 (t (if indent (newline-and-indent) (newline))))))
19312 (defun org-return-indent ()
19313 "Goto next table row or insert a newline and indent.
19314 Calls `org-table-next-row' or `newline-and-indent', depending on
19315 context. See the individual commands for more information."
19316 (interactive)
19317 (org-return t))
19319 (defun org-ctrl-c-star ()
19320 "Compute table, or change heading status of lines.
19321 Calls `org-table-recalculate' or `org-toggle-heading',
19322 depending on context."
19323 (interactive)
19324 (cond
19325 ((org-at-table-p)
19326 (call-interactively 'org-table-recalculate))
19328 ;; Convert all lines in region to list items
19329 (call-interactively 'org-toggle-heading))))
19331 (defun org-ctrl-c-minus ()
19332 "Insert separator line in table or modify bullet status of line.
19333 Also turns a plain line or a region of lines into list items.
19334 Calls `org-table-insert-hline', `org-toggle-item', or
19335 `org-cycle-list-bullet', depending on context."
19336 (interactive)
19337 (cond
19338 ((org-at-table-p)
19339 (call-interactively 'org-table-insert-hline))
19340 ((org-region-active-p)
19341 (call-interactively 'org-toggle-item))
19342 ((org-in-item-p)
19343 (call-interactively 'org-cycle-list-bullet))
19345 (call-interactively 'org-toggle-item))))
19347 (defun org-toggle-item (arg)
19348 "Convert headings or normal lines to items, items to normal lines.
19349 If there is no active region, only the current line is considered.
19351 If the first non blank line in the region is an headline, convert
19352 all headlines to items, shifting text accordingly.
19354 If it is an item, convert all items to normal lines.
19356 If it is normal text, change region into an item. With a prefix
19357 argument ARG, change each line in region into an item."
19358 (interactive "P")
19359 (let ((shift-text
19360 (function
19361 ;; Shift text in current section to IND, from point to END.
19362 ;; The function leaves point to END line.
19363 (lambda (ind end)
19364 (let ((min-i 1000) (end (copy-marker end)))
19365 ;; First determine the minimum indentation (MIN-I) of
19366 ;; the text.
19367 (save-excursion
19368 (catch 'exit
19369 (while (< (point) end)
19370 (let ((i (org-get-indentation)))
19371 (cond
19372 ;; Skip blank lines and inline tasks.
19373 ((looking-at "^[ \t]*$"))
19374 ((looking-at org-outline-regexp-bol))
19375 ;; We can't find less than 0 indentation.
19376 ((zerop i) (throw 'exit (setq min-i 0)))
19377 ((< i min-i) (setq min-i i))))
19378 (forward-line))))
19379 ;; Then indent each line so that a line indented to
19380 ;; MIN-I becomes indented to IND. Ignore blank lines
19381 ;; and inline tasks in the process.
19382 (let ((delta (- ind min-i)))
19383 (while (< (point) end)
19384 (unless (or (looking-at "^[ \t]*$")
19385 (looking-at org-outline-regexp-bol))
19386 (org-indent-line-to (+ (org-get-indentation) delta)))
19387 (forward-line)))))))
19388 (skip-blanks
19389 (function
19390 ;; Return beginning of first non-blank line, starting from
19391 ;; line at POS.
19392 (lambda (pos)
19393 (save-excursion
19394 (goto-char pos)
19395 (skip-chars-forward " \r\t\n")
19396 (point-at-bol)))))
19397 beg end)
19398 ;; Determine boundaries of changes.
19399 (if (org-region-active-p)
19400 (setq beg (funcall skip-blanks (region-beginning))
19401 end (copy-marker (region-end)))
19402 (setq beg (funcall skip-blanks (point-at-bol))
19403 end (copy-marker (point-at-eol))))
19404 ;; Depending on the starting line, choose an action on the text
19405 ;; between BEG and END.
19406 (org-with-limited-levels
19407 (save-excursion
19408 (goto-char beg)
19409 (cond
19410 ;; Case 1. Start at an item: de-itemize. Note that it only
19411 ;; happens when a region is active: `org-ctrl-c-minus'
19412 ;; would call `org-cycle-list-bullet' otherwise.
19413 ((org-at-item-p)
19414 (while (< (point) end)
19415 (when (org-at-item-p)
19416 (skip-chars-forward " \t")
19417 (delete-region (point) (match-end 0)))
19418 (forward-line)))
19419 ;; Case 2. Start at an heading: convert to items.
19420 ((org-at-heading-p)
19421 (let* ((bul (org-list-bullet-string "-"))
19422 (bul-len (length bul))
19423 ;; Indentation of the first heading. It should be
19424 ;; relative to the indentation of its parent, if any.
19425 (start-ind (save-excursion
19426 (cond
19427 ((not org-adapt-indentation) 0)
19428 ((not (outline-previous-heading)) 0)
19429 (t (length (match-string 0))))))
19430 ;; Level of first heading. Further headings will be
19431 ;; compared to it to determine hierarchy in the list.
19432 (ref-level (org-reduced-level (org-outline-level))))
19433 (while (< (point) end)
19434 (let* ((level (org-reduced-level (org-outline-level)))
19435 (delta (max 0 (- level ref-level))))
19436 ;; If current headline is less indented than the first
19437 ;; one, set it as reference, in order to preserve
19438 ;; subtrees.
19439 (when (< level ref-level) (setq ref-level level))
19440 (replace-match bul t t)
19441 (org-indent-line-to (+ start-ind (* delta bul-len)))
19442 ;; Ensure all text down to END (or SECTION-END) belongs
19443 ;; to the newly created item.
19444 (let ((section-end (save-excursion
19445 (or (outline-next-heading) (point)))))
19446 (forward-line)
19447 (funcall shift-text
19448 (+ start-ind (* (1+ delta) bul-len))
19449 (min end section-end)))))))
19450 ;; Case 3. Normal line with ARG: turn each non-item line into
19451 ;; an item.
19452 (arg
19453 (while (< (point) end)
19454 (unless (or (org-at-heading-p) (org-at-item-p))
19455 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19456 (replace-match
19457 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19458 (forward-line)))
19459 ;; Case 4. Normal line without ARG: make the first line of
19460 ;; region an item, and shift indentation of others
19461 ;; lines to set them as item's body.
19462 (t (let* ((bul (org-list-bullet-string "-"))
19463 (bul-len (length bul))
19464 (ref-ind (org-get-indentation)))
19465 (skip-chars-forward " \t")
19466 (insert bul)
19467 (forward-line)
19468 (while (< (point) end)
19469 ;; Ensure that lines less indented than first one
19470 ;; still get included in item body.
19471 (funcall shift-text
19472 (+ ref-ind bul-len)
19473 (min end (save-excursion (or (outline-next-heading)
19474 (point)))))
19475 (forward-line)))))))))
19477 (defun org-toggle-heading (&optional nstars)
19478 "Convert headings to normal text, or items or text to headings.
19479 If there is no active region, only the current line is considered.
19481 With a \\[universal-argument] prefix, convert the whole list at
19482 point into heading.
19484 In a region:
19486 - If the first non blank line is an headline, remove the stars
19487 from all headlines in the region.
19489 - If it is a normal line turn each and every normal line (i.e. not an
19490 heading or an item) in the region into a heading.
19492 - If it is a plain list item, turn all plain list items into headings.
19494 When converting a line into a heading, the number of stars is chosen
19495 such that the lines become children of the current entry. However,
19496 when a prefix argument is given, its value determines the number of
19497 stars to add."
19498 (interactive "P")
19499 (let ((skip-blanks
19500 (function
19501 ;; Return beginning of first non-blank line, starting from
19502 ;; line at POS.
19503 (lambda (pos)
19504 (save-excursion
19505 (goto-char pos)
19506 (while (org-at-comment-p) (forward-line))
19507 (skip-chars-forward " \r\t\n")
19508 (point-at-bol)))))
19509 beg end toggled)
19510 ;; Determine boundaries of changes. If a universal prefix has
19511 ;; been given, put the list in a region. If region ends at a bol,
19512 ;; do not consider the last line to be in the region.
19514 (when (and current-prefix-arg (org-at-item-p))
19515 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19516 (org-mark-element))
19518 (if (org-region-active-p)
19519 (setq beg (funcall skip-blanks (region-beginning))
19520 end (copy-marker (save-excursion
19521 (goto-char (region-end))
19522 (if (bolp) (point) (point-at-eol)))))
19523 (setq beg (funcall skip-blanks (point-at-bol))
19524 end (copy-marker (point-at-eol))))
19525 ;; Ensure inline tasks don't count as headings.
19526 (org-with-limited-levels
19527 (save-excursion
19528 (goto-char beg)
19529 (cond
19530 ;; Case 1. Started at an heading: de-star headings.
19531 ((org-at-heading-p)
19532 (while (< (point) end)
19533 (when (org-at-heading-p t)
19534 (looking-at org-outline-regexp) (replace-match "")
19535 (setq toggled t))
19536 (forward-line)))
19537 ;; Case 2. Started at an item: change items into headlines.
19538 ;; One star will be added by `org-list-to-subtree'.
19539 ((org-at-item-p)
19540 (let* ((stars (make-string
19541 (if nstars
19542 ;; subtract the star that will be added again by
19543 ;; `org-list-to-subtree'
19544 (1- (prefix-numeric-value current-prefix-arg))
19545 (or (org-current-level) 0))
19546 ?*))
19547 (add-stars
19548 (cond (nstars "") ; stars from prefix only
19549 ((equal stars "") "") ; before first heading
19550 (org-odd-levels-only "*") ; inside heading, odd
19551 (t "")))) ; inside heading, oddeven
19552 (while (< (point) end)
19553 (when (org-at-item-p)
19554 ;; Pay attention to cases when region ends before list.
19555 (let* ((struct (org-list-struct))
19556 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19557 (save-restriction
19558 (narrow-to-region (point) list-end)
19559 (insert
19560 (org-list-to-subtree
19561 (org-list-parse-list t)
19562 '(:istart (concat stars add-stars (funcall get-stars depth))
19563 :icount (concat stars add-stars (funcall get-stars depth)))))))
19564 (setq toggled t))
19565 (forward-line))))
19566 ;; Case 3. Started at normal text: make every line an heading,
19567 ;; skipping headlines and items.
19568 (t (let* ((stars (make-string
19569 (if nstars
19570 (prefix-numeric-value current-prefix-arg)
19571 (or (org-current-level) 0))
19572 ?*))
19573 (add-stars
19574 (cond (nstars "") ; stars from prefix only
19575 ((equal stars "") "*") ; before first heading
19576 (org-odd-levels-only "**") ; inside heading, odd
19577 (t "*"))) ; inside heading, oddeven
19578 (rpl (concat stars add-stars " ")))
19579 (while (< (point) end)
19580 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19581 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19582 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19583 (forward-line)))))))
19584 (unless toggled (message "Cannot toggle heading from here"))))
19586 (defun org-meta-return (&optional arg)
19587 "Insert a new heading or wrap a region in a table.
19588 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19589 See the individual commands for more information."
19590 (interactive "P")
19591 (cond
19592 ((run-hook-with-args-until-success 'org-metareturn-hook))
19593 ((or (org-at-drawer-p) (org-at-property-p))
19594 (newline-and-indent))
19595 ((org-at-table-p)
19596 (call-interactively 'org-table-wrap-region))
19597 (t (call-interactively 'org-insert-heading))))
19599 ;;; Menu entries
19601 (defsubst org-in-subtree-not-table-p ()
19602 "Are we in a subtree and not in a table?"
19603 (and (not (org-before-first-heading-p))
19604 (not (org-at-table-p))))
19606 ;; Define the Org-mode menus
19607 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19608 '("Tbl"
19609 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19610 ["Next Field" org-cycle (org-at-table-p)]
19611 ["Previous Field" org-shifttab (org-at-table-p)]
19612 ["Next Row" org-return (org-at-table-p)]
19613 "--"
19614 ["Blank Field" org-table-blank-field (org-at-table-p)]
19615 ["Edit Field" org-table-edit-field (org-at-table-p)]
19616 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19617 "--"
19618 ("Column"
19619 ["Move Column Left" org-metaleft (org-at-table-p)]
19620 ["Move Column Right" org-metaright (org-at-table-p)]
19621 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19622 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19623 ("Row"
19624 ["Move Row Up" org-metaup (org-at-table-p)]
19625 ["Move Row Down" org-metadown (org-at-table-p)]
19626 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19627 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19628 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19629 "--"
19630 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19631 ("Rectangle"
19632 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19633 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19634 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19635 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19636 "--"
19637 ("Calculate"
19638 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19639 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19640 ["Edit Formulas" org-edit-special (org-at-table-p)]
19641 "--"
19642 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19643 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19644 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19645 "--"
19646 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19647 "--"
19648 ["Sum Column/Rectangle" org-table-sum
19649 (or (org-at-table-p) (org-region-active-p))]
19650 ["Which Column?" org-table-current-column (org-at-table-p)])
19651 ["Debug Formulas"
19652 org-table-toggle-formula-debugger
19653 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19654 ["Show Col/Row Numbers"
19655 org-table-toggle-coordinate-overlays
19656 :style toggle
19657 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19658 "--"
19659 ["Create" org-table-create (and (not (org-at-table-p))
19660 org-enable-table-editor)]
19661 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19662 ["Import from File" org-table-import (not (org-at-table-p))]
19663 ["Export to File" org-table-export (org-at-table-p)]
19664 "--"
19665 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19667 (easy-menu-define org-org-menu org-mode-map "Org menu"
19668 '("Org"
19669 ("Show/Hide"
19670 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19671 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19672 ["Sparse Tree..." org-sparse-tree t]
19673 ["Reveal Context" org-reveal t]
19674 ["Show All" show-all t]
19675 "--"
19676 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19677 "--"
19678 ["New Heading" org-insert-heading t]
19679 ("Navigate Headings"
19680 ["Up" outline-up-heading t]
19681 ["Next" outline-next-visible-heading t]
19682 ["Previous" outline-previous-visible-heading t]
19683 ["Next Same Level" outline-forward-same-level t]
19684 ["Previous Same Level" outline-backward-same-level t]
19685 "--"
19686 ["Jump" org-goto t])
19687 ("Edit Structure"
19688 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19689 "--"
19690 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19691 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19692 "--"
19693 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19694 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19695 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19696 "--"
19697 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19698 "--"
19699 ["Copy visible text" org-copy-visible t]
19700 "--"
19701 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19702 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19703 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19704 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19705 "--"
19706 ["Sort Region/Children" org-sort t]
19707 "--"
19708 ["Convert to odd levels" org-convert-to-odd-levels t]
19709 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19710 ("Editing"
19711 ["Emphasis..." org-emphasize t]
19712 ["Edit Source Example" org-edit-special t]
19713 "--"
19714 ["Footnote new/jump" org-footnote-action t]
19715 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19716 ("Archive"
19717 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19718 "--"
19719 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19720 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19721 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19723 "--"
19724 ("Hyperlinks"
19725 ["Store Link (Global)" org-store-link t]
19726 ["Find existing link to here" org-occur-link-in-agenda-files t]
19727 ["Insert Link" org-insert-link t]
19728 ["Follow Link" org-open-at-point t]
19729 "--"
19730 ["Next link" org-next-link t]
19731 ["Previous link" org-previous-link t]
19732 "--"
19733 ["Descriptive Links"
19734 org-toggle-link-display
19735 :style radio
19736 :selected org-descriptive-links
19738 ["Literal Links"
19739 org-toggle-link-display
19740 :style radio
19741 :selected (not org-descriptive-links)])
19742 "--"
19743 ("TODO Lists"
19744 ["TODO/DONE/-" org-todo t]
19745 ("Select keyword"
19746 ["Next keyword" org-shiftright (org-at-heading-p)]
19747 ["Previous keyword" org-shiftleft (org-at-heading-p)]
19748 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
19749 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
19750 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
19751 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
19752 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
19753 "--"
19754 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
19755 :selected org-enforce-todo-dependencies :style toggle :active t]
19756 "Settings for tree at point"
19757 ["Do Children sequentially" org-toggle-ordered-property :style radio
19758 :selected (org-entry-get nil "ORDERED")
19759 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19760 ["Do Children parallel" org-toggle-ordered-property :style radio
19761 :selected (not (org-entry-get nil "ORDERED"))
19762 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
19763 "--"
19764 ["Set Priority" org-priority t]
19765 ["Priority Up" org-shiftup t]
19766 ["Priority Down" org-shiftdown t]
19767 "--"
19768 ["Get news from all feeds" org-feed-update-all t]
19769 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
19770 ["Customize feeds" (customize-variable 'org-feed-alist) t])
19771 ("TAGS and Properties"
19772 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
19773 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
19774 "--"
19775 ["Set property" org-set-property (not (org-before-first-heading-p))]
19776 ["Column view of properties" org-columns t]
19777 ["Insert Column View DBlock" org-insert-columns-dblock t])
19778 ("Dates and Scheduling"
19779 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
19780 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
19781 ("Change Date"
19782 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
19783 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
19784 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
19785 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
19786 ["Compute Time Range" org-evaluate-time-range t]
19787 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
19788 ["Deadline" org-deadline (not (org-before-first-heading-p))]
19789 "--"
19790 ["Custom time format" org-toggle-time-stamp-overlays
19791 :style radio :selected org-display-custom-times]
19792 "--"
19793 ["Goto Calendar" org-goto-calendar t]
19794 ["Date from Calendar" org-date-from-calendar t]
19795 "--"
19796 ["Start/Restart Timer" org-timer-start t]
19797 ["Pause/Continue Timer" org-timer-pause-or-continue t]
19798 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
19799 ["Insert Timer String" org-timer t]
19800 ["Insert Timer Item" org-timer-item t])
19801 ("Logging work"
19802 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
19803 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
19804 ["Clock out" org-clock-out t]
19805 ["Clock cancel" org-clock-cancel t]
19806 "--"
19807 ["Mark as default task" org-clock-mark-default-task t]
19808 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
19809 ["Goto running clock" org-clock-goto t]
19810 "--"
19811 ["Display times" org-clock-display t]
19812 ["Create clock table" org-clock-report t]
19813 "--"
19814 ["Record DONE time"
19815 (progn (setq org-log-done (not org-log-done))
19816 (message "Switching to %s will %s record a timestamp"
19817 (car org-done-keywords)
19818 (if org-log-done "automatically" "not")))
19819 :style toggle :selected org-log-done])
19820 "--"
19821 ["Agenda Command..." org-agenda t]
19822 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
19823 ("File List for Agenda")
19824 ("Special views current file"
19825 ["TODO Tree" org-show-todo-tree t]
19826 ["Check Deadlines" org-check-deadlines t]
19827 ["Timeline" org-timeline t]
19828 ["Tags/Property tree" org-match-sparse-tree t])
19829 "--"
19830 ["Export/Publish..." org-export t]
19831 ("LaTeX"
19832 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
19833 :selected org-cdlatex-mode]
19834 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
19835 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
19836 ["Modify math symbol" org-cdlatex-math-modify
19837 (org-inside-LaTeX-fragment-p)]
19838 ["Insert citation" org-reftex-citation t]
19839 "--"
19840 ["Template for BEAMER" (progn (require 'org-beamer)
19841 (org-insert-beamer-options-template)) t])
19842 "--"
19843 ("MobileOrg"
19844 ["Push Files and Views" org-mobile-push t]
19845 ["Get Captured and Flagged" org-mobile-pull t]
19846 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
19847 "--"
19848 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
19849 "--"
19850 ("Documentation"
19851 ["Show Version" org-version t]
19852 ["Info Documentation" org-info t])
19853 ("Customize"
19854 ["Browse Org Group" org-customize t]
19855 "--"
19856 ["Expand This Menu" org-create-customize-menu
19857 (fboundp 'customize-menu-create)])
19858 ["Send bug report" org-submit-bug-report t]
19859 "--"
19860 ("Refresh/Reload"
19861 ["Refresh setup current buffer" org-mode-restart t]
19862 ["Reload Org (after update)" org-reload t]
19863 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
19866 (defun org-info (&optional node)
19867 "Read documentation for Org-mode in the info system.
19868 With optional NODE, go directly to that node."
19869 (interactive)
19870 (info (format "(org)%s" (or node ""))))
19872 ;;;###autoload
19873 (defun org-submit-bug-report ()
19874 "Submit a bug report on Org-mode via mail.
19876 Don't hesitate to report any problems or inaccurate documentation.
19878 If you don't have setup sending mail from (X)Emacs, please copy the
19879 output buffer into your mail program, as it gives us important
19880 information about your Org-mode version and configuration."
19881 (interactive)
19882 (require 'reporter)
19883 (org-load-modules-maybe)
19884 (org-require-autoloaded-modules)
19885 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
19886 (reporter-submit-bug-report
19887 "emacs-orgmode@gnu.org"
19888 (org-version nil 'full)
19889 (let (list)
19890 (save-window-excursion
19891 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
19892 (delete-other-windows)
19893 (erase-buffer)
19894 (insert "You are about to submit a bug report to the Org-mode mailing list.
19896 We would like to add your full Org-mode and Outline configuration to the
19897 bug report. This greatly simplifies the work of the maintainer and
19898 other experts on the mailing list.
19900 HOWEVER, some variables you have customized may contain private
19901 information. The names of customers, colleagues, or friends, might
19902 appear in the form of file names, tags, todo states, or search strings.
19903 If you answer yes to the prompt, you might want to check and remove
19904 such private information before sending the email.")
19905 (add-text-properties (point-min) (point-max) '(face org-warning))
19906 (when (yes-or-no-p "Include your Org-mode configuration ")
19907 (mapatoms
19908 (lambda (v)
19909 (and (boundp v)
19910 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
19911 (or (and (symbol-value v)
19912 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
19913 (and
19914 (get v 'custom-type) (get v 'standard-value)
19915 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
19916 (push v list)))))
19917 (kill-buffer (get-buffer "*Warn about privacy*"))
19918 list))
19919 nil nil
19920 "Remember to cover the basics, that is, what you expected to happen and
19921 what in fact did happen. You don't know how to make a good report? See
19923 http://orgmode.org/manual/Feedback.html#Feedback
19925 Your bug report will be posted to the Org-mode mailing list.
19926 ------------------------------------------------------------------------")
19927 (save-excursion
19928 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
19929 (replace-match "\\1Bug: \\3 [\\2]")))))
19932 (defun org-install-agenda-files-menu ()
19933 (let ((bl (buffer-list)))
19934 (save-excursion
19935 (while bl
19936 (set-buffer (pop bl))
19937 (if (derived-mode-p 'org-mode) (setq bl nil)))
19938 (when (derived-mode-p 'org-mode)
19939 (easy-menu-change
19940 '("Org") "File List for Agenda"
19941 (append
19942 (list
19943 ["Edit File List" (org-edit-agenda-file-list) t]
19944 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
19945 ["Remove Current File from List" org-remove-file t]
19946 ["Cycle through agenda files" org-cycle-agenda-files t]
19947 ["Occur in all agenda files" org-occur-in-agenda-files t]
19948 "--")
19949 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
19951 ;;;; Documentation
19953 ;;;###autoload
19954 (defun org-require-autoloaded-modules ()
19955 (interactive)
19956 (mapc 'require
19957 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
19958 org-docbook org-exp org-html org-icalendar
19959 org-id org-latex
19960 org-publish org-remember org-table
19961 org-timer org-xoxo)))
19963 ;;;###autoload
19964 (defun org-reload (&optional uncompiled)
19965 "Reload all org lisp files.
19966 With prefix arg UNCOMPILED, load the uncompiled versions."
19967 (interactive "P")
19968 (require 'find-func)
19969 (let* ((file-re "^org\\(-.*\\)?\\.el")
19970 (dir-org (file-name-directory (org-find-library-dir "org")))
19971 (dir-org-contrib (ignore-errors
19972 (file-name-directory
19973 (org-find-library-dir "org-contribdir"))))
19974 (babel-files
19975 (mapcar (lambda (el) (concat "ob" (when el (format "-%s" el)) ".el"))
19976 (append (list nil "comint" "eval" "exp" "keys"
19977 "lob" "ref" "table" "tangle")
19978 (delq nil
19979 (mapcar
19980 (lambda (lang)
19981 (when (cdr lang) (symbol-name (car lang))))
19982 org-babel-load-languages)))))
19983 (files
19984 (append babel-files
19985 (and dir-org-contrib
19986 (directory-files dir-org-contrib t file-re))
19987 (directory-files dir-org t file-re)))
19988 (remove-re (concat (if (featurep 'xemacs)
19989 "org-colview" "org-colview-xemacs")
19990 "\\'")))
19991 (setq files (mapcar 'file-name-sans-extension files))
19992 (setq files (mapcar
19993 (lambda (x) (if (string-match remove-re x) nil x))
19994 files))
19995 (setq files (delq nil files))
19996 (mapc
19997 (lambda (f)
19998 (when (featurep (intern (file-name-nondirectory f)))
19999 (if (and (not uncompiled)
20000 (file-exists-p (concat f ".elc")))
20001 (load (concat f ".elc") nil nil 'nosuffix)
20002 (load (concat f ".el") nil nil 'nosuffix))))
20003 files)
20004 (load (concat dir-org "org-version.el") 'noerror nil 'nosuffix))
20005 (org-version nil 'full 'message))
20007 ;;;###autoload
20008 (defun org-customize ()
20009 "Call the customize function with org as argument."
20010 (interactive)
20011 (org-load-modules-maybe)
20012 (org-require-autoloaded-modules)
20013 (customize-browse 'org))
20015 (defun org-create-customize-menu ()
20016 "Create a full customization menu for Org-mode, insert it into the menu."
20017 (interactive)
20018 (org-load-modules-maybe)
20019 (org-require-autoloaded-modules)
20020 (if (fboundp 'customize-menu-create)
20021 (progn
20022 (easy-menu-change
20023 '("Org") "Customize"
20024 `(["Browse Org group" org-customize t]
20025 "--"
20026 ,(customize-menu-create 'org)
20027 ["Set" Custom-set t]
20028 ["Save" Custom-save t]
20029 ["Reset to Current" Custom-reset-current t]
20030 ["Reset to Saved" Custom-reset-saved t]
20031 ["Reset to Standard Settings" Custom-reset-standard t]))
20032 (message "\"Org\"-menu now contains full customization menu"))
20033 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20035 ;;;; Miscellaneous stuff
20037 ;;; Generally useful functions
20039 (defun org-get-at-bol (property)
20040 "Get text property PROPERTY at beginning of line."
20041 (get-text-property (point-at-bol) property))
20043 (defun org-find-text-property-in-string (prop s)
20044 "Return the first non-nil value of property PROP in string S."
20045 (or (get-text-property 0 prop s)
20046 (get-text-property (or (next-single-property-change 0 prop s) 0)
20047 prop s)))
20049 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20050 "Display the given MESSAGE as a warning."
20051 (if (fboundp 'display-warning)
20052 (display-warning 'org message
20053 (if (featurep 'xemacs) 'warning :warning))
20054 (let ((buf (get-buffer-create "*Org warnings*")))
20055 (with-current-buffer buf
20056 (goto-char (point-max))
20057 (insert "Warning (Org): " message)
20058 (unless (bolp)
20059 (newline)))
20060 (display-buffer buf)
20061 (sit-for 0))))
20063 (defun org-eval (form)
20064 "Eval FORM and return result."
20065 (condition-case error
20066 (eval form)
20067 (error (format "%%![Error: %s]" error))))
20069 (defun org-in-clocktable-p ()
20070 "Check if the cursor is in a clocktable."
20071 (let ((pos (point)) start)
20072 (save-excursion
20073 (end-of-line 1)
20074 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20075 (setq start (match-beginning 0))
20076 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20077 (>= (match-end 0) pos)
20078 start))))
20080 (defun org-in-commented-line ()
20081 "Is point in a line starting with `#'?"
20082 (equal (char-after (point-at-bol)) ?#))
20084 (defun org-in-indented-comment-line ()
20085 "Is point in a line starting with `#' after some white space?"
20086 (save-excursion
20087 (save-match-data
20088 (goto-char (point-at-bol))
20089 (looking-at "[ \t]*#"))))
20091 (defun org-in-verbatim-emphasis ()
20092 (save-match-data
20093 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20095 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20096 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20097 (if (and marker (marker-buffer marker)
20098 (buffer-live-p (marker-buffer marker)))
20099 (progn
20100 (org-pop-to-buffer-same-window (marker-buffer marker))
20101 (if (or (> marker (point-max)) (< marker (point-min)))
20102 (widen))
20103 (goto-char marker)
20104 (org-show-context 'org-goto))
20105 (if bookmark
20106 (bookmark-jump bookmark)
20107 (error "Cannot find location"))))
20109 (defun org-quote-csv-field (s)
20110 "Quote field for inclusion in CSV material."
20111 (if (string-match "[\",]" s)
20112 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20115 (defun org-force-self-insert (N)
20116 "Needed to enforce self-insert under remapping."
20117 (interactive "p")
20118 (self-insert-command N))
20120 (defun org-string-width (s)
20121 "Compute width of string, ignoring invisible characters.
20122 This ignores character with invisibility property `org-link', and also
20123 characters with property `org-cwidth', because these will become invisible
20124 upon the next fontification round."
20125 (let (b l)
20126 (when (or (eq t buffer-invisibility-spec)
20127 (assq 'org-link buffer-invisibility-spec))
20128 (while (setq b (text-property-any 0 (length s)
20129 'invisible 'org-link s))
20130 (setq s (concat (substring s 0 b)
20131 (substring s (or (next-single-property-change
20132 b 'invisible s) (length s)))))))
20133 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20134 (setq s (concat (substring s 0 b)
20135 (substring s (or (next-single-property-change
20136 b 'org-cwidth s) (length s))))))
20137 (setq l (string-width s) b -1)
20138 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20139 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20142 (defun org-shorten-string (s maxlength)
20143 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20144 If the string is shorter or has length MAXLENGTH, just return the
20145 original string. If it is longer, the functions finds a space in the
20146 string, breaks this string off at that locations and adds three dots
20147 as ellipsis. Including the ellipsis, the string will not be longer
20148 than MAXLENGTH. If finding a good breaking point in the string does
20149 not work, the string is just chopped off in the middle of a word
20150 if necessary."
20151 (if (<= (length s) maxlength)
20153 (let* ((n (max (- maxlength 4) 1))
20154 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20155 (if (string-match re s)
20156 (concat (match-string 1 s) "...")
20157 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20159 (defun org-get-indentation (&optional line)
20160 "Get the indentation of the current line, interpreting tabs.
20161 When LINE is given, assume it represents a line and compute its indentation."
20162 (if line
20163 (if (string-match "^ *" (org-remove-tabs line))
20164 (match-end 0))
20165 (save-excursion
20166 (beginning-of-line 1)
20167 (skip-chars-forward " \t")
20168 (current-column))))
20170 (defun org-get-string-indentation (s)
20171 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20172 (let ((n -1) (i 0) (w tab-width) c)
20173 (catch 'exit
20174 (while (< (setq n (1+ n)) (length s))
20175 (setq c (aref s n))
20176 (cond ((= c ?\ ) (setq i (1+ i)))
20177 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20178 (t (throw 'exit t)))))
20181 (defun org-remove-tabs (s &optional width)
20182 "Replace tabulators in S with spaces.
20183 Assumes that s is a single line, starting in column 0."
20184 (setq width (or width tab-width))
20185 (while (string-match "\t" s)
20186 (setq s (replace-match
20187 (make-string
20188 (- (* width (/ (+ (match-beginning 0) width) width))
20189 (match-beginning 0)) ?\ )
20190 t t s)))
20193 (defun org-fix-indentation (line ind)
20194 "Fix indentation in LINE.
20195 IND is a cons cell with target and minimum indentation.
20196 If the current indentation in LINE is smaller than the minimum,
20197 leave it alone. If it is larger than ind, set it to the target."
20198 (let* ((l (org-remove-tabs line))
20199 (i (org-get-indentation l))
20200 (i1 (car ind)) (i2 (cdr ind)))
20201 (if (>= i i2) (setq l (substring line i2)))
20202 (if (> i1 0)
20203 (concat (make-string i1 ?\ ) l)
20204 l)))
20206 (defun org-remove-indentation (code &optional n)
20207 "Remove the maximum common indentation from the lines in CODE.
20208 N may optionally be the number of spaces to remove."
20209 (with-temp-buffer
20210 (insert code)
20211 (org-do-remove-indentation n)
20212 (buffer-string)))
20214 (defun org-do-remove-indentation (&optional n)
20215 "Remove the maximum common indentation from the buffer."
20216 (untabify (point-min) (point-max))
20217 (let ((min 10000) re)
20218 (if n
20219 (setq min n)
20220 (goto-char (point-min))
20221 (while (re-search-forward "^ *[^ \n]" nil t)
20222 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20223 (unless (or (= min 0) (= min 10000))
20224 (setq re (format "^ \\{%d\\}" min))
20225 (goto-char (point-min))
20226 (while (re-search-forward re nil t)
20227 (replace-match "")
20228 (end-of-line 1))
20229 min)))
20231 (defun org-fill-template (template alist)
20232 "Find each %key of ALIST in TEMPLATE and replace it."
20233 (let ((case-fold-search nil)
20234 entry key value)
20235 (setq alist (sort (copy-sequence alist)
20236 (lambda (a b) (< (length (car a)) (length (car b))))))
20237 (while (setq entry (pop alist))
20238 (setq template
20239 (replace-regexp-in-string
20240 (concat "%" (regexp-quote (car entry)))
20241 (or (cdr entry) "") template t t)))
20242 template))
20244 (defun org-base-buffer (buffer)
20245 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20246 (if (not buffer)
20247 buffer
20248 (or (buffer-base-buffer buffer)
20249 buffer)))
20251 (defun org-trim (s)
20252 "Remove whitespace at beginning and end of string."
20253 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20254 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20257 (defun org-wrap (string &optional width lines)
20258 "Wrap string to either a number of lines, or a width in characters.
20259 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20260 that costs. If there is a word longer than WIDTH, the text is actually
20261 wrapped to the length of that word.
20262 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20263 many lines, whatever width that takes.
20264 The return value is a list of lines, without newlines at the end."
20265 (let* ((words (org-split-string string "[ \t\n]+"))
20266 (maxword (apply 'max (mapcar 'org-string-width words)))
20267 w ll)
20268 (cond (width
20269 (org-do-wrap words (max maxword width)))
20270 (lines
20271 (setq w maxword)
20272 (setq ll (org-do-wrap words maxword))
20273 (if (<= (length ll) lines)
20275 (setq ll words)
20276 (while (> (length ll) lines)
20277 (setq w (1+ w))
20278 (setq ll (org-do-wrap words w)))
20279 ll))
20280 (t (error "Cannot wrap this")))))
20282 (defun org-do-wrap (words width)
20283 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20284 (let (lines line)
20285 (while words
20286 (setq line (pop words))
20287 (while (and words (< (+ (length line) (length (car words))) width))
20288 (setq line (concat line " " (pop words))))
20289 (setq lines (push line lines)))
20290 (nreverse lines)))
20292 (defun org-split-string (string &optional separators)
20293 "Splits STRING into substrings at SEPARATORS.
20294 No empty strings are returned if there are matches at the beginning
20295 and end of string."
20296 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20297 (start 0)
20298 notfirst
20299 (list nil))
20300 (while (and (string-match rexp string
20301 (if (and notfirst
20302 (= start (match-beginning 0))
20303 (< start (length string)))
20304 (1+ start) start))
20305 (< (match-beginning 0) (length string)))
20306 (setq notfirst t)
20307 (or (eq (match-beginning 0) 0)
20308 (and (eq (match-beginning 0) (match-end 0))
20309 (eq (match-beginning 0) start))
20310 (setq list
20311 (cons (substring string start (match-beginning 0))
20312 list)))
20313 (setq start (match-end 0)))
20314 (or (eq start (length string))
20315 (setq list
20316 (cons (substring string start)
20317 list)))
20318 (nreverse list)))
20320 (defun org-quote-vert (s)
20321 "Replace \"|\" with \"\\vert\"."
20322 (while (string-match "|" s)
20323 (setq s (replace-match "\\vert" t t s)))
20326 (defun org-uuidgen-p (s)
20327 "Is S an ID created by UUIDGEN?"
20328 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20330 (defun org-in-src-block-p nil
20331 "Whether point is in a code source block."
20332 (let (ov)
20333 (when (setq ov (overlays-at (point)))
20334 (memq 'org-block-background
20335 (overlay-properties
20336 (car ov))))))
20338 (defun org-context ()
20339 "Return a list of contexts of the current cursor position.
20340 If several contexts apply, all are returned.
20341 Each context entry is a list with a symbol naming the context, and
20342 two positions indicating start and end of the context. Possible
20343 contexts are:
20345 :headline anywhere in a headline
20346 :headline-stars on the leading stars in a headline
20347 :todo-keyword on a TODO keyword (including DONE) in a headline
20348 :tags on the TAGS in a headline
20349 :priority on the priority cookie in a headline
20350 :item on the first line of a plain list item
20351 :item-bullet on the bullet/number of a plain list item
20352 :checkbox on the checkbox in a plain list item
20353 :table in an org-mode table
20354 :table-special on a special filed in a table
20355 :table-table in a table.el table
20356 :clocktable in a clocktable
20357 :src-block in a source block
20358 :link on a hyperlink
20359 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20360 :target on a <<target>>
20361 :radio-target on a <<<radio-target>>>
20362 :latex-fragment on a LaTeX fragment
20363 :latex-preview on a LaTeX fragment with overlaid preview image
20365 This function expects the position to be visible because it uses font-lock
20366 faces as a help to recognize the following contexts: :table-special, :link,
20367 and :keyword."
20368 (let* ((f (get-text-property (point) 'face))
20369 (faces (if (listp f) f (list f)))
20370 (case-fold-search t)
20371 (p (point)) clist o)
20372 ;; First the large context
20373 (cond
20374 ((org-at-heading-p t)
20375 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20376 (when (progn
20377 (beginning-of-line 1)
20378 (looking-at org-todo-line-tags-regexp))
20379 (push (org-point-in-group p 1 :headline-stars) clist)
20380 (push (org-point-in-group p 2 :todo-keyword) clist)
20381 (push (org-point-in-group p 4 :tags) clist))
20382 (goto-char p)
20383 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20384 (if (looking-at "\\[#[A-Z0-9]\\]")
20385 (push (org-point-in-group p 0 :priority) clist)))
20387 ((org-at-item-p)
20388 (push (org-point-in-group p 2 :item-bullet) clist)
20389 (push (list :item (point-at-bol)
20390 (save-excursion (org-end-of-item) (point)))
20391 clist)
20392 (and (org-at-item-checkbox-p)
20393 (push (org-point-in-group p 0 :checkbox) clist)))
20395 ((org-at-table-p)
20396 (push (list :table (org-table-begin) (org-table-end)) clist)
20397 (if (memq 'org-formula faces)
20398 (push (list :table-special
20399 (previous-single-property-change p 'face)
20400 (next-single-property-change p 'face)) clist)))
20401 ((org-at-table-p 'any)
20402 (push (list :table-table) clist)))
20403 (goto-char p)
20405 (let ((case-fold-search t))
20406 ;; New the "medium" contexts: clocktables, source blocks
20407 (cond ((org-in-clocktable-p)
20408 (push (list :clocktable
20409 (and (or (looking-at "#\\+BEGIN: clocktable")
20410 (search-backward "#+BEGIN: clocktable" nil t))
20411 (match-beginning 0))
20412 (and (re-search-forward "#\\+END:?" nil t)
20413 (match-end 0))) clist))
20414 ((org-in-src-block-p)
20415 (push (list :src-block
20416 (and (or (looking-at "#\\+BEGIN_SRC")
20417 (search-backward "#+BEGIN_SRC" nil t))
20418 (match-beginning 0))
20419 (and (search-forward "#+END_SRC" nil t)
20420 (match-beginning 0))) clist))))
20421 (goto-char p)
20423 ;; Now the small context
20424 (cond
20425 ((org-at-timestamp-p)
20426 (push (org-point-in-group p 0 :timestamp) clist))
20427 ((memq 'org-link faces)
20428 (push (list :link
20429 (previous-single-property-change p 'face)
20430 (next-single-property-change p 'face)) clist))
20431 ((memq 'org-special-keyword faces)
20432 (push (list :keyword
20433 (previous-single-property-change p 'face)
20434 (next-single-property-change p 'face)) clist))
20435 ((org-at-target-p)
20436 (push (org-point-in-group p 0 :target) clist)
20437 (goto-char (1- (match-beginning 0)))
20438 (if (looking-at org-radio-target-regexp)
20439 (push (org-point-in-group p 0 :radio-target) clist))
20440 (goto-char p))
20441 ((setq o (car (delq nil
20442 (mapcar
20443 (lambda (x)
20444 (if (memq x org-latex-fragment-image-overlays) x))
20445 (overlays-at (point))))))
20446 (push (list :latex-fragment
20447 (overlay-start o) (overlay-end o)) clist)
20448 (push (list :latex-preview
20449 (overlay-start o) (overlay-end o)) clist))
20450 ((org-inside-LaTeX-fragment-p)
20451 ;; FIXME: positions wrong.
20452 (push (list :latex-fragment (point) (point)) clist)))
20454 (setq clist (nreverse (delq nil clist)))
20455 clist))
20457 ;; FIXME: Compare with at-regexp-p Do we need both?
20458 (defun org-in-regexp (re &optional nlines visually)
20459 "Check if point is inside a match of regexp.
20460 Normally only the current line is checked, but you can include NLINES extra
20461 lines both before and after point into the search.
20462 If VISUALLY is set, require that the cursor is not after the match but
20463 really on, so that the block visually is on the match."
20464 (catch 'exit
20465 (let ((pos (point))
20466 (eol (point-at-eol (+ 1 (or nlines 0))))
20467 (inc (if visually 1 0)))
20468 (save-excursion
20469 (beginning-of-line (- 1 (or nlines 0)))
20470 (while (re-search-forward re eol t)
20471 (if (and (<= (match-beginning 0) pos)
20472 (>= (+ inc (match-end 0)) pos))
20473 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20475 (defun org-at-regexp-p (regexp)
20476 "Is point inside a match of REGEXP in the current line?"
20477 (catch 'exit
20478 (save-excursion
20479 (let ((pos (point)) (end (point-at-eol)))
20480 (beginning-of-line 1)
20481 (while (re-search-forward regexp end t)
20482 (if (and (<= (match-beginning 0) pos)
20483 (>= (match-end 0) pos))
20484 (throw 'exit t)))
20485 nil))))
20487 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20488 "Non-nil when point is between matches of START-RE and END-RE.
20490 Also return a non-nil value when point is on one of the matches.
20492 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20493 buffer positions. Default values are the positions of headlines
20494 surrounding the point.
20496 The functions returns a cons cell whose car (resp. cdr) is the
20497 position before START-RE (resp. after END-RE)."
20498 (save-match-data
20499 (let ((pos (point))
20500 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20501 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20502 beg end)
20503 (save-excursion
20504 ;; Point is on a block when on START-RE or if START-RE can be
20505 ;; found before it...
20506 (and (or (org-at-regexp-p start-re)
20507 (re-search-backward start-re limit-up t))
20508 (setq beg (match-beginning 0))
20509 ;; ... and END-RE after it...
20510 (goto-char (match-end 0))
20511 (re-search-forward end-re limit-down t)
20512 (> (setq end (match-end 0)) pos)
20513 ;; ... without another START-RE in-between.
20514 (goto-char (match-beginning 0))
20515 (not (re-search-backward start-re (1+ beg) t))
20516 ;; Return value.
20517 (cons beg end))))))
20519 (defun org-in-block-p (names)
20520 "Non-nil when point belongs to a block whose name belongs to NAMES.
20522 NAMES is a list of strings containing names of blocks.
20524 Return first block name matched, or nil. Beware that in case of
20525 nested blocks, the returned name may not belong to the closest
20526 block from point."
20527 (save-match-data
20528 (catch 'exit
20529 (let ((case-fold-search t)
20530 (lim-up (save-excursion (outline-previous-heading)))
20531 (lim-down (save-excursion (outline-next-heading))))
20532 (mapc (lambda (name)
20533 (let ((n (regexp-quote name)))
20534 (when (org-between-regexps-p
20535 (concat "^[ \t]*#\\+begin_" n)
20536 (concat "^[ \t]*#\\+end_" n)
20537 lim-up lim-down)
20538 (throw 'exit n))))
20539 names))
20540 nil)))
20542 (defun org-occur-in-agenda-files (regexp &optional nlines)
20543 "Call `multi-occur' with buffers for all agenda files."
20544 (interactive "sOrg-files matching: \np")
20545 (let* ((files (org-agenda-files))
20546 (tnames (mapcar 'file-truename files))
20547 (extra org-agenda-text-search-extra-files)
20549 (when (eq (car extra) 'agenda-archives)
20550 (setq extra (cdr extra))
20551 (setq files (org-add-archive-files files)))
20552 (while (setq f (pop extra))
20553 (unless (member (file-truename f) tnames)
20554 (add-to-list 'files f 'append)
20555 (add-to-list 'tnames (file-truename f) 'append)))
20556 (multi-occur
20557 (mapcar (lambda (x)
20558 (with-current-buffer
20559 (or (get-file-buffer x) (find-file-noselect x))
20560 (widen)
20561 (current-buffer)))
20562 files)
20563 regexp)))
20565 (if (boundp 'occur-mode-find-occurrence-hook)
20566 ;; Emacs 23
20567 (add-hook 'occur-mode-find-occurrence-hook
20568 (lambda ()
20569 (when (derived-mode-p 'org-mode)
20570 (org-reveal))))
20571 ;; Emacs 22
20572 (defadvice occur-mode-goto-occurrence
20573 (after org-occur-reveal activate)
20574 (and (derived-mode-p 'org-mode) (org-reveal)))
20575 (defadvice occur-mode-goto-occurrence-other-window
20576 (after org-occur-reveal activate)
20577 (and (derived-mode-p 'org-mode) (org-reveal)))
20578 (defadvice occur-mode-display-occurrence
20579 (after org-occur-reveal activate)
20580 (when (derived-mode-p 'org-mode)
20581 (let ((pos (occur-mode-find-occurrence)))
20582 (with-current-buffer (marker-buffer pos)
20583 (save-excursion
20584 (goto-char pos)
20585 (org-reveal)))))))
20587 (defun org-occur-link-in-agenda-files ()
20588 "Create a link and search for it in the agendas.
20589 The link is not stored in `org-stored-links', it is just created
20590 for the search purpose."
20591 (interactive)
20592 (let ((link (condition-case nil
20593 (org-store-link nil)
20594 (error "Unable to create a link to here"))))
20595 (org-occur-in-agenda-files (regexp-quote link))))
20597 (defun org-uniquify (list)
20598 "Remove duplicate elements from LIST."
20599 (let (res)
20600 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20601 res))
20603 (defun org-delete-all (elts list)
20604 "Remove all elements in ELTS from LIST."
20605 (while elts
20606 (setq list (delete (pop elts) list)))
20607 list)
20609 (defun org-count (cl-item cl-seq)
20610 "Count the number of occurrences of ITEM in SEQ.
20611 Taken from `count' in cl-seq.el with all keyword arguments removed."
20612 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20613 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20614 (while (< cl-start cl-end)
20615 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20616 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20617 (setq cl-start (1+ cl-start)))
20618 cl-count))
20620 (defun org-remove-if (predicate seq)
20621 "Remove everything from SEQ that fulfills PREDICATE."
20622 (let (res e)
20623 (while seq
20624 (setq e (pop seq))
20625 (if (not (funcall predicate e)) (push e res)))
20626 (nreverse res)))
20628 (defun org-remove-if-not (predicate seq)
20629 "Remove everything from SEQ that does not fulfill PREDICATE."
20630 (let (res e)
20631 (while seq
20632 (setq e (pop seq))
20633 (if (funcall predicate e) (push e res)))
20634 (nreverse res)))
20636 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20637 "Reduce two-argument FUNCTION across SEQ.
20638 Taken from `reduce' in cl-seq.el with all keyword arguments but
20639 \":initial-value\" removed."
20640 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20641 (cadr (memq :initial-value cl-keys)))
20642 (cl-seq (pop cl-seq))
20643 (t (funcall cl-func)))))
20644 (while cl-seq
20645 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20646 cl-accum))
20648 (defun org-back-over-empty-lines ()
20649 "Move backwards over whitespace, to the beginning of the first empty line.
20650 Returns the number of empty lines passed."
20651 (let ((pos (point)))
20652 (if (cdr (assoc 'heading org-blank-before-new-entry))
20653 (skip-chars-backward " \t\n\r")
20654 (unless (eobp)
20655 (forward-line -1)))
20656 (beginning-of-line 2)
20657 (goto-char (min (point) pos))
20658 (count-lines (point) pos)))
20660 (defun org-skip-whitespace ()
20661 (skip-chars-forward " \t\n\r"))
20663 (defun org-point-in-group (point group &optional context)
20664 "Check if POINT is in match-group GROUP.
20665 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20666 match. If the match group does not exist or point is not inside it,
20667 return nil."
20668 (and (match-beginning group)
20669 (>= point (match-beginning group))
20670 (<= point (match-end group))
20671 (if context
20672 (list context (match-beginning group) (match-end group))
20673 t)))
20675 (defun org-switch-to-buffer-other-window (&rest args)
20676 "Switch to buffer in a second window on the current frame.
20677 In particular, do not allow pop-up frames.
20678 Returns the newly created buffer."
20679 (let (pop-up-frames special-display-buffer-names special-display-regexps
20680 special-display-function)
20681 (apply 'switch-to-buffer-other-window args)))
20683 (defun org-combine-plists (&rest plists)
20684 "Create a single property list from all plists in PLISTS.
20685 The process starts by copying the first list, and then setting properties
20686 from the other lists. Settings in the last list are the most significant
20687 ones and overrule settings in the other lists."
20688 (let ((rtn (copy-sequence (pop plists)))
20689 p v ls)
20690 (while plists
20691 (setq ls (pop plists))
20692 (while ls
20693 (setq p (pop ls) v (pop ls))
20694 (setq rtn (plist-put rtn p v))))
20695 rtn))
20697 (defun org-replace-escapes (string table)
20698 "Replace %-escapes in STRING with values in TABLE.
20699 TABLE is an association list with keys like \"%a\" and string values.
20700 The sequences in STRING may contain normal field width and padding information,
20701 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20702 so values can contain further %-escapes if they are define later in TABLE."
20703 (let ((tbl (copy-alist table))
20704 (case-fold-search nil)
20705 (pchg 0)
20706 e re rpl)
20707 (while (setq e (pop tbl))
20708 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20709 (when (and (cdr e) (string-match re (cdr e)))
20710 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20711 (safe "SREF"))
20712 (add-text-properties 0 3 (list 'sref sref) safe)
20713 (setcdr e (replace-match safe t t (cdr e)))))
20714 (while (string-match re string)
20715 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20716 (cdr e)))
20717 (setq string (replace-match rpl t t string))))
20718 (while (setq pchg (next-property-change pchg string))
20719 (let ((sref (get-text-property pchg 'sref string)))
20720 (when (and sref (string-match "SREF" string pchg))
20721 (setq string (replace-match sref t t string)))))
20722 string))
20724 (defun org-sublist (list start end)
20725 "Return a section of LIST, from START to END.
20726 Counting starts at 1."
20727 (let (rtn (c start))
20728 (setq list (nthcdr (1- start) list))
20729 (while (and list (<= c end))
20730 (push (pop list) rtn)
20731 (setq c (1+ c)))
20732 (nreverse rtn)))
20734 (defun org-find-base-buffer-visiting (file)
20735 "Like `find-buffer-visiting' but always return the base buffer and
20736 not an indirect buffer."
20737 (let ((buf (or (get-file-buffer file)
20738 (find-buffer-visiting file))))
20739 (if buf
20740 (or (buffer-base-buffer buf) buf)
20741 nil)))
20743 (defun org-image-file-name-regexp (&optional extensions)
20744 "Return regexp matching the file names of images.
20745 If EXTENSIONS is given, only match these."
20746 (if (and (not extensions) (fboundp 'image-file-name-regexp))
20747 (image-file-name-regexp)
20748 (let ((image-file-name-extensions
20749 (or extensions
20750 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
20751 "xbm" "xpm" "pbm" "pgm" "ppm"))))
20752 (concat "\\."
20753 (regexp-opt (nconc (mapcar 'upcase
20754 image-file-name-extensions)
20755 image-file-name-extensions)
20757 "\\'"))))
20759 (defun org-file-image-p (file &optional extensions)
20760 "Return non-nil if FILE is an image."
20761 (save-match-data
20762 (string-match (org-image-file-name-regexp extensions) file)))
20764 (defun org-get-cursor-date ()
20765 "Return the date at cursor in as a time.
20766 This works in the calendar and in the agenda, anywhere else it just
20767 returns the current time."
20768 (let (date day defd)
20769 (cond
20770 ((eq major-mode 'calendar-mode)
20771 (setq date (calendar-cursor-to-date)
20772 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20773 ((eq major-mode 'org-agenda-mode)
20774 (setq day (get-text-property (point) 'day))
20775 (if day
20776 (setq date (calendar-gregorian-from-absolute day)
20777 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
20778 (nth 2 date))))))
20779 (or defd (current-time))))
20781 (defvar org-agenda-action-marker (make-marker)
20782 "Marker pointing to the entry for the next agenda action.")
20784 (defun org-mark-entry-for-agenda-action ()
20785 "Mark the current entry as target of an agenda action.
20786 Agenda actions are actions executed from the agenda with the key `k',
20787 which make use of the date at the cursor."
20788 (interactive)
20789 (move-marker org-agenda-action-marker
20790 (save-excursion (org-back-to-heading t) (point))
20791 (current-buffer))
20792 (message
20793 "Entry marked for action; press `k' at desired date in agenda or calendar"))
20795 (defun org-mark-subtree (&optional up)
20796 "Mark the current subtree.
20797 This puts point at the start of the current subtree, and mark at
20798 the end. If a numeric prefix UP is given, move up into the
20799 hierarchy of headlines by UP levels before marking the subtree."
20800 (interactive "P")
20801 (org-with-limited-levels
20802 (cond ((org-at-heading-p) (beginning-of-line))
20803 ((org-before-first-heading-p) (error "Not in a subtree"))
20804 (t (outline-previous-visible-heading 1))))
20805 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
20806 (if (org-called-interactively-p 'any)
20807 (call-interactively 'org-mark-element)
20808 (org-mark-element)))
20810 ;;; Indentation
20812 (defun org-indent-line ()
20813 "Indent line depending on context."
20814 (interactive)
20815 (let* ((pos (point))
20816 (itemp (org-at-item-p))
20817 (case-fold-search t)
20818 (org-drawer-regexp (or org-drawer-regexp "\000"))
20819 (inline-task-p (and (featurep 'org-inlinetask)
20820 (org-inlinetask-in-task-p)))
20821 (inline-re (and inline-task-p
20822 (org-inlinetask-outline-regexp)))
20823 column)
20824 (if (and orgstruct-is-++ (eq pos (point)))
20825 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
20826 (indent-according-to-mode))
20827 (beginning-of-line 1)
20828 (cond
20829 ;; Headings
20830 ((looking-at org-outline-regexp) (setq column 0))
20831 ;; Included files
20832 ((looking-at "#\\+include:") (setq column 0))
20833 ;; Footnote definition
20834 ((looking-at org-footnote-definition-re) (setq column 0))
20835 ;; Literal examples
20836 ((looking-at "[ \t]*:\\( \\|$\\)")
20837 (setq column (org-get-indentation))) ; do nothing
20838 ;; Lists
20839 ((ignore-errors (goto-char (org-in-item-p)))
20840 (setq column (if itemp
20841 (org-get-indentation)
20842 (org-list-item-body-column (point))))
20843 (goto-char pos))
20844 ;; Drawers
20845 ((and (looking-at "[ \t]*:END:")
20846 (save-excursion (re-search-backward org-drawer-regexp nil t)))
20847 (save-excursion
20848 (goto-char (1- (match-beginning 1)))
20849 (setq column (current-column))))
20850 ;; Special blocks
20851 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
20852 (save-excursion
20853 (re-search-backward
20854 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
20855 (setq column (org-get-indentation (match-string 0))))
20856 ((and (not (looking-at "[ \t]*#\\+begin_"))
20857 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
20858 (save-excursion
20859 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
20860 (setq column
20861 (cond ((equal (downcase (match-string 1)) "src")
20862 ;; src blocks: let `org-edit-src-exit' handle them
20863 (org-get-indentation))
20864 ((equal (downcase (match-string 1)) "example")
20865 (max (org-get-indentation)
20866 (org-get-indentation (match-string 0))))
20868 (org-get-indentation (match-string 0))))))
20869 ;; This line has nothing special, look at the previous relevant
20870 ;; line to compute indentation
20872 (beginning-of-line 0)
20873 (while (and (not (bobp))
20874 (not (looking-at org-drawer-regexp))
20875 ;; When point started in an inline task, do not move
20876 ;; above task starting line.
20877 (not (and inline-task-p (looking-at inline-re)))
20878 ;; Skip drawers, blocks, empty lines, verbatim,
20879 ;; comments, tables, footnotes definitions, lists,
20880 ;; inline tasks.
20881 (or (and (looking-at "[ \t]*:END:")
20882 (re-search-backward org-drawer-regexp nil t))
20883 (and (looking-at "[ \t]*#\\+end_")
20884 (re-search-backward "[ \t]*#\\+begin_"nil t))
20885 (looking-at "[ \t]*[\n:#|]")
20886 (looking-at org-footnote-definition-re)
20887 (and (ignore-errors (goto-char (org-in-item-p)))
20888 (goto-char
20889 (org-list-get-top-point (org-list-struct))))
20890 (and (not inline-task-p)
20891 (featurep 'org-inlinetask)
20892 (org-inlinetask-in-task-p)
20893 (or (org-inlinetask-goto-beginning) t))))
20894 (beginning-of-line 0))
20895 (cond
20896 ;; There was an heading above.
20897 ((looking-at "\\*+[ \t]+")
20898 (if (not org-adapt-indentation)
20899 (setq column 0)
20900 (goto-char (match-end 0))
20901 (setq column (current-column))))
20902 ;; A drawer had started and is unfinished
20903 ((looking-at org-drawer-regexp)
20904 (goto-char (1- (match-beginning 1)))
20905 (setq column (current-column)))
20906 ;; Else, nothing noticeable found: get indentation and go on.
20907 (t (setq column (org-get-indentation))))))
20908 ;; Now apply indentation and move cursor accordingly
20909 (goto-char pos)
20910 (if (<= (current-column) (current-indentation))
20911 (org-indent-line-to column)
20912 (save-excursion (org-indent-line-to column)))
20913 ;; Special polishing for properties, see `org-property-format'
20914 (setq column (current-column))
20915 (beginning-of-line 1)
20916 (if (looking-at
20917 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
20918 (replace-match (concat (match-string 1)
20919 (format org-property-format
20920 (match-string 2) (match-string 3)))
20921 t t))
20922 (org-move-to-column column))))
20924 (defun org-indent-drawer ()
20925 "Indent the drawer at point."
20926 (interactive)
20927 (let ((p (point))
20928 (e (and (save-excursion (re-search-forward ":END:" nil t))
20929 (match-end 0)))
20930 (folded
20931 (save-excursion
20932 (end-of-line)
20933 (when (overlays-at (point))
20934 (member 'invisible (overlay-properties
20935 (car (overlays-at (point)))))))))
20936 (when folded (org-cycle))
20937 (indent-for-tab-command)
20938 (while (and (move-beginning-of-line 2) (< (point) e))
20939 (indent-for-tab-command))
20940 (goto-char p)
20941 (when folded (org-cycle)))
20942 (message "Drawer at point indented"))
20944 (defun org-indent-block ()
20945 "Indent the block at point."
20946 (interactive)
20947 (let ((p (point))
20948 (case-fold-search t)
20949 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
20950 (match-end 0)))
20951 (folded
20952 (save-excursion
20953 (end-of-line)
20954 (when (overlays-at (point))
20955 (member 'invisible (overlay-properties
20956 (car (overlays-at (point)))))))))
20957 (when folded (org-cycle))
20958 (indent-for-tab-command)
20959 (while (and (move-beginning-of-line 2) (< (point) e))
20960 (indent-for-tab-command))
20961 (goto-char p)
20962 (when folded (org-cycle)))
20963 (message "Block at point indented"))
20965 (defun org-indent-region (start end)
20966 "Indent region."
20967 (interactive "r")
20968 (save-excursion
20969 (let ((line-end (org-current-line end)))
20970 (goto-char start)
20971 (while (< (org-current-line) line-end)
20972 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
20973 (t (call-interactively 'org-indent-line)))
20974 (move-beginning-of-line 2)))))
20977 ;;; Filling
20979 ;; We use our own fill-paragraph and auto-fill functions.
20981 ;; `org-fill-paragraph' relies on adaptive filling and context
20982 ;; checking. Appropriate `fill-prefix' is computed with
20983 ;; `org-adaptive-fill-function'.
20985 ;; `org-auto-fill-function' takes care of auto-filling. It calls
20986 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
20987 ;; `org-adaptive-fill-function' value. Internally,
20988 ;; `org-comment-line-break-function' breaks the line.
20990 ;; `org-setup-filling' installs filling and auto-filling related
20991 ;; variables during `org-mode' initialization.
20993 (defun org-setup-filling ()
20994 (interactive)
20995 ;; Prevent auto-fill from inserting unwanted new items.
20996 (when (boundp 'fill-nobreak-predicate)
20997 (org-set-local
20998 'fill-nobreak-predicate
20999 (org-uniquify
21000 (append fill-nobreak-predicate
21001 '(org-fill-paragraph-separate-nobreak-p
21002 org-fill-line-break-nobreak-p)))))
21003 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21004 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21005 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21006 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21008 (defvar org-element-paragraph-separate) ; org-element.el
21009 (defun org-fill-paragraph-separate-nobreak-p ()
21010 "Non-nil when a line break at point would insert a new item."
21011 (looking-at (substring org-element-paragraph-separate 1)))
21013 (defun org-fill-line-break-nobreak-p ()
21014 "Non-nil when a line break at point would create an Org line break."
21015 (save-excursion
21016 (skip-chars-backward "[ \t]")
21017 (skip-chars-backward "\\\\")
21018 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21020 (declare-function message-in-body-p "message" ())
21021 (defvar org-element--affiliated-re) ; From org-element.el
21022 (defun org-adaptive-fill-function ()
21023 "Compute a fill prefix for the current line.
21024 Return fill prefix, as a string, or nil if current line isn't
21025 meant to be filled."
21026 (org-with-wide-buffer
21027 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21028 ;; FIXME: This is really the job of orgstruct++-mode
21029 (let* ((p (line-beginning-position))
21030 (element (save-excursion (beginning-of-line)
21031 (org-element-at-point)))
21032 (type (org-element-type element))
21033 (post-affiliated
21034 (save-excursion
21035 (goto-char (org-element-property :begin element))
21036 (while (looking-at org-element--affiliated-re) (forward-line))
21037 (point))))
21038 (unless (< p post-affiliated)
21039 (case type
21040 (comment (looking-at "[ \t]*# ?") (match-string 0))
21041 (footnote-definition "")
21042 ((item plain-list)
21043 (make-string (org-list-item-body-column post-affiliated) ? ))
21044 (paragraph
21045 ;; Fill prefix is usually the same as the current line,
21046 ;; except if the paragraph is at the beginning of an item.
21047 (let ((parent (org-element-property :parent element)))
21048 (cond ((eq (org-element-type parent) 'item)
21049 (make-string (org-list-item-body-column
21050 (org-element-property :begin parent))
21051 ? ))
21052 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21053 (match-string 0))
21054 (t ""))))
21055 (comment-block
21056 ;; Only fill contents if P is within block boundaries.
21057 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21058 (forward-line)
21059 (point)))
21060 (cend (save-excursion
21061 (goto-char (org-element-property :end element))
21062 (skip-chars-backward " \r\t\n")
21063 (line-beginning-position))))
21064 (when (and (>= p cbeg) (< p cend))
21065 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21066 (match-string 0)
21067 ""))))))))))
21069 (declare-function message-goto-body "message" ())
21070 (defvar message-cite-prefix-regexp) ; From message.el
21071 (defvar org-element-all-objects) ; From org-element.el
21072 (defun org-fill-paragraph (&optional justify)
21073 "Fill element at point, when applicable.
21075 This function only applies to comment blocks, comments, example
21076 blocks and paragraphs. Also, as a special case, re-align table
21077 when point is at one.
21079 If JUSTIFY is non-nil (interactively, with prefix argument),
21080 justify as well. If `sentence-end-double-space' is non-nil, then
21081 period followed by one space does not end a sentence, so don't
21082 break a line there. The variable `fill-column' controls the
21083 width for filling.
21085 For convenience, when point is at a plain list, an item or
21086 a footnote definition, try to fill the first paragraph within."
21087 ;; Falls back on message-fill-paragraph when necessary
21088 (interactive)
21089 (if (and (derived-mode-p 'message-mode)
21090 (or (not (message-in-body-p))
21091 (save-excursion (move-beginning-of-line 1)
21092 (looking-at message-cite-prefix-regexp))))
21093 (let ((fill-paragraph-function
21094 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21095 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21096 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21097 (paragraph-separate
21098 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21099 (fill-paragraph nil))
21100 (save-excursion
21101 ;; Move to end of line in order to get the first paragraph
21102 ;; within a plain list or a footnote definition.
21103 (end-of-line)
21104 (let ((element (org-element-at-point)))
21105 ;; First check if point is in a blank line at the beginning of
21106 ;; the buffer. In that case, ignore filling.
21107 (if (< (point) (org-element-property :begin element)) t
21108 (case (org-element-type element)
21109 ;; Align Org tables, leave table.el tables as-is.
21110 (table-row (org-table-align) t)
21111 (table
21112 (when (eq (org-element-property :type element) 'org)
21113 (org-table-align))
21115 (paragraph
21116 ;; Paragraphs may contain `line-break' type objects.
21117 (let ((beg (max (point-min)
21118 (org-element-property :contents-begin element)))
21119 (end (min (point-max)
21120 (org-element-property :contents-end element))))
21121 ;; Do nothing if point is at an affiliated keyword.
21122 (if (< (point) beg) t
21123 (when (derived-mode-p 'message-mode)
21124 ;; In `message-mode', do not fill following
21125 ;; citation in current paragraph nor text before
21126 ;; message body.
21127 (let ((body-start (save-excursion (message-goto-body))))
21128 (when body-start (setq beg (max body-start beg))))
21129 (when (save-excursion
21130 (re-search-forward
21131 (concat "^" message-cite-prefix-regexp) end t))
21132 (setq end (match-beginning 0))))
21133 ;; Fill paragraph, taking line breaks into
21134 ;; consideration. For that, slice the paragraph
21135 ;; using line breaks as separators, and fill the
21136 ;; parts in reverse order to avoid messing with
21137 ;; markers.
21138 (save-excursion
21139 (goto-char end)
21140 (mapc
21141 (lambda (pos)
21142 (fill-region-as-paragraph pos (point) justify)
21143 (goto-char pos))
21144 ;; Find the list of ending positions for line
21145 ;; breaks in the current paragraph. Add paragraph
21146 ;; beginning to include first slice.
21147 (nreverse
21148 (cons
21150 (org-element-map
21151 (org-element--parse-objects
21152 beg end nil org-element-all-objects)
21153 'line-break
21154 (lambda (lb) (org-element-property :end lb)))))))
21155 t)))
21156 ;; Contents of `comment-block' type elements should be
21157 ;; filled as plain text, but only if point is within block
21158 ;; markers.
21159 (comment-block
21160 (let* ((case-fold-search t)
21161 (beg (save-excursion
21162 (goto-char (org-element-property :begin element))
21163 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21164 (forward-line)
21165 (point)))
21166 (end (save-excursion
21167 (goto-char (org-element-property :end element))
21168 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21169 (line-beginning-position))))
21170 (when (and (>= (point) beg) (< (point) end))
21171 (fill-region-as-paragraph
21172 (save-excursion
21173 (end-of-line)
21174 (re-search-backward "^[ \t]*$" beg 'move)
21175 (line-beginning-position))
21176 (save-excursion
21177 (beginning-of-line)
21178 (re-search-forward "^[ \t]*$" end 'move)
21179 (line-beginning-position))
21180 justify)))
21182 ;; Fill comments.
21183 (comment (fill-comment-paragraph justify))
21184 ;; Ignore every other element.
21185 (otherwise t)))))))
21187 (defun org-auto-fill-function ()
21188 "Auto-fill function."
21189 ;; Check if auto-filling is meaningful.
21190 (let ((fc (current-fill-column)))
21191 (when (and fc (> (current-column) fc))
21192 (let ((fill-prefix (org-adaptive-fill-function)))
21193 (when fill-prefix (do-auto-fill))))))
21195 (defun org-comment-line-break-function (&optional soft)
21196 "Break line at point and indent, continuing comment if within one.
21197 The inserted newline is marked hard if variable
21198 `use-hard-newlines' is true, unless optional argument SOFT is
21199 non-nil."
21200 (if soft (insert-and-inherit ?\n) (newline 1))
21201 (save-excursion (forward-char -1) (delete-horizontal-space))
21202 (delete-horizontal-space)
21203 (indent-to-left-margin)
21204 (insert-before-markers-and-inherit fill-prefix))
21207 ;;; Comments
21209 ;; Org comments syntax is quite complex. It requires the entire line
21210 ;; to be just a comment. Also, even with the right syntax at the
21211 ;; beginning of line, some some elements (i.e. verse-block or
21212 ;; example-block) don't accept comments. Usual Emacs comment commands
21213 ;; cannot cope with those requirements. Therefore, Org replaces them.
21215 ;; Org still relies on `comment-dwim', but cannot trust
21216 ;; `comment-only-p'. So, `comment-region-function' and
21217 ;; `uncomment-region-function' both point
21218 ;; to`org-comment-or-uncomment-region'. Eventually,
21219 ;; `org-insert-comment' takes care of insertion of comments at the
21220 ;; beginning of line.
21222 ;; `org-setup-comments-handling' install comments related variables
21223 ;; during `org-mode' initialization.
21225 (defun org-setup-comments-handling ()
21226 (interactive)
21227 (org-set-local 'comment-use-syntax nil)
21228 (org-set-local 'comment-start "# ")
21229 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21230 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21231 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21232 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21234 (defun org-insert-comment ()
21235 "Insert an empty comment above current line.
21236 If the line is empty, insert comment at its beginning."
21237 (beginning-of-line)
21238 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21239 (org-indent-line)
21240 (insert "# "))
21242 (defvar comment-empty-lines) ; From newcomment.el.
21243 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21244 "Comment or uncomment each non-blank line in the region.
21245 Uncomment each non-blank line between BEG and END if it only
21246 contains commented lines. Otherwise, comment them."
21247 (save-restriction
21248 ;; Restrict region
21249 (narrow-to-region (save-excursion (goto-char beg)
21250 (skip-chars-forward " \r\t\n" end)
21251 (line-beginning-position))
21252 (save-excursion (goto-char end)
21253 (skip-chars-backward " \r\t\n" beg)
21254 (line-end-position)))
21255 (let ((uncommentp
21256 ;; UNCOMMENTP is non-nil when every non blank line between
21257 ;; BEG and END is a comment.
21258 (save-excursion
21259 (goto-char (point-min))
21260 (while (and (not (eobp))
21261 (let ((element (org-element-at-point)))
21262 (and (eq (org-element-type element) 'comment)
21263 (goto-char (min (point-max)
21264 (org-element-property
21265 :end element)))))))
21266 (eobp))))
21267 (if uncommentp
21268 ;; Only blank lines and comments in region: uncomment it.
21269 (save-excursion
21270 (goto-char (point-min))
21271 (while (not (eobp))
21272 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21273 (replace-match "" nil nil nil 1))
21274 (forward-line)))
21275 ;; Comment each line in region.
21276 (let ((min-indent (point-max)))
21277 ;; First find the minimum indentation across all lines.
21278 (save-excursion
21279 (goto-char (point-min))
21280 (while (and (not (eobp)) (not (zerop min-indent)))
21281 (unless (looking-at "[ \t]*$")
21282 (setq min-indent (min min-indent (current-indentation))))
21283 (forward-line)))
21284 ;; Then loop over all lines.
21285 (save-excursion
21286 (goto-char (point-min))
21287 (while (not (eobp))
21288 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21289 (org-move-to-column min-indent t)
21290 (insert comment-start))
21291 (forward-line))))))))
21294 ;;; Other stuff.
21296 (defun org-toggle-fixed-width-section (arg)
21297 "Toggle the fixed-width export.
21298 If there is no active region, the QUOTE keyword at the current headline is
21299 inserted or removed. When present, it causes the text between this headline
21300 and the next to be exported as fixed-width text, and unmodified.
21301 If there is an active region, this command adds or removes a colon as the
21302 first character of this line. If the first character of a line is a colon,
21303 this line is also exported in fixed-width font."
21304 (interactive "P")
21305 (let* ((cc 0)
21306 (regionp (org-region-active-p))
21307 (beg (if regionp (region-beginning) (point)))
21308 (end (if regionp (region-end)))
21309 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21310 (case-fold-search nil)
21311 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21312 off)
21313 (if regionp
21314 (save-excursion
21315 (goto-char beg)
21316 (setq cc (current-column))
21317 (beginning-of-line 1)
21318 (setq off (looking-at re))
21319 (while (> nlines 0)
21320 (setq nlines (1- nlines))
21321 (beginning-of-line 1)
21322 (cond
21323 (arg
21324 (org-move-to-column cc t)
21325 (insert ": \n")
21326 (forward-line -1))
21327 ((and off (looking-at re))
21328 (replace-match "" t t nil 1))
21329 ((not off) (org-move-to-column cc t) (insert ": ")))
21330 (forward-line 1)))
21331 (save-excursion
21332 (org-back-to-heading)
21333 (cond
21334 ((looking-at (format org-heading-keyword-regexp-format
21335 org-quote-string))
21336 (goto-char (match-end 1))
21337 (looking-at (concat " +" org-quote-string))
21338 (replace-match "" t t)
21339 (when (eolp) (insert " ")))
21340 ((looking-at org-outline-regexp)
21341 (goto-char (match-end 0))
21342 (insert org-quote-string " ")))))))
21344 (defun org-reftex-citation ()
21345 "Use reftex-citation to insert a citation into the buffer.
21346 This looks for a line like
21348 #+BIBLIOGRAPHY: foo plain option:-d
21350 and derives from it that foo.bib is the bibliography file relevant
21351 for this document. It then installs the necessary environment for RefTeX
21352 to work in this buffer and calls `reftex-citation' to insert a citation
21353 into the buffer.
21355 Export of such citations to both LaTeX and HTML is handled by the contributed
21356 package org-exp-bibtex by Taru Karttunen."
21357 (interactive)
21358 (let ((reftex-docstruct-symbol 'rds)
21359 (reftex-cite-format "\\cite{%l}")
21360 rds bib)
21361 (save-excursion
21362 (save-restriction
21363 (widen)
21364 (let ((case-fold-search t)
21365 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21366 (if (not (save-excursion
21367 (or (re-search-forward re nil t)
21368 (re-search-backward re nil t))))
21369 (error "No bibliography defined in file")
21370 (setq bib (concat (match-string 1) ".bib")
21371 rds (list (list 'bib bib)))))))
21372 (call-interactively 'reftex-citation)))
21374 ;;;; Functions extending outline functionality
21376 (defun org-beginning-of-line (&optional arg)
21377 "Go to the beginning of the current line. If that is invisible, continue
21378 to a visible line beginning. This makes the function of C-a more intuitive.
21379 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21380 first attempt, and only move to after the tags when the cursor is already
21381 beyond the end of the headline."
21382 (interactive "P")
21383 (let ((pos (point))
21384 (special (if (consp org-special-ctrl-a/e)
21385 (car org-special-ctrl-a/e)
21386 org-special-ctrl-a/e))
21387 refpos)
21388 (if (org-bound-and-true-p line-move-visual)
21389 (beginning-of-visual-line 1)
21390 (beginning-of-line 1))
21391 (if (and arg (fboundp 'move-beginning-of-line))
21392 (call-interactively 'move-beginning-of-line)
21393 (if (bobp)
21395 (backward-char 1)
21396 (if (org-truely-invisible-p)
21397 (while (and (not (bobp)) (org-truely-invisible-p))
21398 (backward-char 1)
21399 (beginning-of-line 1))
21400 (forward-char 1))))
21401 (when special
21402 (cond
21403 ((and (looking-at org-complex-heading-regexp)
21404 (= (char-after (match-end 1)) ?\ ))
21405 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21406 (point-at-eol)))
21407 (goto-char
21408 (if (eq special t)
21409 (cond ((> pos refpos) refpos)
21410 ((= pos (point)) refpos)
21411 (t (point)))
21412 (cond ((> pos (point)) (point))
21413 ((not (eq last-command this-command)) (point))
21414 (t refpos)))))
21415 ((org-at-item-p)
21416 ;; Being at an item and not looking at an the item means point
21417 ;; was previously moved to beginning of a visual line, which
21418 ;; doesn't contain the item. Therefore, do nothing special,
21419 ;; just stay here.
21420 (when (looking-at org-list-full-item-re)
21421 ;; Set special position at first white space character after
21422 ;; bullet, and check-box, if any.
21423 (let ((after-bullet
21424 (let ((box (match-end 3)))
21425 (if (not box) (match-end 1)
21426 (let ((after (char-after box)))
21427 (if (and after (= after ? )) (1+ box) box))))))
21428 ;; Special case: Move point to special position when
21429 ;; currently after it or at beginning of line.
21430 (if (eq special t)
21431 (when (or (> pos after-bullet) (= (point) pos))
21432 (goto-char after-bullet))
21433 ;; Reversed case: Move point to special position when
21434 ;; point was already at beginning of line and command is
21435 ;; repeated.
21436 (when (and (= (point) pos) (eq last-command this-command))
21437 (goto-char after-bullet))))))))
21438 (org-no-warnings
21439 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21441 (defun org-end-of-line (&optional arg)
21442 "Go to the end of the line.
21443 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21444 first attempt, and only move to after the tags when the cursor is already
21445 beyond the end of the headline."
21446 (interactive "P")
21447 (let ((special (if (consp org-special-ctrl-a/e)
21448 (cdr org-special-ctrl-a/e)
21449 org-special-ctrl-a/e)))
21450 (cond
21451 ((or (not special) arg
21452 (not (or (org-at-heading-p) (org-at-item-p) (org-at-drawer-p))))
21453 (call-interactively
21454 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21455 ((fboundp 'move-end-of-line) 'move-end-of-line)
21456 (t 'end-of-line))))
21457 ((org-at-heading-p)
21458 (let ((pos (point)))
21459 (beginning-of-line 1)
21460 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21461 (if (eq special t)
21462 (if (or (< pos (match-beginning 1))
21463 (= pos (match-end 0)))
21464 (goto-char (match-beginning 1))
21465 (goto-char (match-end 0)))
21466 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
21467 (goto-char (match-end 0))
21468 (goto-char (match-beginning 1))))
21469 (call-interactively (if (fboundp 'move-end-of-line)
21470 'move-end-of-line
21471 'end-of-line)))))
21472 ((org-at-drawer-p)
21473 (move-end-of-line 1)
21474 (when (overlays-at (1- (point))) (backward-char 1)))
21475 ;; At an item: Move before any hidden text.
21476 (t (call-interactively
21477 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
21478 ((fboundp 'move-end-of-line) 'move-end-of-line)
21479 (t 'end-of-line)))))
21480 (org-no-warnings
21481 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21483 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21484 (define-key org-mode-map "\C-e" 'org-end-of-line)
21486 (defun org-backward-sentence (&optional arg)
21487 "Go to beginning of sentence, or beginning of table field.
21488 This will call `backward-sentence' or `org-table-beginning-of-field',
21489 depending on context."
21490 (interactive "P")
21491 (cond
21492 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21493 (t (call-interactively 'backward-sentence))))
21495 (defun org-forward-sentence (&optional arg)
21496 "Go to end of sentence, or end of table field.
21497 This will call `forward-sentence' or `org-table-end-of-field',
21498 depending on context."
21499 (interactive "P")
21500 (cond
21501 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21502 (t (call-interactively 'forward-sentence))))
21504 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21505 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21507 (defun org-kill-line (&optional arg)
21508 "Kill line, to tags or end of line."
21509 (interactive "P")
21510 (cond
21511 ((or (not org-special-ctrl-k)
21512 (bolp)
21513 (not (org-at-heading-p)))
21514 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21515 org-ctrl-k-protect-subtree)
21516 (if (or (eq org-ctrl-k-protect-subtree 'error)
21517 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21518 (error "C-k aborted - would kill hidden subtree")))
21519 (call-interactively
21520 (if (and (boundp 'visual-line-mode) visual-line-mode) 'kill-visual-line 'kill-line)))
21521 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21522 (kill-region (point) (match-beginning 1))
21523 (org-set-tags nil t))
21524 (t (kill-region (point) (point-at-eol)))))
21526 (define-key org-mode-map "\C-k" 'org-kill-line)
21528 (defun org-yank (&optional arg)
21529 "Yank. If the kill is a subtree, treat it specially.
21530 This command will look at the current kill and check if is a single
21531 subtree, or a series of subtrees[1]. If it passes the test, and if the
21532 cursor is at the beginning of a line or after the stars of a currently
21533 empty headline, then the yank is handled specially. How exactly depends
21534 on the value of the following variables, both set by default.
21536 org-yank-folded-subtrees
21537 When set, the subtree(s) will be folded after insertion, but only
21538 if doing so would now swallow text after the yanked text.
21540 org-yank-adjusted-subtrees
21541 When set, the subtree will be promoted or demoted in order to
21542 fit into the local outline tree structure, which means that the level
21543 will be adjusted so that it becomes the smaller one of the two
21544 *visible* surrounding headings.
21546 Any prefix to this command will cause `yank' to be called directly with
21547 no special treatment. In particular, a simple \\[universal-argument] prefix \
21548 will just
21549 plainly yank the text as it is.
21551 \[1] The test checks if the first non-white line is a heading
21552 and if there are no other headings with fewer stars."
21553 (interactive "P")
21554 (org-yank-generic 'yank arg))
21556 (defun org-yank-generic (command arg)
21557 "Perform some yank-like command.
21559 This function implements the behavior described in the `org-yank'
21560 documentation. However, it has been generalized to work for any
21561 interactive command with similar behavior."
21563 ;; pretend to be command COMMAND
21564 (setq this-command command)
21566 (if arg
21567 (call-interactively command)
21569 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21570 (and (org-kill-is-subtree-p)
21571 (or (bolp)
21572 (and (looking-at "[ \t]*$")
21573 (string-match
21574 "\\`\\*+\\'"
21575 (buffer-substring (point-at-bol) (point)))))))
21576 swallowp)
21577 (cond
21578 ((and subtreep org-yank-folded-subtrees)
21579 (let ((beg (point))
21580 end)
21581 (if (and subtreep org-yank-adjusted-subtrees)
21582 (org-paste-subtree nil nil 'for-yank)
21583 (call-interactively command))
21585 (setq end (point))
21586 (goto-char beg)
21587 (when (and (bolp) subtreep
21588 (not (setq swallowp
21589 (org-yank-folding-would-swallow-text beg end))))
21590 (org-with-limited-levels
21591 (or (looking-at org-outline-regexp)
21592 (re-search-forward org-outline-regexp-bol end t))
21593 (while (and (< (point) end) (looking-at org-outline-regexp))
21594 (hide-subtree)
21595 (org-cycle-show-empty-lines 'folded)
21596 (condition-case nil
21597 (outline-forward-same-level 1)
21598 (error (goto-char end))))))
21599 (when swallowp
21600 (message
21601 "Inserted text not folded because that would swallow text"))
21603 (goto-char end)
21604 (skip-chars-forward " \t\n\r")
21605 (beginning-of-line 1)
21606 (push-mark beg 'nomsg)))
21607 ((and subtreep org-yank-adjusted-subtrees)
21608 (let ((beg (point-at-bol)))
21609 (org-paste-subtree nil nil 'for-yank)
21610 (push-mark beg 'nomsg)))
21612 (call-interactively command))))))
21614 (defun org-yank-folding-would-swallow-text (beg end)
21615 "Would hide-subtree at BEG swallow any text after END?"
21616 (let (level)
21617 (org-with-limited-levels
21618 (save-excursion
21619 (goto-char beg)
21620 (when (or (looking-at org-outline-regexp)
21621 (re-search-forward org-outline-regexp-bol end t))
21622 (setq level (org-outline-level)))
21623 (goto-char end)
21624 (skip-chars-forward " \t\r\n\v\f")
21625 (if (or (eobp)
21626 (and (bolp) (looking-at org-outline-regexp)
21627 (<= (org-outline-level) level)))
21628 nil ; Nothing would be swallowed
21629 t))))) ; something would swallow
21631 (define-key org-mode-map "\C-y" 'org-yank)
21633 (defun org-truely-invisible-p ()
21634 "Check if point is at a character currently not visible.
21635 This version does not only check the character property, but also
21636 `visible-mode'."
21637 ;; Early versions of noutline don't have `outline-invisible-p'.
21638 (if (org-bound-and-true-p visible-mode)
21640 (outline-invisible-p)))
21642 (defun org-invisible-p2 ()
21643 "Check if point is at a character currently not visible."
21644 (save-excursion
21645 (if (and (eolp) (not (bobp))) (backward-char 1))
21646 ;; Early versions of noutline don't have `outline-invisible-p'.
21647 (outline-invisible-p)))
21649 (defun org-back-to-heading (&optional invisible-ok)
21650 "Call `outline-back-to-heading', but provide a better error message."
21651 (condition-case nil
21652 (outline-back-to-heading invisible-ok)
21653 (error (error "Before first headline at position %d in buffer %s"
21654 (point) (current-buffer)))))
21656 (defun org-before-first-heading-p ()
21657 "Before first heading?"
21658 (save-excursion
21659 (end-of-line)
21660 (null (re-search-backward org-outline-regexp-bol nil t))))
21662 (defun org-at-heading-p (&optional ignored)
21663 (outline-on-heading-p t))
21664 ;; Compatibility alias with Org versions < 7.8.03
21665 (defalias 'org-on-heading-p 'org-at-heading-p)
21667 (defun org-at-comment-p nil
21668 "Is cursor in a line starting with a # character?"
21669 (save-excursion
21670 (beginning-of-line)
21671 (looking-at "^#")))
21673 (defun org-at-drawer-p nil
21674 "Is cursor at a drawer keyword?"
21675 (save-excursion
21676 (move-beginning-of-line 1)
21677 (looking-at org-drawer-regexp)))
21679 (defun org-at-block-p nil
21680 "Is cursor at a block keyword?"
21681 (save-excursion
21682 (move-beginning-of-line 1)
21683 (looking-at org-block-regexp)))
21685 (defun org-point-at-end-of-empty-headline ()
21686 "If point is at the end of an empty headline, return t, else nil.
21687 If the heading only contains a TODO keyword, it is still still considered
21688 empty."
21689 (and (looking-at "[ \t]*$")
21690 (when org-todo-line-regexp
21691 (save-excursion
21692 (beginning-of-line 1)
21693 (let ((case-fold-search nil))
21694 (looking-at org-todo-line-regexp)
21695 (string= (match-string 3) ""))))))
21697 (defun org-at-heading-or-item-p ()
21698 (or (org-at-heading-p) (org-at-item-p)))
21700 (defun org-at-target-p ()
21701 (or (org-in-regexp org-radio-target-regexp)
21702 (org-in-regexp org-target-regexp)))
21703 ;; Compatibility alias with Org versions < 7.8.03
21704 (defalias 'org-on-target-p 'org-at-target-p)
21706 (defun org-up-heading-all (arg)
21707 "Move to the heading line of which the present line is a subheading.
21708 This function considers both visible and invisible heading lines.
21709 With argument, move up ARG levels."
21710 (if (fboundp 'outline-up-heading-all)
21711 (outline-up-heading-all arg) ; emacs 21 version of outline.el
21712 (outline-up-heading arg t))) ; emacs 22 version of outline.el
21714 (defun org-up-heading-safe ()
21715 "Move to the heading line of which the present line is a subheading.
21716 This version will not throw an error. It will return the level of the
21717 headline found, or nil if no higher level is found.
21719 Also, this function will be a lot faster than `outline-up-heading',
21720 because it relies on stars being the outline starters. This can really
21721 make a significant difference in outlines with very many siblings."
21722 (let (start-level re)
21723 (org-back-to-heading t)
21724 (setq start-level (funcall outline-level))
21725 (if (equal start-level 1)
21727 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
21728 (if (re-search-backward re nil t)
21729 (funcall outline-level)))))
21731 (defun org-first-sibling-p ()
21732 "Is this heading the first child of its parents?"
21733 (interactive)
21734 (let ((re org-outline-regexp-bol)
21735 level l)
21736 (unless (org-at-heading-p t)
21737 (error "Not at a heading"))
21738 (setq level (funcall outline-level))
21739 (save-excursion
21740 (if (not (re-search-backward re nil t))
21742 (setq l (funcall outline-level))
21743 (< l level)))))
21745 (defun org-goto-sibling (&optional previous)
21746 "Goto the next sibling, even if it is invisible.
21747 When PREVIOUS is set, go to the previous sibling instead. Returns t
21748 when a sibling was found. When none is found, return nil and don't
21749 move point."
21750 (let ((fun (if previous 're-search-backward 're-search-forward))
21751 (pos (point))
21752 (re org-outline-regexp-bol)
21753 level l)
21754 (when (condition-case nil (org-back-to-heading t) (error nil))
21755 (setq level (funcall outline-level))
21756 (catch 'exit
21757 (or previous (forward-char 1))
21758 (while (funcall fun re nil t)
21759 (setq l (funcall outline-level))
21760 (when (< l level) (goto-char pos) (throw 'exit nil))
21761 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
21762 (goto-char pos)
21763 nil))))
21765 (defun org-show-siblings ()
21766 "Show all siblings of the current headline."
21767 (save-excursion
21768 (while (org-goto-sibling) (org-flag-heading nil)))
21769 (save-excursion
21770 (while (org-goto-sibling 'previous)
21771 (org-flag-heading nil))))
21773 (defun org-goto-first-child ()
21774 "Goto the first child, even if it is invisible.
21775 Return t when a child was found. Otherwise don't move point and
21776 return nil."
21777 (let (level (pos (point)) (re org-outline-regexp-bol))
21778 (when (condition-case nil (org-back-to-heading t) (error nil))
21779 (setq level (outline-level))
21780 (forward-char 1)
21781 (if (and (re-search-forward re nil t) (> (outline-level) level))
21782 (progn (goto-char (match-beginning 0)) t)
21783 (goto-char pos) nil))))
21785 (defun org-show-hidden-entry ()
21786 "Show an entry where even the heading is hidden."
21787 (save-excursion
21788 (org-show-entry)))
21790 (defun org-flag-heading (flag &optional entry)
21791 "Flag the current heading. FLAG non-nil means make invisible.
21792 When ENTRY is non-nil, show the entire entry."
21793 (save-excursion
21794 (org-back-to-heading t)
21795 ;; Check if we should show the entire entry
21796 (if entry
21797 (progn
21798 (org-show-entry)
21799 (save-excursion
21800 (and (outline-next-heading)
21801 (org-flag-heading nil))))
21802 (outline-flag-region (max (point-min) (1- (point)))
21803 (save-excursion (outline-end-of-heading) (point))
21804 flag))))
21806 (defun org-get-next-sibling ()
21807 "Move to next heading of the same level, and return point.
21808 If there is no such heading, return nil.
21809 This is like outline-next-sibling, but invisible headings are ok."
21810 (let ((level (funcall outline-level)))
21811 (outline-next-heading)
21812 (while (and (not (eobp)) (> (funcall outline-level) level))
21813 (outline-next-heading))
21814 (if (or (eobp) (< (funcall outline-level) level))
21816 (point))))
21818 (defun org-get-last-sibling ()
21819 "Move to previous heading of the same level, and return point.
21820 If there is no such heading, return nil."
21821 (let ((opoint (point))
21822 (level (funcall outline-level)))
21823 (outline-previous-heading)
21824 (when (and (/= (point) opoint) (outline-on-heading-p t))
21825 (while (and (> (funcall outline-level) level)
21826 (not (bobp)))
21827 (outline-previous-heading))
21828 (if (< (funcall outline-level) level)
21830 (point)))))
21832 (defun org-end-of-subtree (&optional invisible-ok to-heading)
21833 "Goto to the end of a subtree."
21834 ;; This contains an exact copy of the original function, but it uses
21835 ;; `org-back-to-heading', to make it work also in invisible
21836 ;; trees. And is uses an invisible-ok argument.
21837 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
21838 ;; Furthermore, when used inside Org, finding the end of a large subtree
21839 ;; with many children and grandchildren etc, this can be much faster
21840 ;; than the outline version.
21841 (org-back-to-heading invisible-ok)
21842 (let ((first t)
21843 (level (funcall outline-level)))
21844 (if (and (derived-mode-p 'org-mode) (< level 1000))
21845 ;; A true heading (not a plain list item), in Org-mode
21846 ;; This means we can easily find the end by looking
21847 ;; only for the right number of stars. Using a regexp to do
21848 ;; this is so much faster than using a Lisp loop.
21849 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
21850 (forward-char 1)
21851 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
21852 ;; something else, do it the slow way
21853 (while (and (not (eobp))
21854 (or first (> (funcall outline-level) level)))
21855 (setq first nil)
21856 (outline-next-heading)))
21857 (unless to-heading
21858 (if (memq (preceding-char) '(?\n ?\^M))
21859 (progn
21860 ;; Go to end of line before heading
21861 (forward-char -1)
21862 (if (memq (preceding-char) '(?\n ?\^M))
21863 ;; leave blank line before heading
21864 (forward-char -1))))))
21865 (point))
21867 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
21868 "Use Org version in org-mode, for dramatic speed-up."
21869 (if (derived-mode-p 'org-mode)
21870 (progn
21871 (org-end-of-subtree nil t)
21872 (unless (eobp) (backward-char 1)))
21873 ad-do-it))
21875 (defun org-end-of-meta-data-and-drawers ()
21876 "Jump to the first text after meta data and drawers in the current entry.
21877 This will move over empty lines, lines with planning time stamps,
21878 clocking lines, and drawers."
21879 (org-back-to-heading t)
21880 (let ((end (save-excursion (outline-next-heading) (point)))
21881 (re (concat "\\(" org-drawer-regexp "\\)"
21882 "\\|" "[ \t]*" org-keyword-time-regexp)))
21883 (forward-line 1)
21884 (while (re-search-forward re end t)
21885 (if (not (match-end 1))
21886 ;; empty or planning line
21887 (forward-line 1)
21888 ;; a drawer, find the end
21889 (re-search-forward "^[ \t]*:END:" end 'move)
21890 (forward-line 1)))
21891 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
21892 (point)))
21894 (defun org-forward-heading-same-level (arg &optional invisible-ok)
21895 "Move forward to the arg'th subheading at same level as this one.
21896 Stop at the first and last subheadings of a superior heading.
21897 Normally this only looks at visible headings, but when INVISIBLE-OK is
21898 non-nil it will also look at invisible ones."
21899 (interactive "p")
21900 (org-back-to-heading invisible-ok)
21901 (org-at-heading-p)
21902 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21903 (re (format "^\\*\\{1,%d\\} " level))
21905 (forward-char 1)
21906 (while (> arg 0)
21907 (while (and (re-search-forward re nil 'move)
21908 (setq l (- (match-end 0) (match-beginning 0) 1))
21909 (= l level)
21910 (not invisible-ok)
21911 (progn (backward-char 1) (outline-invisible-p)))
21912 (if (< l level) (setq arg 1)))
21913 (setq arg (1- arg)))
21914 (beginning-of-line 1)))
21916 (defun org-backward-heading-same-level (arg &optional invisible-ok)
21917 "Move backward to the arg'th subheading at same level as this one.
21918 Stop at the first and last subheadings of a superior heading."
21919 (interactive "p")
21920 (org-back-to-heading)
21921 (org-at-heading-p)
21922 (let* ((level (- (match-end 0) (match-beginning 0) 1))
21923 (re (format "^\\*\\{1,%d\\} " level))
21925 (while (> arg 0)
21926 (while (and (re-search-backward re nil 'move)
21927 (setq l (- (match-end 0) (match-beginning 0) 1))
21928 (= l level)
21929 (not invisible-ok)
21930 (outline-invisible-p))
21931 (if (< l level) (setq arg 1)))
21932 (setq arg (1- arg)))))
21934 ;;;###autoload
21935 (defun org-forward-element ()
21936 "Move forward by one element.
21937 Move to the next element at the same level, when possible."
21938 (interactive)
21939 (cond ((eobp) (error "Cannot move further down"))
21940 ((org-with-limited-levels (org-at-heading-p))
21941 (let ((origin (point)))
21942 (org-forward-heading-same-level 1)
21943 (unless (org-with-limited-levels (org-at-heading-p))
21944 (goto-char origin)
21945 (error "Cannot move further down"))))
21947 (let* ((elem (org-element-at-point))
21948 (end (org-element-property :end elem))
21949 (parent (org-element-property :parent elem)))
21950 (if (and parent (= (org-element-property :contents-end parent) end))
21951 (goto-char (org-element-property :end parent))
21952 (goto-char end))))))
21954 ;;;###autoload
21955 (defun org-backward-element ()
21956 "Move backward by one element.
21957 Move to the previous element at the same level, when possible."
21958 (interactive)
21959 (cond ((bobp) (error "Cannot move further up"))
21960 ((org-with-limited-levels (org-at-heading-p))
21961 ;; At an headline, move to the previous one, if any, or stay
21962 ;; here.
21963 (let ((origin (point)))
21964 (org-backward-heading-same-level 1)
21965 (unless (org-with-limited-levels (org-at-heading-p))
21966 (goto-char origin)
21967 (error "Cannot move further up"))))
21969 (let* ((trail (org-element-at-point 'keep-trail))
21970 (elem (car trail))
21971 (prev-elem (nth 1 trail))
21972 (beg (org-element-property :begin elem)))
21973 (cond
21974 ;; Move to beginning of current element if point isn't
21975 ;; there already.
21976 ((/= (point) beg) (goto-char beg))
21977 (prev-elem (goto-char (org-element-property :begin prev-elem)))
21978 ((org-before-first-heading-p) (goto-char (point-min)))
21979 (t (org-back-to-heading)))))))
21981 ;;;###autoload
21982 (defun org-up-element ()
21983 "Move to upper element."
21984 (interactive)
21985 (if (org-with-limited-levels (org-at-heading-p))
21986 (unless (org-up-heading-safe) (error "No surrounding element"))
21987 (let* ((elem (org-element-at-point))
21988 (parent (org-element-property :parent elem)))
21989 (if parent (goto-char (org-element-property :begin parent))
21990 (if (org-with-limited-levels (org-before-first-heading-p))
21991 (error "No surrounding element")
21992 (org-with-limited-levels (org-back-to-heading)))))))
21994 ;;;###autoload
21995 (defvar org-element-greater-elements)
21996 (defun org-down-element ()
21997 "Move to inner element."
21998 (interactive)
21999 (let ((element (org-element-at-point)))
22000 (cond
22001 ((memq (org-element-type element) '(plain-list table))
22002 (goto-char (org-element-property :contents-begin element))
22003 (forward-char))
22004 ((memq (org-element-type element) org-element-greater-elements)
22005 ;; If contents are hidden, first disclose them.
22006 (when (org-element-property :hiddenp element) (org-cycle))
22007 (goto-char (or (org-element-property :contents-begin element)
22008 (error "No content for this element"))))
22009 (t (error "No inner element")))))
22011 ;;;###autoload
22012 (defun org-drag-element-backward ()
22013 "Move backward element at point."
22014 (interactive)
22015 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22016 (let* ((trail (org-element-at-point 'keep-trail))
22017 (elem (car trail))
22018 (prev-elem (nth 1 trail)))
22019 ;; Error out if no previous element or previous element is
22020 ;; a parent of the current one.
22021 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22022 (error "Cannot drag element backward")
22023 (let ((pos (point)))
22024 (org-element-swap-A-B prev-elem elem)
22025 (goto-char (+ (org-element-property :begin prev-elem)
22026 (- pos (org-element-property :begin elem)))))))))
22028 ;;;###autoload
22029 (defun org-drag-element-forward ()
22030 "Move forward element at point."
22031 (interactive)
22032 (let* ((pos (point))
22033 (elem (org-element-at-point)))
22034 (when (= (point-max) (org-element-property :end elem))
22035 (error "Cannot drag element forward"))
22036 (goto-char (org-element-property :end elem))
22037 (let ((next-elem (org-element-at-point)))
22038 (when (or (org-element-nested-p elem next-elem)
22039 (and (eq (org-element-type next-elem) 'headline)
22040 (not (eq (org-element-type elem) 'headline))))
22041 (goto-char pos)
22042 (error "Cannot drag element forward"))
22043 ;; Compute new position of point: it's shifted by NEXT-ELEM
22044 ;; body's length (without final blanks) and by the length of
22045 ;; blanks between ELEM and NEXT-ELEM.
22046 (let ((size-next (- (save-excursion
22047 (goto-char (org-element-property :end next-elem))
22048 (skip-chars-backward " \r\t\n")
22049 (forward-line)
22050 ;; Small correction if buffer doesn't end
22051 ;; with a newline character.
22052 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22053 (org-element-property :begin next-elem)))
22054 (size-blank (- (org-element-property :end elem)
22055 (save-excursion
22056 (goto-char (org-element-property :end elem))
22057 (skip-chars-backward " \r\t\n")
22058 (forward-line)
22059 (point)))))
22060 (org-element-swap-A-B elem next-elem)
22061 (goto-char (+ pos size-next size-blank))))))
22063 ;;;###autoload
22064 (defun org-mark-element ()
22065 "Put point at beginning of this element, mark at end.
22067 Interactively, if this command is repeated or (in Transient Mark
22068 mode) if the mark is active, it marks the next element after the
22069 ones already marked."
22070 (interactive)
22071 (let (deactivate-mark)
22072 (if (and (org-called-interactively-p 'any)
22073 (or (and (eq last-command this-command) (mark t))
22074 (and transient-mark-mode mark-active)))
22075 (set-mark
22076 (save-excursion
22077 (goto-char (mark))
22078 (goto-char (org-element-property :end (org-element-at-point)))))
22079 (let ((element (org-element-at-point)))
22080 (end-of-line)
22081 (push-mark (org-element-property :end element) t t)
22082 (goto-char (org-element-property :begin element))))))
22084 ;;;###autoload
22085 (defun org-narrow-to-element ()
22086 "Narrow buffer to current element."
22087 (interactive)
22088 (let ((elem (org-element-at-point)))
22089 (cond
22090 ((eq (car elem) 'headline)
22091 (narrow-to-region
22092 (org-element-property :begin elem)
22093 (org-element-property :end elem)))
22094 ((memq (car elem) org-element-greater-elements)
22095 (narrow-to-region
22096 (org-element-property :contents-begin elem)
22097 (org-element-property :contents-end elem)))
22099 (narrow-to-region
22100 (org-element-property :begin elem)
22101 (org-element-property :end elem))))))
22103 ;;;###autoload
22104 (defun org-transpose-element ()
22105 "Transpose current and previous elements, keeping blank lines between.
22106 Point is moved after both elements."
22107 (interactive)
22108 (org-skip-whitespace)
22109 (let ((end (org-element-property :end (org-element-at-point))))
22110 (org-drag-element-backward)
22111 (goto-char end)))
22113 ;;;###autoload
22114 (defun org-unindent-buffer ()
22115 "Un-indent the visible part of the buffer.
22116 Relative indentation (between items, inside blocks, etc.) isn't
22117 modified."
22118 (interactive)
22119 (unless (eq major-mode 'org-mode)
22120 (error "Cannot un-indent a buffer not in Org mode"))
22121 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22122 unindent-tree ; For byte-compiler.
22123 (unindent-tree
22124 (function
22125 (lambda (contents)
22126 (mapc
22127 (lambda (element)
22128 (if (memq (org-element-type element) '(headline section))
22129 (funcall unindent-tree (org-element-contents element))
22130 (save-excursion
22131 (save-restriction
22132 (narrow-to-region
22133 (org-element-property :begin element)
22134 (org-element-property :end element))
22135 (org-do-remove-indentation)))))
22136 (reverse contents))))))
22137 (funcall unindent-tree (org-element-contents parse-tree))))
22139 (defun org-show-subtree ()
22140 "Show everything after this heading at deeper levels."
22141 (interactive)
22142 (outline-flag-region
22143 (point)
22144 (save-excursion
22145 (org-end-of-subtree t t))
22146 nil))
22148 (defun org-show-entry ()
22149 "Show the body directly following this heading.
22150 Show the heading too, if it is currently invisible."
22151 (interactive)
22152 (save-excursion
22153 (condition-case nil
22154 (progn
22155 (org-back-to-heading t)
22156 (outline-flag-region
22157 (max (point-min) (1- (point)))
22158 (save-excursion
22159 (if (re-search-forward
22160 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22161 (match-beginning 1)
22162 (point-max)))
22163 nil)
22164 (org-cycle-hide-drawers 'children))
22165 (error nil))))
22167 (defun org-make-options-regexp (kwds &optional extra)
22168 "Make a regular expression for keyword lines."
22169 (concat
22170 "^#\\+\\("
22171 (mapconcat 'regexp-quote kwds "\\|")
22172 (if extra (concat "\\|" extra))
22173 "\\):[ \t]*\\(.*\\)"))
22175 ;; Make isearch reveal the necessary context
22176 (defun org-isearch-end ()
22177 "Reveal context after isearch exits."
22178 (when isearch-success ; only if search was successful
22179 (if (featurep 'xemacs)
22180 ;; Under XEmacs, the hook is run in the correct place,
22181 ;; we directly show the context.
22182 (org-show-context 'isearch)
22183 ;; In Emacs the hook runs *before* restoring the overlays.
22184 ;; So we have to use a one-time post-command-hook to do this.
22185 ;; (Emacs 22 has a special variable, see function `org-mode')
22186 (unless (and (boundp 'isearch-mode-end-hook-quit)
22187 isearch-mode-end-hook-quit)
22188 ;; Only when the isearch was not quitted.
22189 (org-add-hook 'post-command-hook 'org-isearch-post-command
22190 'append 'local)))))
22192 (defun org-isearch-post-command ()
22193 "Remove self from hook, and show context."
22194 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22195 (org-show-context 'isearch))
22198 ;;;; Integration with and fixes for other packages
22200 ;;; Imenu support
22202 (defvar org-imenu-markers nil
22203 "All markers currently used by Imenu.")
22204 (make-variable-buffer-local 'org-imenu-markers)
22206 (defun org-imenu-new-marker (&optional pos)
22207 "Return a new marker for use by Imenu, and remember the marker."
22208 (let ((m (make-marker)))
22209 (move-marker m (or pos (point)))
22210 (push m org-imenu-markers)
22213 (defun org-imenu-get-tree ()
22214 "Produce the index for Imenu."
22215 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22216 (setq org-imenu-markers nil)
22217 (let* ((n org-imenu-depth)
22218 (re (concat "^" (org-get-limited-outline-regexp)))
22219 (subs (make-vector (1+ n) nil))
22220 (last-level 0)
22221 m level head)
22222 (save-excursion
22223 (save-restriction
22224 (widen)
22225 (goto-char (point-max))
22226 (while (re-search-backward re nil t)
22227 (setq level (org-reduced-level (funcall outline-level)))
22228 (when (and (<= level n)
22229 (looking-at org-complex-heading-regexp))
22230 (setq head (org-link-display-format
22231 (org-match-string-no-properties 4))
22232 m (org-imenu-new-marker))
22233 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22234 (if (>= level last-level)
22235 (push (cons head m) (aref subs level))
22236 (push (cons head (aref subs (1+ level))) (aref subs level))
22237 (loop for i from (1+ level) to n do (aset subs i nil)))
22238 (setq last-level level)))))
22239 (aref subs 1)))
22241 (eval-after-load "imenu"
22242 '(progn
22243 (add-hook 'imenu-after-jump-hook
22244 (lambda ()
22245 (if (derived-mode-p 'org-mode)
22246 (org-show-context 'org-goto))))))
22248 (defun org-link-display-format (link)
22249 "Replace a link with either the description, or the link target
22250 if no description is present"
22251 (save-match-data
22252 (if (string-match org-bracket-link-analytic-regexp link)
22253 (replace-match (if (match-end 5)
22254 (match-string 5 link)
22255 (concat (match-string 1 link)
22256 (match-string 3 link)))
22257 nil t link)
22258 link)))
22260 (defun org-toggle-link-display ()
22261 "Toggle the literal or descriptive display of links."
22262 (interactive)
22263 (if org-descriptive-links
22264 (progn (org-remove-from-invisibility-spec '(org-link))
22265 (org-restart-font-lock)
22266 (setq org-descriptive-links nil))
22267 (progn (add-to-invisibility-spec '(org-link))
22268 (org-restart-font-lock)
22269 (setq org-descriptive-links t))))
22271 ;; Speedbar support
22273 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22274 "Overlay marking the agenda restriction line in speedbar.")
22275 (overlay-put org-speedbar-restriction-lock-overlay
22276 'face 'org-agenda-restriction-lock)
22277 (overlay-put org-speedbar-restriction-lock-overlay
22278 'help-echo "Agendas are currently limited to this item.")
22279 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22281 (defun org-speedbar-set-agenda-restriction ()
22282 "Restrict future agenda commands to the location at point in speedbar.
22283 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22284 (interactive)
22285 (require 'org-agenda)
22286 (let (p m tp np dir txt)
22287 (cond
22288 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22289 'org-imenu t))
22290 (setq m (get-text-property p 'org-imenu-marker))
22291 (with-current-buffer (marker-buffer m)
22292 (goto-char m)
22293 (org-agenda-set-restriction-lock 'subtree)))
22294 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22295 'speedbar-function 'speedbar-find-file))
22296 (setq tp (previous-single-property-change
22297 (1+ p) 'speedbar-function)
22298 np (next-single-property-change
22299 tp 'speedbar-function)
22300 dir (speedbar-line-directory)
22301 txt (buffer-substring-no-properties (or tp (point-min))
22302 (or np (point-max))))
22303 (with-current-buffer (find-file-noselect
22304 (let ((default-directory dir))
22305 (expand-file-name txt)))
22306 (unless (derived-mode-p 'org-mode)
22307 (error "Cannot restrict to non-Org-mode file"))
22308 (org-agenda-set-restriction-lock 'file)))
22309 (t (error "Don't know how to restrict Org-mode's agenda")))
22310 (move-overlay org-speedbar-restriction-lock-overlay
22311 (point-at-bol) (point-at-eol))
22312 (setq current-prefix-arg nil)
22313 (org-agenda-maybe-redo)))
22315 (eval-after-load "speedbar"
22316 '(progn
22317 (speedbar-add-supported-extension ".org")
22318 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22319 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22320 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22321 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22322 (add-hook 'speedbar-visiting-tag-hook
22323 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22325 ;;; Fixes and Hacks for problems with other packages
22327 ;; Make flyspell not check words in links, to not mess up our keymap
22328 (defun org-mode-flyspell-verify ()
22329 "Don't let flyspell put overlays at active buttons, or on
22330 {todo,all-time,additional-option-like}-keywords."
22331 (let ((pos (max (1- (point)) (point-min)))
22332 (word (thing-at-point 'word)))
22333 (and (not (get-text-property pos 'keymap))
22334 (not (get-text-property pos 'org-no-flyspell))
22335 (not (member word org-todo-keywords-1))
22336 (not (member word org-all-time-keywords))
22337 (not (member word org-options-keywords))
22338 (not (member word (mapcar 'car org-startup-options)))
22339 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22341 (defun org-remove-flyspell-overlays-in (beg end)
22342 "Remove flyspell overlays in region."
22343 (and (org-bound-and-true-p flyspell-mode)
22344 (fboundp 'flyspell-delete-region-overlays)
22345 (flyspell-delete-region-overlays beg end))
22346 (add-text-properties beg end '(org-no-flyspell t)))
22348 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22349 (eval-after-load "bookmark"
22350 '(if (boundp 'bookmark-after-jump-hook)
22351 ;; We can use the hook
22352 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22353 ;; Hook not available, use advice
22354 (defadvice bookmark-jump (after org-make-visible activate)
22355 "Make the position visible."
22356 (org-bookmark-jump-unhide))))
22358 ;; Make sure saveplace shows the location if it was hidden
22359 (eval-after-load "saveplace"
22360 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22361 "Make the position visible."
22362 (org-bookmark-jump-unhide)))
22364 ;; Make sure ecb shows the location if it was hidden
22365 (eval-after-load "ecb"
22366 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22367 "Make hierarchy visible when jumping into location from ECB tree buffer."
22368 (if (derived-mode-p 'org-mode)
22369 (org-show-context))))
22371 (defun org-bookmark-jump-unhide ()
22372 "Unhide the current position, to show the bookmark location."
22373 (and (derived-mode-p 'org-mode)
22374 (or (outline-invisible-p)
22375 (save-excursion (goto-char (max (point-min) (1- (point))))
22376 (outline-invisible-p)))
22377 (org-show-context 'bookmark-jump)))
22379 ;; Make session.el ignore our circular variable
22380 (eval-after-load "session"
22381 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22383 ;;;; Experimental code
22385 (defun org-closed-in-range ()
22386 "Sparse tree of items closed in a certain time range.
22387 Still experimental, may disappear in the future."
22388 (interactive)
22389 ;; Get the time interval from the user.
22390 (let* ((time1 (org-float-time
22391 (org-read-date nil 'to-time nil "Starting date: ")))
22392 (time2 (org-float-time
22393 (org-read-date nil 'to-time nil "End date:")))
22394 ;; callback function
22395 (callback (lambda ()
22396 (let ((time
22397 (org-float-time
22398 (apply 'encode-time
22399 (org-parse-time-string
22400 (match-string 1))))))
22401 ;; check if time in interval
22402 (and (>= time time1) (<= time time2))))))
22403 ;; make tree, check each match with the callback
22404 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22406 ;;;; Finish up
22408 (provide 'org)
22410 (run-hooks 'org-load-hook)
22412 ;;; org.el ends here